Plater.pm 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103
  1. # The "Plater" tab. It contains the "3D", "2D", "Preview" and "Layers" subtabs.
  2. package Slic3r::GUI::Plater;
  3. use strict;
  4. use warnings;
  5. use utf8;
  6. use File::Basename qw(basename dirname);
  7. use List::Util qw(sum first max);
  8. use Slic3r::Geometry qw(X Y Z scale unscale deg2rad rad2deg);
  9. use LWP::UserAgent;
  10. use threads::shared qw(shared_clone);
  11. use Wx qw(:button :colour :cursor :dialog :filedialog :keycode :icon :font :id :listctrl :misc
  12. :panel :sizer :toolbar :window wxTheApp :notebook :combobox wxNullBitmap);
  13. use Wx::Event qw(EVT_BUTTON EVT_TOGGLEBUTTON EVT_COMMAND EVT_KEY_DOWN EVT_LIST_ITEM_ACTIVATED
  14. EVT_LIST_ITEM_DESELECTED EVT_LIST_ITEM_SELECTED EVT_LEFT_DOWN EVT_MOUSE_EVENTS EVT_PAINT EVT_TOOL
  15. EVT_CHOICE EVT_COMBOBOX EVT_TIMER EVT_NOTEBOOK_PAGE_CHANGED);
  16. use base 'Wx::Panel';
  17. use constant TB_ADD => &Wx::NewId;
  18. use constant TB_REMOVE => &Wx::NewId;
  19. use constant TB_RESET => &Wx::NewId;
  20. use constant TB_ARRANGE => &Wx::NewId;
  21. use constant TB_EXPORT_GCODE => &Wx::NewId;
  22. use constant TB_EXPORT_STL => &Wx::NewId;
  23. use constant TB_MORE => &Wx::NewId;
  24. use constant TB_FEWER => &Wx::NewId;
  25. use constant TB_45CW => &Wx::NewId;
  26. use constant TB_45CCW => &Wx::NewId;
  27. use constant TB_SCALE => &Wx::NewId;
  28. use constant TB_SPLIT => &Wx::NewId;
  29. use constant TB_CUT => &Wx::NewId;
  30. use constant TB_SETTINGS => &Wx::NewId;
  31. use constant TB_LAYER_EDITING => &Wx::NewId;
  32. # package variables to avoid passing lexicals to threads
  33. our $PROGRESS_BAR_EVENT : shared = Wx::NewEventType;
  34. our $ERROR_EVENT : shared = Wx::NewEventType;
  35. # Emitted from the worker thread when the G-code export is finished.
  36. our $EXPORT_COMPLETED_EVENT : shared = Wx::NewEventType;
  37. our $PROCESS_COMPLETED_EVENT : shared = Wx::NewEventType;
  38. use constant FILAMENT_CHOOSERS_SPACING => 0;
  39. use constant PROCESS_DELAY => 0.5 * 1000; # milliseconds
  40. my $PreventListEvents = 0;
  41. sub new {
  42. my ($class, $parent) = @_;
  43. my $self = $class->SUPER::new($parent, -1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
  44. $self->{config} = Slic3r::Config::new_from_defaults_keys([qw(
  45. bed_shape complete_objects extruder_clearance_radius skirts skirt_distance brim_width variable_layer_height
  46. serial_port serial_speed octoprint_host octoprint_apikey
  47. nozzle_diameter single_extruder_multi_material
  48. wipe_tower wipe_tower_x wipe_tower_y wipe_tower_width wipe_tower_per_color_wipe extruder_colour filament_colour
  49. )]);
  50. # C++ Slic3r::Model with Perl extensions in Slic3r/Model.pm
  51. $self->{model} = Slic3r::Model->new;
  52. # C++ Slic3r::Print with Perl extensions in Slic3r/Print.pm
  53. $self->{print} = Slic3r::Print->new;
  54. # List of Perl objects Slic3r::GUI::Plater::Object, representing a 2D preview of the platter.
  55. $self->{objects} = [];
  56. $self->{print}->set_status_cb(sub {
  57. my ($percent, $message) = @_;
  58. Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROGRESS_BAR_EVENT, shared_clone([$percent, $message])));
  59. });
  60. # Initialize preview notebook
  61. $self->{preview_notebook} = Wx::Notebook->new($self, -1, wxDefaultPosition, [335,335], wxNB_BOTTOM);
  62. # Initialize handlers for canvases
  63. my $on_select_object = sub {
  64. my ($obj_idx) = @_;
  65. # Ignore the special objects (the wipe tower proxy and such).
  66. $self->select_object((defined($obj_idx) && $obj_idx < 1000) ? $obj_idx : undef);
  67. };
  68. my $on_double_click = sub {
  69. $self->object_settings_dialog if $self->selected_object;
  70. };
  71. my $on_right_click = sub {
  72. my ($canvas, $click_pos) = @_;
  73. my ($obj_idx, $object) = $self->selected_object;
  74. return if !defined $obj_idx;
  75. my $menu = $self->object_menu;
  76. $canvas->PopupMenu($menu, $click_pos);
  77. $menu->Destroy;
  78. };
  79. my $on_instances_moved = sub {
  80. $self->update;
  81. };
  82. # Initialize 3D plater
  83. if ($Slic3r::GUI::have_OpenGL) {
  84. $self->{canvas3D} = Slic3r::GUI::Plater::3D->new($self->{preview_notebook}, $self->{objects}, $self->{model}, $self->{print}, $self->{config});
  85. $self->{preview_notebook}->AddPage($self->{canvas3D}, '3D');
  86. $self->{canvas3D}->set_on_select_object($on_select_object);
  87. $self->{canvas3D}->set_on_double_click($on_double_click);
  88. $self->{canvas3D}->set_on_right_click(sub { $on_right_click->($self->{canvas3D}, @_); });
  89. $self->{canvas3D}->set_on_rotate_object_left(sub { $self->rotate(-45, Z, 'relative') });
  90. $self->{canvas3D}->set_on_rotate_object_right(sub { $self->rotate( 45, Z, 'relative') });
  91. $self->{canvas3D}->set_on_scale_object_uniformly(sub { $self->changescale(undef) });
  92. $self->{canvas3D}->set_on_increase_objects(sub { $self->increase() });
  93. $self->{canvas3D}->set_on_decrease_objects(sub { $self->decrease() });
  94. $self->{canvas3D}->set_on_remove_object(sub { $self->remove() });
  95. $self->{canvas3D}->set_on_instances_moved($on_instances_moved);
  96. $self->{canvas3D}->set_on_wipe_tower_moved(sub {
  97. my ($new_pos_3f) = @_;
  98. my $cfg = Slic3r::Config->new;
  99. $cfg->set('wipe_tower_x', $new_pos_3f->x);
  100. $cfg->set('wipe_tower_y', $new_pos_3f->y);
  101. $self->GetFrame->{options_tabs}{print}->load_config($cfg);
  102. });
  103. $self->{canvas3D}->set_on_model_update(sub {
  104. if (wxTheApp->{app_config}->get("background_processing")) {
  105. $self->schedule_background_process;
  106. } else {
  107. # Hide the print info box, it is no more valid.
  108. $self->{"print_info_box_show"}->(0);
  109. }
  110. });
  111. $self->{canvas3D}->on_viewport_changed(sub {
  112. $self->{preview3D}->canvas->set_viewport_from_scene($self->{canvas3D});
  113. });
  114. }
  115. # Initialize 2D preview canvas
  116. $self->{canvas} = Slic3r::GUI::Plater::2D->new($self->{preview_notebook}, wxDefaultSize, $self->{objects}, $self->{model}, $self->{config});
  117. $self->{preview_notebook}->AddPage($self->{canvas}, '2D');
  118. $self->{canvas}->on_select_object($on_select_object);
  119. $self->{canvas}->on_double_click($on_double_click);
  120. $self->{canvas}->on_right_click(sub { $on_right_click->($self->{canvas}, @_); });
  121. $self->{canvas}->on_instances_moved($on_instances_moved);
  122. # Initialize 3D toolpaths preview
  123. if ($Slic3r::GUI::have_OpenGL) {
  124. $self->{preview3D} = Slic3r::GUI::Plater::3DPreview->new($self->{preview_notebook}, $self->{print}, $self->{config});
  125. $self->{preview3D}->canvas->on_viewport_changed(sub {
  126. $self->{canvas3D}->set_viewport_from_scene($self->{preview3D}->canvas);
  127. });
  128. $self->{preview_notebook}->AddPage($self->{preview3D}, 'Preview');
  129. $self->{preview3D_page_idx} = $self->{preview_notebook}->GetPageCount-1;
  130. }
  131. # Initialize toolpaths preview
  132. if ($Slic3r::GUI::have_OpenGL) {
  133. $self->{toolpaths2D} = Slic3r::GUI::Plater::2DToolpaths->new($self->{preview_notebook}, $self->{print});
  134. $self->{preview_notebook}->AddPage($self->{toolpaths2D}, 'Layers');
  135. }
  136. EVT_NOTEBOOK_PAGE_CHANGED($self, $self->{preview_notebook}, sub {
  137. my $preview = $self->{preview_notebook}->GetCurrentPage;
  138. $self->{preview3D}->load_print(1) if ($preview == $self->{preview3D});
  139. $preview->OnActivate if $preview->can('OnActivate');
  140. });
  141. # toolbar for object manipulation
  142. if (!&Wx::wxMSW) {
  143. Wx::ToolTip::Enable(1);
  144. $self->{htoolbar} = Wx::ToolBar->new($self, -1, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL | wxTB_TEXT | wxBORDER_SIMPLE | wxTAB_TRAVERSAL);
  145. $self->{htoolbar}->AddTool(TB_ADD, "Add…", Wx::Bitmap->new(Slic3r::var("brick_add.png"), wxBITMAP_TYPE_PNG), '');
  146. $self->{htoolbar}->AddTool(TB_REMOVE, "Delete", Wx::Bitmap->new(Slic3r::var("brick_delete.png"), wxBITMAP_TYPE_PNG), '');
  147. $self->{htoolbar}->AddTool(TB_RESET, "Delete All", Wx::Bitmap->new(Slic3r::var("cross.png"), wxBITMAP_TYPE_PNG), '');
  148. $self->{htoolbar}->AddTool(TB_ARRANGE, "Arrange", Wx::Bitmap->new(Slic3r::var("bricks.png"), wxBITMAP_TYPE_PNG), '');
  149. $self->{htoolbar}->AddSeparator;
  150. $self->{htoolbar}->AddTool(TB_MORE, "More", Wx::Bitmap->new(Slic3r::var("add.png"), wxBITMAP_TYPE_PNG), '');
  151. $self->{htoolbar}->AddTool(TB_FEWER, "Fewer", Wx::Bitmap->new(Slic3r::var("delete.png"), wxBITMAP_TYPE_PNG), '');
  152. $self->{htoolbar}->AddSeparator;
  153. $self->{htoolbar}->AddTool(TB_45CCW, "45° ccw", Wx::Bitmap->new(Slic3r::var("arrow_rotate_anticlockwise.png"), wxBITMAP_TYPE_PNG), '');
  154. $self->{htoolbar}->AddTool(TB_45CW, "45° cw", Wx::Bitmap->new(Slic3r::var("arrow_rotate_clockwise.png"), wxBITMAP_TYPE_PNG), '');
  155. $self->{htoolbar}->AddTool(TB_SCALE, "Scale…", Wx::Bitmap->new(Slic3r::var("arrow_out.png"), wxBITMAP_TYPE_PNG), '');
  156. $self->{htoolbar}->AddTool(TB_SPLIT, "Split", Wx::Bitmap->new(Slic3r::var("shape_ungroup.png"), wxBITMAP_TYPE_PNG), '');
  157. $self->{htoolbar}->AddTool(TB_CUT, "Cut…", Wx::Bitmap->new(Slic3r::var("package.png"), wxBITMAP_TYPE_PNG), '');
  158. $self->{htoolbar}->AddSeparator;
  159. $self->{htoolbar}->AddTool(TB_SETTINGS, "Settings…", Wx::Bitmap->new(Slic3r::var("cog.png"), wxBITMAP_TYPE_PNG), '');
  160. $self->{htoolbar}->AddTool(TB_LAYER_EDITING, 'Layer Editing', Wx::Bitmap->new(Slic3r::var("variable_layer_height.png"), wxBITMAP_TYPE_PNG), wxNullBitmap, 1, 0, 'Layer Editing');
  161. } else {
  162. my %tbar_buttons = (
  163. add => "Add…",
  164. remove => "Delete",
  165. reset => "Delete All",
  166. arrange => "Arrange",
  167. increase => "",
  168. decrease => "",
  169. rotate45ccw => "",
  170. rotate45cw => "",
  171. changescale => "Scale…",
  172. split => "Split",
  173. cut => "Cut…",
  174. settings => "Settings…",
  175. layer_editing => "Layer editing",
  176. );
  177. $self->{btoolbar} = Wx::BoxSizer->new(wxHORIZONTAL);
  178. for (qw(add remove reset arrange increase decrease rotate45ccw rotate45cw changescale split cut settings)) {
  179. $self->{"btn_$_"} = Wx::Button->new($self, -1, $tbar_buttons{$_}, wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
  180. $self->{btoolbar}->Add($self->{"btn_$_"});
  181. }
  182. $self->{"btn_layer_editing"} = Wx::ToggleButton->new($self, -1, $tbar_buttons{'layer_editing'}, wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
  183. $self->{btoolbar}->Add($self->{"btn_layer_editing"});
  184. }
  185. $self->{list} = Wx::ListView->new($self, -1, wxDefaultPosition, wxDefaultSize,
  186. wxLC_SINGLE_SEL | wxLC_REPORT | wxBORDER_SUNKEN | wxTAB_TRAVERSAL | wxWANTS_CHARS );
  187. $self->{list}->InsertColumn(0, "Name", wxLIST_FORMAT_LEFT, 145);
  188. $self->{list}->InsertColumn(1, "Copies", wxLIST_FORMAT_CENTER, 45);
  189. $self->{list}->InsertColumn(2, "Scale", wxLIST_FORMAT_CENTER, wxLIST_AUTOSIZE_USEHEADER);
  190. EVT_LIST_ITEM_SELECTED($self, $self->{list}, \&list_item_selected);
  191. EVT_LIST_ITEM_DESELECTED($self, $self->{list}, \&list_item_deselected);
  192. EVT_LIST_ITEM_ACTIVATED($self, $self->{list}, \&list_item_activated);
  193. EVT_KEY_DOWN($self->{list}, sub {
  194. my ($list, $event) = @_;
  195. if ($event->GetKeyCode == WXK_TAB) {
  196. $list->Navigate($event->ShiftDown ? &Wx::wxNavigateBackward : &Wx::wxNavigateForward);
  197. } else {
  198. $event->Skip;
  199. }
  200. });
  201. # right pane buttons
  202. $self->{btn_export_gcode} = Wx::Button->new($self, -1, "Export G-code…", wxDefaultPosition, [-1, 30], wxBU_LEFT);
  203. $self->{btn_reslice} = Wx::Button->new($self, -1, "Slice now", wxDefaultPosition, [-1, 30], wxBU_LEFT);
  204. $self->{btn_print} = Wx::Button->new($self, -1, "Print…", wxDefaultPosition, [-1, 30], wxBU_LEFT);
  205. $self->{btn_send_gcode} = Wx::Button->new($self, -1, "Send to printer", wxDefaultPosition, [-1, 30], wxBU_LEFT);
  206. $self->{btn_export_stl} = Wx::Button->new($self, -1, "Export STL…", wxDefaultPosition, [-1, 30], wxBU_LEFT);
  207. #$self->{btn_export_gcode}->SetFont($Slic3r::GUI::small_font);
  208. #$self->{btn_export_stl}->SetFont($Slic3r::GUI::small_font);
  209. $self->{btn_print}->Hide;
  210. $self->{btn_send_gcode}->Hide;
  211. my %icons = qw(
  212. add brick_add.png
  213. remove brick_delete.png
  214. reset cross.png
  215. arrange bricks.png
  216. export_gcode cog_go.png
  217. print arrow_up.png
  218. send_gcode arrow_up.png
  219. reslice reslice.png
  220. export_stl brick_go.png
  221. increase add.png
  222. decrease delete.png
  223. rotate45cw arrow_rotate_clockwise.png
  224. rotate45ccw arrow_rotate_anticlockwise.png
  225. changescale arrow_out.png
  226. split shape_ungroup.png
  227. cut package.png
  228. settings cog.png
  229. );
  230. for (grep $self->{"btn_$_"}, keys %icons) {
  231. $self->{"btn_$_"}->SetBitmap(Wx::Bitmap->new(Slic3r::var($icons{$_}), wxBITMAP_TYPE_PNG));
  232. }
  233. $self->selection_changed(0);
  234. $self->object_list_changed;
  235. EVT_BUTTON($self, $self->{btn_export_gcode}, sub {
  236. $self->export_gcode;
  237. });
  238. EVT_BUTTON($self, $self->{btn_print}, sub {
  239. $self->{print_file} = $self->export_gcode(Wx::StandardPaths::Get->GetTempDir());
  240. });
  241. EVT_BUTTON($self, $self->{btn_send_gcode}, sub {
  242. $self->{send_gcode_file} = $self->export_gcode(Wx::StandardPaths::Get->GetTempDir());
  243. });
  244. EVT_BUTTON($self, $self->{btn_reslice}, \&reslice);
  245. EVT_BUTTON($self, $self->{btn_export_stl}, \&export_stl);
  246. if ($self->{htoolbar}) {
  247. EVT_TOOL($self, TB_ADD, sub { $self->add; });
  248. EVT_TOOL($self, TB_REMOVE, sub { $self->remove() }); # explicitly pass no argument to remove
  249. EVT_TOOL($self, TB_RESET, sub { $self->reset; });
  250. EVT_TOOL($self, TB_ARRANGE, sub { $self->arrange; });
  251. EVT_TOOL($self, TB_MORE, sub { $self->increase; });
  252. EVT_TOOL($self, TB_FEWER, sub { $self->decrease; });
  253. EVT_TOOL($self, TB_45CW, sub { $_[0]->rotate(-45, Z, 'relative') });
  254. EVT_TOOL($self, TB_45CCW, sub { $_[0]->rotate(45, Z, 'relative') });
  255. EVT_TOOL($self, TB_SCALE, sub { $self->changescale(undef); });
  256. EVT_TOOL($self, TB_SPLIT, sub { $self->split_object; });
  257. EVT_TOOL($self, TB_CUT, sub { $_[0]->object_cut_dialog });
  258. EVT_TOOL($self, TB_SETTINGS, sub { $_[0]->object_settings_dialog });
  259. EVT_TOOL($self, TB_LAYER_EDITING, sub {
  260. my $state = $self->{canvas3D}->layer_editing_enabled;
  261. $self->{htoolbar}->ToggleTool(TB_LAYER_EDITING, ! $state);
  262. $self->on_layer_editing_toggled(! $state);
  263. });
  264. } else {
  265. EVT_BUTTON($self, $self->{btn_add}, sub { $self->add; });
  266. EVT_BUTTON($self, $self->{btn_remove}, sub { $self->remove() }); # explicitly pass no argument to remove
  267. EVT_BUTTON($self, $self->{btn_reset}, sub { $self->reset; });
  268. EVT_BUTTON($self, $self->{btn_arrange}, sub { $self->arrange; });
  269. EVT_BUTTON($self, $self->{btn_increase}, sub { $self->increase; });
  270. EVT_BUTTON($self, $self->{btn_decrease}, sub { $self->decrease; });
  271. EVT_BUTTON($self, $self->{btn_rotate45cw}, sub { $_[0]->rotate(-45, Z, 'relative') });
  272. EVT_BUTTON($self, $self->{btn_rotate45ccw}, sub { $_[0]->rotate(45, Z, 'relative') });
  273. EVT_BUTTON($self, $self->{btn_changescale}, sub { $self->changescale(undef); });
  274. EVT_BUTTON($self, $self->{btn_split}, sub { $self->split_object; });
  275. EVT_BUTTON($self, $self->{btn_cut}, sub { $_[0]->object_cut_dialog });
  276. EVT_BUTTON($self, $self->{btn_settings}, sub { $_[0]->object_settings_dialog });
  277. EVT_TOGGLEBUTTON($self, $self->{btn_layer_editing}, sub { $self->on_layer_editing_toggled($self->{btn_layer_editing}->GetValue); });
  278. }
  279. $_->SetDropTarget(Slic3r::GUI::Plater::DropTarget->new($self))
  280. for grep defined($_),
  281. $self, $self->{canvas}, $self->{canvas3D}, $self->{preview3D}, $self->{list};
  282. EVT_COMMAND($self, -1, $PROGRESS_BAR_EVENT, sub {
  283. my ($self, $event) = @_;
  284. my ($percent, $message) = @{$event->GetData};
  285. $self->on_progress_event($percent, $message);
  286. });
  287. EVT_COMMAND($self, -1, $ERROR_EVENT, sub {
  288. my ($self, $event) = @_;
  289. Slic3r::GUI::show_error($self, @{$event->GetData});
  290. });
  291. EVT_COMMAND($self, -1, $EXPORT_COMPLETED_EVENT, sub {
  292. my ($self, $event) = @_;
  293. $self->on_export_completed($event->GetData);
  294. });
  295. EVT_COMMAND($self, -1, $PROCESS_COMPLETED_EVENT, sub {
  296. my ($self, $event) = @_;
  297. $self->on_process_completed($event->GetData);
  298. });
  299. {
  300. my $timer_id = Wx::NewId();
  301. $self->{apply_config_timer} = Wx::Timer->new($self, $timer_id);
  302. EVT_TIMER($self, $timer_id, sub {
  303. my ($self, $event) = @_;
  304. $self->async_apply_config;
  305. });
  306. }
  307. $self->{canvas}->update_bed_size;
  308. if ($self->{canvas3D}) {
  309. $self->{canvas3D}->update_bed_size;
  310. $self->{canvas3D}->zoom_to_bed;
  311. }
  312. if ($self->{preview3D}) {
  313. $self->{preview3D}->set_bed_shape($self->{config}->bed_shape);
  314. }
  315. $self->update;
  316. {
  317. my $presets;
  318. {
  319. $presets = $self->{presets_sizer} = Wx::FlexGridSizer->new(3, 2, 1, 2);
  320. $presets->AddGrowableCol(1, 1);
  321. $presets->SetFlexibleDirection(wxHORIZONTAL);
  322. my %group_labels = (
  323. print => 'Print settings',
  324. filament => 'Filament',
  325. printer => 'Printer',
  326. );
  327. # UI Combo boxes for a print, multiple filaments, and a printer.
  328. # Initially a single filament combo box is created, but the number of combo boxes for the filament selection may increase,
  329. # once a printer preset with multiple extruders is activated.
  330. # $self->{preset_choosers}{$group}[$idx]
  331. $self->{preset_choosers} = {};
  332. for my $group (qw(print filament printer)) {
  333. my $text = Wx::StaticText->new($self, -1, "$group_labels{$group}:", wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT);
  334. $text->SetFont($Slic3r::GUI::small_font);
  335. my $choice = Wx::BitmapComboBox->new($self, -1, "", wxDefaultPosition, wxDefaultSize, [], wxCB_READONLY);
  336. EVT_LEFT_DOWN($choice, sub { $self->filament_color_box_lmouse_down(0, @_); } );
  337. $self->{preset_choosers}{$group} = [$choice];
  338. # setup the listener
  339. EVT_COMBOBOX($choice, $choice, sub {
  340. my ($choice) = @_;
  341. wxTheApp->CallAfter(sub {
  342. $self->_on_select_preset($group, $choice, 0);
  343. });
  344. });
  345. $presets->Add($text, 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL | wxRIGHT, 4);
  346. $presets->Add($choice, 1, wxALIGN_CENTER_VERTICAL | wxEXPAND | wxBOTTOM, 0);
  347. }
  348. }
  349. my $object_info_sizer;
  350. {
  351. my $box = Wx::StaticBox->new($self, -1, "Info");
  352. $object_info_sizer = Wx::StaticBoxSizer->new($box, wxVERTICAL);
  353. $object_info_sizer->SetMinSize([350,-1]);
  354. my $grid_sizer = Wx::FlexGridSizer->new(3, 4, 5, 5);
  355. $grid_sizer->SetFlexibleDirection(wxHORIZONTAL);
  356. $grid_sizer->AddGrowableCol(1, 1);
  357. $grid_sizer->AddGrowableCol(3, 1);
  358. $object_info_sizer->Add($grid_sizer, 0, wxEXPAND);
  359. my @info = (
  360. size => "Size",
  361. volume => "Volume",
  362. facets => "Facets",
  363. materials => "Materials",
  364. manifold => "Manifold",
  365. );
  366. while (my $field = shift @info) {
  367. my $label = shift @info;
  368. my $text = Wx::StaticText->new($self, -1, "$label:", wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT);
  369. $text->SetFont($Slic3r::GUI::small_font);
  370. $grid_sizer->Add($text, 0);
  371. $self->{"object_info_$field"} = Wx::StaticText->new($self, -1, "", wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT);
  372. $self->{"object_info_$field"}->SetFont($Slic3r::GUI::small_font);
  373. if ($field eq 'manifold') {
  374. $self->{object_info_manifold_warning_icon} = Wx::StaticBitmap->new($self, -1, Wx::Bitmap->new(Slic3r::var("error.png"), wxBITMAP_TYPE_PNG));
  375. $self->{object_info_manifold_warning_icon}->Hide;
  376. my $h_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
  377. $h_sizer->Add($self->{object_info_manifold_warning_icon}, 0);
  378. $h_sizer->Add($self->{"object_info_$field"}, 0);
  379. $grid_sizer->Add($h_sizer, 0, wxEXPAND);
  380. } else {
  381. $grid_sizer->Add($self->{"object_info_$field"}, 0);
  382. }
  383. }
  384. }
  385. my $print_info_sizer;
  386. {
  387. my $box = Wx::StaticBox->new($self, -1, "Sliced Info");
  388. $print_info_sizer = Wx::StaticBoxSizer->new($box, wxVERTICAL);
  389. $print_info_sizer->SetMinSize([350,-1]);
  390. my $grid_sizer = Wx::FlexGridSizer->new(2, 2, 5, 5);
  391. $grid_sizer->SetFlexibleDirection(wxHORIZONTAL);
  392. $grid_sizer->AddGrowableCol(1, 1);
  393. $grid_sizer->AddGrowableCol(3, 1);
  394. $print_info_sizer->Add($grid_sizer, 0, wxEXPAND);
  395. my @info = (
  396. fil_mm3 => "Used Filament (mm^3)",
  397. fil_g => "Used Filament (g)",
  398. cost => "Cost",
  399. );
  400. while (my $field = shift @info) {
  401. my $label = shift @info;
  402. my $text = Wx::StaticText->new($self, -1, "$label:", wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT);
  403. $text->SetFont($Slic3r::GUI::small_font);
  404. $grid_sizer->Add($text, 0);
  405. $self->{"print_info_$field"} = Wx::StaticText->new($self, -1, "", wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT);
  406. $self->{"print_info_$field"}->SetFont($Slic3r::GUI::small_font);
  407. $grid_sizer->Add($self->{"print_info_$field"}, 0);
  408. }
  409. }
  410. my $buttons_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
  411. $self->{buttons_sizer} = $buttons_sizer;
  412. $buttons_sizer->AddStretchSpacer(1);
  413. $buttons_sizer->Add($self->{btn_export_stl}, 0, wxALIGN_RIGHT, 0);
  414. $buttons_sizer->Add($self->{btn_reslice}, 0, wxALIGN_RIGHT, 0);
  415. $buttons_sizer->Add($self->{btn_print}, 0, wxALIGN_RIGHT, 0);
  416. $buttons_sizer->Add($self->{btn_send_gcode}, 0, wxALIGN_RIGHT, 0);
  417. $buttons_sizer->Add($self->{btn_export_gcode}, 0, wxALIGN_RIGHT, 0);
  418. my $right_sizer = Wx::BoxSizer->new(wxVERTICAL);
  419. $right_sizer->Add($presets, 0, wxEXPAND | wxTOP, 10) if defined $presets;
  420. $right_sizer->Add($buttons_sizer, 0, wxEXPAND | wxBOTTOM, 5);
  421. $right_sizer->Add($self->{list}, 1, wxEXPAND, 5);
  422. $right_sizer->Add($object_info_sizer, 0, wxEXPAND, 0);
  423. $right_sizer->Add($print_info_sizer, 0, wxEXPAND, 0);
  424. # Callback for showing / hiding the print info box.
  425. $self->{"print_info_box_show"} = sub {
  426. if ($right_sizer->IsShown(4) != $_[0]) {
  427. $right_sizer->Show(4, $_[0]);
  428. $self->Layout
  429. }
  430. };
  431. # Show the box initially, let it be shown after the slicing is finished.
  432. $self->{"print_info_box_show"}->(0);
  433. my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL);
  434. $hsizer->Add($self->{preview_notebook}, 1, wxEXPAND | wxTOP, 1);
  435. $hsizer->Add($right_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT, 3);
  436. my $sizer = Wx::BoxSizer->new(wxVERTICAL);
  437. $sizer->Add($self->{htoolbar}, 0, wxEXPAND, 0) if $self->{htoolbar};
  438. $sizer->Add($self->{btoolbar}, 0, wxEXPAND, 0) if $self->{btoolbar};
  439. $sizer->Add($hsizer, 1, wxEXPAND, 0);
  440. $sizer->SetSizeHints($self);
  441. $self->SetSizer($sizer);
  442. }
  443. $self->update_ui_from_settings();
  444. return $self;
  445. }
  446. # sets the callback
  447. sub on_select_preset {
  448. my ($self, $cb) = @_;
  449. $self->{on_select_preset} = $cb;
  450. }
  451. # Called from the platter combo boxes selecting the active print, filament or printer.
  452. sub _on_select_preset {
  453. my ($self, $group, $choice, $idx) = @_;
  454. # If user changed a filament preset and the selected machine is equipped with multiple extruders,
  455. # there are multiple filament selection combo boxes shown at the platter. In that case
  456. # don't propagate the filament selection changes to the tab.
  457. if ($group eq 'filament') {
  458. wxTheApp->{preset_bundle}->set_filament_preset($idx, $choice->GetStringSelection);
  459. }
  460. if ($group eq 'filament' && @{$self->{preset_choosers}{filament}} > 1) {
  461. wxTheApp->{preset_bundle}->update_platter_filament_ui($idx, $choice);
  462. } else {
  463. # call GetSelection() in scalar context as it's context-aware
  464. $self->{on_select_preset}->($group, $choice->GetStringSelection)
  465. if $self->{on_select_preset};
  466. }
  467. # Synchronize config.ini with the current selections.
  468. wxTheApp->{preset_bundle}->export_selections(wxTheApp->{app_config});
  469. # get new config and generate on_config_change() event for updating plater and other things
  470. $self->on_config_change(wxTheApp->{preset_bundle}->full_config);
  471. }
  472. sub on_layer_editing_toggled {
  473. my ($self, $new_state) = @_;
  474. $self->{canvas3D}->layer_editing_enabled($new_state);
  475. if ($new_state && ! $self->{canvas3D}->layer_editing_enabled) {
  476. # Initialization of the OpenGL shaders failed. Disable the tool.
  477. if ($self->{htoolbar}) {
  478. $self->{htoolbar}->EnableTool(TB_LAYER_EDITING, 0);
  479. $self->{htoolbar}->ToggleTool(TB_LAYER_EDITING, 0);
  480. } else {
  481. $self->{"btn_layer_editing"}->Disable;
  482. $self->{"btn_layer_editing"}->SetValue(0);
  483. }
  484. }
  485. $self->{canvas3D}->Refresh;
  486. $self->{canvas3D}->Update;
  487. }
  488. sub GetFrame {
  489. my ($self) = @_;
  490. return &Wx::GetTopLevelParent($self);
  491. }
  492. # Called after the Preferences dialog is closed and the program settings are saved.
  493. # Update the UI based on the current preferences.
  494. sub update_ui_from_settings
  495. {
  496. my ($self) = @_;
  497. if (defined($self->{btn_reslice}) && $self->{buttons_sizer}->IsShown($self->{btn_reslice}) != (! wxTheApp->{app_config}->get("background_processing"))) {
  498. $self->{buttons_sizer}->Show($self->{btn_reslice}, ! wxTheApp->{app_config}->get("background_processing"));
  499. $self->{buttons_sizer}->Layout;
  500. }
  501. }
  502. # Update preset combo boxes (Print settings, Filament, Printer) from their respective tabs.
  503. # Called by
  504. # Slic3r::GUI::Tab::Print::_on_presets_changed
  505. # Slic3r::GUI::Tab::Filament::_on_presets_changed
  506. # Slic3r::GUI::Tab::Printer::_on_presets_changed
  507. # when the presets are loaded or the user selects another preset.
  508. # For Print settings and Printer, synchronize the selection index with their tabs.
  509. # For Filament, synchronize the selection index for a single extruder printer only, otherwise keep the selection.
  510. sub update_presets {
  511. # $group: one of qw(print filament printer)
  512. # $presets: PresetCollection
  513. my ($self, $group, $presets) = @_;
  514. my @choosers = @{$self->{preset_choosers}{$group}};
  515. if ($group eq 'filament') {
  516. my $choice_idx = 0;
  517. if (int(@choosers) == 1) {
  518. # Single filament printer, synchronize the filament presets.
  519. wxTheApp->{preset_bundle}->set_filament_preset(0, wxTheApp->{preset_bundle}->filament->get_selected_preset->name);
  520. }
  521. foreach my $choice (@choosers) {
  522. wxTheApp->{preset_bundle}->update_platter_filament_ui($choice_idx, $choice);
  523. $choice_idx += 1;
  524. }
  525. } elsif ($group eq 'print') {
  526. wxTheApp->{preset_bundle}->print->update_platter_ui($choosers[0]);
  527. } elsif ($group eq 'printer') {
  528. # Update the print choosers to only contain the compatible presets, update the dirty flags.
  529. wxTheApp->{preset_bundle}->print->update_platter_ui($self->{preset_choosers}{print}->[0]);
  530. # Update the printer choosers, update the dirty flags.
  531. wxTheApp->{preset_bundle}->printer->update_platter_ui($choosers[0]);
  532. # Update the filament choosers to only contain the compatible presets, update the color preview,
  533. # update the dirty flags.
  534. my $choice_idx = 0;
  535. foreach my $choice (@{$self->{preset_choosers}{filament}}) {
  536. wxTheApp->{preset_bundle}->update_platter_filament_ui($choice_idx, $choice);
  537. $choice_idx += 1;
  538. }
  539. }
  540. # Synchronize config.ini with the current selections.
  541. wxTheApp->{preset_bundle}->export_selections(wxTheApp->{app_config});
  542. }
  543. sub add {
  544. my ($self) = @_;
  545. my @input_files = wxTheApp->open_model($self);
  546. $self->load_files(\@input_files);
  547. }
  548. sub load_files {
  549. my ($self, $input_files) = @_;
  550. return if ! defined($input_files) || ! scalar(@$input_files);
  551. my $nozzle_dmrs = $self->{config}->get('nozzle_diameter');
  552. # One of the files is potentionally a bundle of files. Don't bundle them, but load them one by one.
  553. # Only bundle .stls or .objs if the printer has multiple extruders.
  554. my $one_by_one = (@$nozzle_dmrs <= 1) || (@$input_files == 1) ||
  555. defined(first { $_ =~ /.[aA][mM][fF]$/ || $_ =~ /.3[mM][fF]$/ || $_ =~ /.[pP][rR][uI][sS][aA]$/ } @$input_files);
  556. my $process_dialog = Wx::ProgressDialog->new('Loading…', "Processing input file\n" . basename($input_files->[0]), 100, $self, 0);
  557. $process_dialog->Pulse;
  558. local $SIG{__WARN__} = Slic3r::GUI::warning_catcher($self);
  559. # new_model to collect volumes, if all of them come from .stl or .obj and there is a chance, that they will be
  560. # possibly merged into a single multi-part object.
  561. my $new_model = $one_by_one ? undef : Slic3r::Model->new;
  562. # Object indices for the UI.
  563. my @obj_idx = ();
  564. # Collected file names to display the final message on the status bar.
  565. my @loaded_files = ();
  566. # For all input files.
  567. for (my $i = 0; $i < @$input_files; $i += 1) {
  568. my $input_file = $input_files->[$i];
  569. $process_dialog->Update(100. * $i / @$input_files, "Processing input file\n" . basename($input_file));
  570. my $model = eval { Slic3r::Model->read_from_file($input_file, 0) };
  571. Slic3r::GUI::show_error($self, $@) if $@;
  572. next if ! defined $model;
  573. if ($model->looks_like_multipart_object) {
  574. my $dialog = Wx::MessageDialog->new($self,
  575. "This file contains several objects positioned at multiple heights. "
  576. . "Instead of considering them as multiple objects, should I consider\n"
  577. . "this file as a single object having multiple parts?\n",
  578. 'Multi-part object detected', wxICON_WARNING | wxYES | wxNO);
  579. $model->convert_multipart_object if $dialog->ShowModal() == wxID_YES;
  580. }
  581. if ($one_by_one) {
  582. push @obj_idx, $self->load_model_objects(@{$model->objects});
  583. } else {
  584. # This must be an .stl or .obj file, which may contain a maximum of one volume.
  585. $new_model->add_object($_) for (@{$model->objects});
  586. }
  587. }
  588. if ($new_model) {
  589. my $dialog = Wx::MessageDialog->new($self,
  590. "Multiple objects were loaded for a multi-material printer.\n"
  591. . "Instead of considering them as multiple objects, should I consider\n"
  592. . "these files to represent a single object having multiple parts?\n",
  593. 'Multi-part object detected', wxICON_WARNING | wxYES | wxNO);
  594. $new_model->convert_multipart_object if $dialog->ShowModal() == wxID_YES;
  595. push @obj_idx, $self->load_model_objects(@{$new_model->objects});
  596. }
  597. # Note the current directory for the file open dialog.
  598. wxTheApp->{app_config}->update_skein_dir(dirname($input_files->[-1]));
  599. $process_dialog->Destroy;
  600. $self->statusbar->SetStatusText("Loaded " . join(',', @loaded_files));
  601. return @obj_idx;
  602. }
  603. sub load_model_objects {
  604. my ($self, @model_objects) = @_;
  605. my $bed_centerf = $self->bed_centerf;
  606. my $bed_shape = Slic3r::Polygon->new_scale(@{$self->{config}->bed_shape});
  607. my $bed_size = $bed_shape->bounding_box->size;
  608. my $need_arrange = 0;
  609. my $scaled_down = 0;
  610. my @obj_idx = ();
  611. foreach my $model_object (@model_objects) {
  612. my $o = $self->{model}->add_object($model_object);
  613. my $object_name = $model_object->name;
  614. $object_name = basename($model_object->input_file) if ($object_name eq '');
  615. push @{ $self->{objects} }, Slic3r::GUI::Plater::Object->new(name => $object_name);
  616. push @obj_idx, $#{ $self->{objects} };
  617. if ($model_object->instances_count == 0) {
  618. # if object has no defined position(s) we need to rearrange everything after loading
  619. $need_arrange = 1;
  620. # add a default instance and center object around origin
  621. $o->center_around_origin; # also aligns object to Z = 0
  622. $o->add_instance(offset => $bed_centerf);
  623. }
  624. {
  625. # if the object is too large (more than 5 times the bed), scale it down
  626. my $size = $o->bounding_box->size;
  627. my $ratio = max(@$size[X,Y]) / unscale(max(@$bed_size[X,Y]));
  628. if ($ratio > 5) {
  629. $_->set_scaling_factor(1/$ratio) for @{$o->instances};
  630. $scaled_down = 1;
  631. }
  632. }
  633. $self->{print}->auto_assign_extruders($o);
  634. $self->{print}->add_model_object($o);
  635. }
  636. # if user turned autocentering off, automatic arranging would disappoint them
  637. if (! wxTheApp->{app_config}->get("autocenter")) {
  638. $need_arrange = 0;
  639. }
  640. if ($scaled_down) {
  641. Slic3r::GUI::show_info(
  642. $self,
  643. 'Your object appears to be too large, so it was automatically scaled down to fit your print bed.',
  644. 'Object too large?',
  645. );
  646. }
  647. foreach my $obj_idx (@obj_idx) {
  648. my $object = $self->{objects}[$obj_idx];
  649. my $model_object = $self->{model}->objects->[$obj_idx];
  650. $self->{list}->InsertStringItem($obj_idx, $object->name);
  651. $self->{list}->SetItemFont($obj_idx, Wx::Font->new(10, wxDEFAULT, wxNORMAL, wxNORMAL))
  652. if $self->{list}->can('SetItemFont'); # legacy code for wxPerl < 0.9918 not supporting SetItemFont()
  653. $self->{list}->SetItem($obj_idx, 1, $model_object->instances_count);
  654. $self->{list}->SetItem($obj_idx, 2, ($model_object->instances->[0]->scaling_factor * 100) . "%");
  655. $self->reset_thumbnail($obj_idx);
  656. }
  657. $self->arrange if $need_arrange;
  658. $self->update;
  659. # zoom to objects
  660. $self->{canvas3D}->zoom_to_volumes
  661. if $self->{canvas3D};
  662. $self->{list}->Update;
  663. $self->{list}->Select($obj_idx[-1], 1);
  664. $self->object_list_changed;
  665. $self->schedule_background_process;
  666. return @obj_idx;
  667. }
  668. sub bed_centerf {
  669. my ($self) = @_;
  670. my $bed_shape = Slic3r::Polygon->new_scale(@{$self->{config}->bed_shape});
  671. my $bed_center = $bed_shape->bounding_box->center;
  672. return Slic3r::Pointf->new(unscale($bed_center->x), unscale($bed_center->y)); #)
  673. }
  674. sub remove {
  675. my $self = shift;
  676. my ($obj_idx) = @_;
  677. $self->stop_background_process;
  678. # Prevent toolpaths preview from rendering while we modify the Print object
  679. $self->{toolpaths2D}->enabled(0) if $self->{toolpaths2D};
  680. $self->{preview3D}->enabled(0) if $self->{preview3D};
  681. # if no object index is supplied, remove the selected one
  682. if (! defined $obj_idx) {
  683. ($obj_idx, undef) = $self->selected_object;
  684. return if ! defined $obj_idx;
  685. }
  686. splice @{$self->{objects}}, $obj_idx, 1;
  687. $self->{model}->delete_object($obj_idx);
  688. $self->{print}->delete_object($obj_idx);
  689. $self->{list}->DeleteItem($obj_idx);
  690. $self->object_list_changed;
  691. $self->select_object(undef);
  692. $self->update;
  693. $self->schedule_background_process;
  694. }
  695. sub reset {
  696. my $self = shift;
  697. $self->stop_background_process;
  698. # Prevent toolpaths preview from rendering while we modify the Print object
  699. $self->{toolpaths2D}->enabled(0) if $self->{toolpaths2D};
  700. $self->{preview3D}->enabled(0) if $self->{preview3D};
  701. @{$self->{objects}} = ();
  702. $self->{model}->clear_objects;
  703. $self->{print}->clear_objects;
  704. $self->{list}->DeleteAllItems;
  705. $self->object_list_changed;
  706. $self->select_object(undef);
  707. $self->update;
  708. }
  709. sub increase {
  710. my ($self, $copies) = @_;
  711. $copies //= 1;
  712. my ($obj_idx, $object) = $self->selected_object;
  713. return if ! defined $obj_idx;
  714. my $model_object = $self->{model}->objects->[$obj_idx];
  715. my $instance = $model_object->instances->[-1];
  716. for my $i (1..$copies) {
  717. $instance = $model_object->add_instance(
  718. offset => Slic3r::Pointf->new(map 10+$_, @{$instance->offset}),
  719. scaling_factor => $instance->scaling_factor,
  720. rotation => $instance->rotation,
  721. );
  722. $self->{print}->objects->[$obj_idx]->add_copy($instance->offset);
  723. }
  724. $self->{list}->SetItem($obj_idx, 1, $model_object->instances_count);
  725. # only autoarrange if user has autocentering enabled
  726. $self->stop_background_process;
  727. if (wxTheApp->{app_config}->get("autocenter")) {
  728. $self->arrange;
  729. } else {
  730. $self->update;
  731. }
  732. $self->schedule_background_process;
  733. }
  734. sub decrease {
  735. my ($self, $copies_asked) = @_;
  736. my $copies = $copies_asked // 1;
  737. my ($obj_idx, $object) = $self->selected_object;
  738. return if ! defined $obj_idx;
  739. $self->stop_background_process;
  740. my $model_object = $self->{model}->objects->[$obj_idx];
  741. if ($model_object->instances_count > $copies) {
  742. for my $i (1..$copies) {
  743. $model_object->delete_last_instance;
  744. $self->{print}->objects->[$obj_idx]->delete_last_copy;
  745. }
  746. $self->{list}->SetItem($obj_idx, 1, $model_object->instances_count);
  747. } elsif (defined $copies_asked) {
  748. # The "decrease" came from the "set number of copies" dialog.
  749. $self->remove;
  750. } else {
  751. # The "decrease" came from the "-" button. Don't allow the object to disappear.
  752. $self->resume_background_process;
  753. return;
  754. }
  755. if ($self->{objects}[$obj_idx]) {
  756. $self->{list}->Select($obj_idx, 0);
  757. $self->{list}->Select($obj_idx, 1);
  758. }
  759. $self->update;
  760. $self->schedule_background_process;
  761. }
  762. sub set_number_of_copies {
  763. my ($self) = @_;
  764. $self->pause_background_process;
  765. # get current number of copies
  766. my ($obj_idx, $object) = $self->selected_object;
  767. my $model_object = $self->{model}->objects->[$obj_idx];
  768. # prompt user
  769. my $copies = Wx::GetNumberFromUser("", "Enter the number of copies of the selected object:", "Copies", $model_object->instances_count, 0, 1000, $self);
  770. my $diff = $copies - $model_object->instances_count;
  771. if ($diff == 0) {
  772. # no variation
  773. $self->resume_background_process;
  774. } elsif ($diff > 0) {
  775. $self->increase($diff);
  776. } elsif ($diff < 0) {
  777. $self->decrease(-$diff);
  778. }
  779. }
  780. sub _get_number_from_user {
  781. my ($self, $title, $prompt_message, $error_message, $default, $only_positive) = @_;
  782. for (;;) {
  783. my $value = Wx::GetTextFromUser($prompt_message, $title, $default, $self);
  784. # Accept both dashes and dots as a decimal separator.
  785. $value =~ s/,/./;
  786. # If scaling value is being entered, remove the trailing percent sign.
  787. $value =~ s/%$// if $only_positive;
  788. # User canceled the selection, return undef.
  789. return if $value eq '';
  790. # Validate a numeric value.
  791. return $value if ($value =~ /^-?\d*(?:\.\d*)?$/) && (! $only_positive || $value > 0);
  792. Wx::MessageBox(
  793. $error_message .
  794. (($only_positive && $value <= 0) ?
  795. ": $value\nNon-positive value." :
  796. ": $value\nNot a numeric value."),
  797. "Slic3r Error", wxOK | wxICON_EXCLAMATION, $self);
  798. $default = $value;
  799. }
  800. }
  801. sub rotate {
  802. my ($self, $angle, $axis, $relative_key) = @_;
  803. $relative_key //= 'absolute'; # relative or absolute coordinates
  804. $axis //= Z; # angle is in degrees
  805. my $relative = $relative_key eq 'relative';
  806. my ($obj_idx, $object) = $self->selected_object;
  807. return if !defined $obj_idx;
  808. my $model_object = $self->{model}->objects->[$obj_idx];
  809. my $model_instance = $model_object->instances->[0];
  810. if (!defined $angle) {
  811. my $axis_name = $axis == X ? 'X' : $axis == Y ? 'Y' : 'Z';
  812. my $default = $axis == Z ? rad2deg($model_instance->rotation) : 0;
  813. $angle = $self->_get_number_from_user("Enter the rotation angle:", "Rotate around $axis_name axis", "Invalid rotation angle entered", $default);
  814. return if $angle eq '';
  815. }
  816. $self->stop_background_process;
  817. if ($axis == Z) {
  818. my $new_angle = deg2rad($angle);
  819. $_->set_rotation(($relative ? $_->rotation : 0.) + $new_angle) for @{ $model_object->instances };
  820. $object->transform_thumbnail($self->{model}, $obj_idx);
  821. } else {
  822. # rotation around X and Y needs to be performed on mesh
  823. # so we first apply any Z rotation
  824. if ($model_instance->rotation != 0) {
  825. $model_object->rotate($model_instance->rotation, Z);
  826. $_->set_rotation(0) for @{ $model_object->instances };
  827. }
  828. $model_object->rotate(deg2rad($angle), $axis);
  829. # realign object to Z = 0
  830. $model_object->center_around_origin;
  831. $self->reset_thumbnail($obj_idx);
  832. }
  833. # update print and start background processing
  834. $self->{print}->add_model_object($model_object, $obj_idx);
  835. $self->selection_changed; # refresh info (size etc.)
  836. $self->update;
  837. $self->schedule_background_process;
  838. }
  839. sub mirror {
  840. my ($self, $axis) = @_;
  841. my ($obj_idx, $object) = $self->selected_object;
  842. return if !defined $obj_idx;
  843. my $model_object = $self->{model}->objects->[$obj_idx];
  844. my $model_instance = $model_object->instances->[0];
  845. # apply Z rotation before mirroring
  846. if ($model_instance->rotation != 0) {
  847. $model_object->rotate($model_instance->rotation, Z);
  848. $_->set_rotation(0) for @{ $model_object->instances };
  849. }
  850. $model_object->mirror($axis);
  851. # realign object to Z = 0
  852. $model_object->center_around_origin;
  853. $self->reset_thumbnail($obj_idx);
  854. # update print and start background processing
  855. $self->stop_background_process;
  856. $self->{print}->add_model_object($model_object, $obj_idx);
  857. $self->selection_changed; # refresh info (size etc.)
  858. $self->update;
  859. $self->schedule_background_process;
  860. }
  861. sub changescale {
  862. my ($self, $axis, $tosize) = @_;
  863. my ($obj_idx, $object) = $self->selected_object;
  864. return if !defined $obj_idx;
  865. my $model_object = $self->{model}->objects->[$obj_idx];
  866. my $model_instance = $model_object->instances->[0];
  867. my $object_size = $model_object->bounding_box->size;
  868. my $bed_size = Slic3r::Polygon->new_scale(@{$self->{config}->bed_shape})->bounding_box->size;
  869. if (defined $axis) {
  870. my $axis_name = $axis == X ? 'X' : $axis == Y ? 'Y' : 'Z';
  871. my $scale;
  872. if ($tosize) {
  873. my $cursize = $object_size->[$axis];
  874. my $newsize = $self->_get_number_from_user(
  875. sprintf('Enter the new size for the selected object (print bed: %smm):', unscale($bed_size->[$axis])),
  876. "Scale along $axis_name", 'Invalid scaling value entered', $cursize, 1);
  877. return if $newsize eq '';
  878. $scale = $newsize / $cursize * 100;
  879. } else {
  880. $scale = $self->_get_number_from_user('Enter the scale % for the selected object:', "Scale along $axis_name", 'Invalid scaling value entered', 100, 1);
  881. return if $scale eq '';
  882. }
  883. # apply Z rotation before scaling
  884. if ($model_instance->rotation != 0) {
  885. $model_object->rotate($model_instance->rotation, Z);
  886. $_->set_rotation(0) for @{ $model_object->instances };
  887. }
  888. my $versor = [1,1,1];
  889. $versor->[$axis] = $scale/100;
  890. $model_object->scale_xyz(Slic3r::Pointf3->new(@$versor));
  891. #FIXME Scale the layer height profile when $axis == Z?
  892. #FIXME Scale the layer height ranges $axis == Z?
  893. # object was already aligned to Z = 0, so no need to realign it
  894. $self->reset_thumbnail($obj_idx);
  895. } else {
  896. my $scale;
  897. if ($tosize) {
  898. my $cursize = max(@$object_size);
  899. my $newsize = $self->_get_number_from_user('Enter the new max size for the selected object:', 'Scale', 'Invalid scaling value entered', $cursize, 1);
  900. return if ! defined($newsize) || $newsize eq '';
  901. $scale = $model_instance->scaling_factor * $newsize / $cursize * 100;
  902. } else {
  903. # max scale factor should be above 2540 to allow importing files exported in inches
  904. $scale = $self->_get_number_from_user('Enter the scale % for the selected object:', 'Scale', 'Invalid scaling value entered', $model_instance->scaling_factor*100, 1);
  905. return if ! defined($scale) || $scale eq '';
  906. }
  907. $self->{list}->SetItem($obj_idx, 2, "$scale%");
  908. $scale /= 100; # turn percent into factor
  909. my $variation = $scale / $model_instance->scaling_factor;
  910. #FIXME Scale the layer height profile?
  911. foreach my $range (@{ $model_object->layer_height_ranges }) {
  912. $range->[0] *= $variation;
  913. $range->[1] *= $variation;
  914. }
  915. $_->set_scaling_factor($scale) for @{ $model_object->instances };
  916. $object->transform_thumbnail($self->{model}, $obj_idx);
  917. }
  918. # update print and start background processing
  919. $self->stop_background_process;
  920. $self->{print}->add_model_object($model_object, $obj_idx);
  921. $self->selection_changed(1); # refresh info (size, volume etc.)
  922. $self->update;
  923. $self->schedule_background_process;
  924. }
  925. sub arrange {
  926. my $self = shift;
  927. $self->pause_background_process;
  928. my $bb = Slic3r::Geometry::BoundingBoxf->new_from_points($self->{config}->bed_shape);
  929. my $success = $self->{model}->arrange_objects(wxTheApp->{preset_bundle}->full_config->min_object_distance, $bb);
  930. # ignore arrange failures on purpose: user has visual feedback and we don't need to warn him
  931. # when parts don't fit in print bed
  932. # Force auto center of the aligned grid of of objects on the print bed.
  933. $self->update(1);
  934. }
  935. sub split_object {
  936. my $self = shift;
  937. my ($obj_idx, $current_object) = $self->selected_object;
  938. # we clone model object because split_object() adds the split volumes
  939. # into the same model object, thus causing duplicates when we call load_model_objects()
  940. my $new_model = $self->{model}->clone; # store this before calling get_object()
  941. my $current_model_object = $new_model->get_object($obj_idx);
  942. if ($current_model_object->volumes_count > 1) {
  943. Slic3r::GUI::warning_catcher($self)->("The selected object can't be split because it contains more than one volume/material.");
  944. return;
  945. }
  946. $self->pause_background_process;
  947. my @model_objects = @{$current_model_object->split_object};
  948. if (@model_objects == 1) {
  949. $self->resume_background_process;
  950. Slic3r::GUI::warning_catcher($self)->("The selected object couldn't be split because it contains only one part.");
  951. $self->resume_background_process;
  952. return;
  953. }
  954. $_->center_around_origin for (@model_objects);
  955. $self->remove($obj_idx);
  956. $current_object = $obj_idx = undef;
  957. # load all model objects at once, otherwise the plate would be rearranged after each one
  958. # causing original positions not to be kept
  959. $self->load_model_objects(@model_objects);
  960. }
  961. sub schedule_background_process {
  962. my ($self) = @_;
  963. if (defined $self->{apply_config_timer}) {
  964. $self->{apply_config_timer}->Start(PROCESS_DELAY, 1); # 1 = one shot
  965. }
  966. }
  967. # Executed asynchronously by a timer every PROCESS_DELAY (0.5 second).
  968. # The timer is started by schedule_background_process(),
  969. sub async_apply_config {
  970. my ($self) = @_;
  971. # pause process thread before applying new config
  972. # since we don't want to touch data that is being used by the threads
  973. $self->pause_background_process;
  974. # apply new config
  975. my $invalidated = $self->{print}->apply_config(wxTheApp->{preset_bundle}->full_config);
  976. # Just redraw the 3D canvas without reloading the scene.
  977. # $self->{canvas3D}->Refresh if ($invalidated && $self->{canvas3D}->layer_editing_enabled);
  978. $self->{canvas3D}->Refresh if ($self->{canvas3D}->layer_editing_enabled);
  979. # Hide the slicing results if the current slicing status is no more valid.
  980. $self->{"print_info_box_show"}->(0) if $invalidated;
  981. if (wxTheApp->{app_config}->get("background_processing")) {
  982. if ($invalidated) {
  983. # kill current thread if any
  984. $self->stop_background_process;
  985. } else {
  986. $self->resume_background_process;
  987. }
  988. # schedule a new process thread in case it wasn't running
  989. $self->start_background_process;
  990. }
  991. # Reset preview canvases. If the print has been invalidated, the preview canvases will be cleared.
  992. # Otherwise they will be just refreshed.
  993. if ($invalidated) {
  994. $self->{toolpaths2D}->reload_print if $self->{toolpaths2D};
  995. $self->{preview3D}->reload_print if $self->{preview3D};
  996. }
  997. }
  998. sub start_background_process {
  999. my ($self) = @_;
  1000. return if !@{$self->{objects}};
  1001. return if $self->{process_thread};
  1002. # It looks like declaring a local $SIG{__WARN__} prevents the ugly
  1003. # "Attempt to free unreferenced scalar" warning...
  1004. local $SIG{__WARN__} = Slic3r::GUI::warning_catcher($self);
  1005. # don't start process thread if config is not valid
  1006. eval {
  1007. # this will throw errors if config is not valid
  1008. wxTheApp->{preset_bundle}->full_config->validate;
  1009. $self->{print}->validate;
  1010. };
  1011. if ($@) {
  1012. $self->statusbar->SetStatusText($@);
  1013. return;
  1014. }
  1015. # Copy the names of active presets into the placeholder parser.
  1016. wxTheApp->{preset_bundle}->export_selections_pp($self->{print}->placeholder_parser);
  1017. # start thread
  1018. @_ = ();
  1019. $self->{process_thread} = Slic3r::spawn_thread(sub {
  1020. eval {
  1021. $self->{print}->process;
  1022. };
  1023. if ($@) {
  1024. Slic3r::debugf "Background process error: $@\n";
  1025. Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROCESS_COMPLETED_EVENT, $@));
  1026. } else {
  1027. Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROCESS_COMPLETED_EVENT, undef));
  1028. }
  1029. Slic3r::thread_cleanup();
  1030. });
  1031. Slic3r::debugf "Background processing started.\n";
  1032. }
  1033. sub stop_background_process {
  1034. my ($self) = @_;
  1035. $self->{apply_config_timer}->Stop if defined $self->{apply_config_timer};
  1036. $self->statusbar->SetCancelCallback(undef);
  1037. $self->statusbar->StopBusy;
  1038. $self->statusbar->SetStatusText("");
  1039. $self->{toolpaths2D}->reload_print if $self->{toolpaths2D};
  1040. $self->{preview3D}->reload_print if $self->{preview3D};
  1041. if ($self->{process_thread}) {
  1042. Slic3r::debugf "Killing background process.\n";
  1043. Slic3r::kill_all_threads();
  1044. $self->{process_thread} = undef;
  1045. } else {
  1046. Slic3r::debugf "No background process running.\n";
  1047. }
  1048. # if there's an export process, kill that one as well
  1049. if ($self->{export_thread}) {
  1050. Slic3r::debugf "Killing background export process.\n";
  1051. Slic3r::kill_all_threads();
  1052. $self->{export_thread} = undef;
  1053. }
  1054. }
  1055. sub pause_background_process {
  1056. my ($self) = @_;
  1057. if ($self->{process_thread} || $self->{export_thread}) {
  1058. Slic3r::pause_all_threads();
  1059. return 1;
  1060. } elsif (defined $self->{apply_config_timer} && $self->{apply_config_timer}->IsRunning) {
  1061. $self->{apply_config_timer}->Stop;
  1062. return 1;
  1063. }
  1064. return 0;
  1065. }
  1066. sub resume_background_process {
  1067. my ($self) = @_;
  1068. if ($self->{process_thread} || $self->{export_thread}) {
  1069. Slic3r::resume_all_threads();
  1070. }
  1071. }
  1072. sub reslice {
  1073. # explicitly cancel a previous thread and start a new one.
  1074. my ($self) = @_;
  1075. # Don't reslice if export of G-code or sending to OctoPrint is running.
  1076. if (! defined($self->{export_gcode_output_file}) && ! defined($self->{send_gcode_file})) {
  1077. # Stop the background processing threads, stop the async update timer.
  1078. $self->stop_background_process;
  1079. # Rather perform one additional unnecessary update of the print object instead of skipping a pending async update.
  1080. $self->async_apply_config;
  1081. $self->statusbar->SetCancelCallback(sub {
  1082. $self->stop_background_process;
  1083. $self->statusbar->SetStatusText("Slicing cancelled");
  1084. # this updates buttons status
  1085. $self->object_list_changed;
  1086. });
  1087. $self->start_background_process;
  1088. }
  1089. }
  1090. sub export_gcode {
  1091. my ($self, $output_file) = @_;
  1092. return if !@{$self->{objects}};
  1093. if ($self->{export_gcode_output_file}) {
  1094. Wx::MessageDialog->new($self, "Another export job is currently running.", 'Error', wxOK | wxICON_ERROR)->ShowModal;
  1095. return;
  1096. }
  1097. # if process is not running, validate config
  1098. # (we assume that if it is running, config is valid)
  1099. eval {
  1100. # this will throw errors if config is not valid
  1101. wxTheApp->{preset_bundle}->full_config->validate;
  1102. $self->{print}->validate;
  1103. };
  1104. Slic3r::GUI::catch_error($self) and return;
  1105. # apply config and validate print
  1106. my $config = wxTheApp->{preset_bundle}->full_config;
  1107. eval {
  1108. # this will throw errors if config is not valid
  1109. $config->validate;
  1110. $self->{print}->apply_config($config);
  1111. $self->{print}->validate;
  1112. };
  1113. Slic3r::GUI::catch_error($self) and return;
  1114. # select output file
  1115. if ($output_file) {
  1116. $self->{export_gcode_output_file} = $self->{print}->output_filepath($output_file);
  1117. } else {
  1118. my $default_output_file = $self->{print}->output_filepath($main::opt{output} // '');
  1119. my $dlg = Wx::FileDialog->new($self, 'Save G-code file as:',
  1120. wxTheApp->{app_config}->get_last_output_dir(dirname($default_output_file)),
  1121. basename($default_output_file), &Slic3r::GUI::FILE_WILDCARDS->{gcode}, wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
  1122. if ($dlg->ShowModal != wxID_OK) {
  1123. $dlg->Destroy;
  1124. return;
  1125. }
  1126. my $path = $dlg->GetPath;
  1127. wxTheApp->{app_config}->update_last_output_dir(dirname($path));
  1128. $self->{export_gcode_output_file} = $path;
  1129. $dlg->Destroy;
  1130. }
  1131. $self->statusbar->StartBusy;
  1132. $self->statusbar->SetCancelCallback(sub {
  1133. $self->stop_background_process;
  1134. $self->statusbar->SetStatusText("Export cancelled");
  1135. $self->{export_gcode_output_file} = undef;
  1136. $self->{send_gcode_file} = undef;
  1137. # this updates buttons status
  1138. $self->object_list_changed;
  1139. });
  1140. # start background process, whose completion event handler
  1141. # will detect $self->{export_gcode_output_file} and proceed with export
  1142. $self->start_background_process;
  1143. # this updates buttons status
  1144. $self->object_list_changed;
  1145. return $self->{export_gcode_output_file};
  1146. }
  1147. # This gets called only if we have threads.
  1148. sub on_process_completed {
  1149. my ($self, $error) = @_;
  1150. $self->statusbar->SetCancelCallback(undef);
  1151. $self->statusbar->StopBusy;
  1152. $self->statusbar->SetStatusText($error // "");
  1153. Slic3r::debugf "Background processing completed.\n";
  1154. $self->{process_thread}->detach if $self->{process_thread};
  1155. $self->{process_thread} = undef;
  1156. # if we're supposed to perform an explicit export let's display the error in a dialog
  1157. if ($error && $self->{export_gcode_output_file}) {
  1158. $self->{export_gcode_output_file} = undef;
  1159. Slic3r::GUI::show_error($self, $error);
  1160. }
  1161. return if $error;
  1162. $self->{toolpaths2D}->reload_print if $self->{toolpaths2D};
  1163. $self->{preview3D}->reload_print if $self->{preview3D};
  1164. # if we have an export filename, start a new thread for exporting G-code
  1165. if ($self->{export_gcode_output_file}) {
  1166. @_ = ();
  1167. # workaround for "Attempt to free un referenced scalar..."
  1168. our $_thread_self = $self;
  1169. $self->{export_thread} = Slic3r::spawn_thread(sub {
  1170. eval {
  1171. $_thread_self->{print}->export_gcode(output_file => $_thread_self->{export_gcode_output_file});
  1172. };
  1173. if ($@) {
  1174. Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $ERROR_EVENT, shared_clone([ $@ ])));
  1175. Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $EXPORT_COMPLETED_EVENT, 0));
  1176. } else {
  1177. Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $EXPORT_COMPLETED_EVENT, 1));
  1178. }
  1179. Slic3r::thread_cleanup();
  1180. });
  1181. Slic3r::debugf "Background G-code export started.\n";
  1182. }
  1183. }
  1184. # This gets called also if we have no threads.
  1185. sub on_progress_event {
  1186. my ($self, $percent, $message) = @_;
  1187. $self->statusbar->SetProgress($percent);
  1188. $self->statusbar->SetStatusText("$message…");
  1189. }
  1190. # Called when the G-code export finishes, either successfully or with an error.
  1191. # This gets called also if we don't have threads.
  1192. sub on_export_completed {
  1193. my ($self, $result) = @_;
  1194. $self->statusbar->SetCancelCallback(undef);
  1195. $self->statusbar->StopBusy;
  1196. $self->statusbar->SetStatusText("");
  1197. Slic3r::debugf "Background export process completed.\n";
  1198. $self->{export_thread}->detach if $self->{export_thread};
  1199. $self->{export_thread} = undef;
  1200. my $message;
  1201. my $send_gcode = 0;
  1202. my $do_print = 0;
  1203. if ($result) {
  1204. # G-code file exported successfully.
  1205. if ($self->{print_file}) {
  1206. $message = "File added to print queue";
  1207. $do_print = 1;
  1208. } elsif ($self->{send_gcode_file}) {
  1209. $message = "Sending G-code file to the OctoPrint server...";
  1210. $send_gcode = 1;
  1211. } else {
  1212. $message = "G-code file exported to " . $self->{export_gcode_output_file};
  1213. }
  1214. } else {
  1215. $message = "Export failed";
  1216. }
  1217. $self->{export_gcode_output_file} = undef;
  1218. $self->statusbar->SetStatusText($message);
  1219. wxTheApp->notify($message);
  1220. $self->do_print if $do_print;
  1221. # Send $self->{send_gcode_file} to OctoPrint.
  1222. $self->send_gcode if $send_gcode;
  1223. $self->{print_file} = undef;
  1224. $self->{send_gcode_file} = undef;
  1225. $self->{"print_info_cost"}->SetLabel(sprintf("%.2f" , $self->{print}->total_cost));
  1226. $self->{"print_info_fil_g"}->SetLabel(sprintf("%.2f" , $self->{print}->total_weight));
  1227. $self->{"print_info_fil_mm3"}->SetLabel(sprintf("%.2f" , $self->{print}->total_extruded_volume));
  1228. $self->{"print_info_box_show"}->(1);
  1229. # this updates buttons status
  1230. $self->object_list_changed;
  1231. }
  1232. sub do_print {
  1233. my ($self) = @_;
  1234. my $controller = $self->GetFrame->{controller};
  1235. my $printer_preset = wxTheApp->{preset_bundle}->printer->get_edited_preset;
  1236. my $printer_panel = $controller->add_printer($printer_preset->name, $printer_preset->config);
  1237. my $filament_stats = $self->{print}->filament_stats;
  1238. my @filament_names = wxTheApp->{preset_bundle}->filament_presets;
  1239. $filament_stats = { map { $filament_names[$_] => $filament_stats->{$_} } keys %$filament_stats };
  1240. $printer_panel->load_print_job($self->{print_file}, $filament_stats);
  1241. $self->GetFrame->select_tab(1);
  1242. }
  1243. # Send $self->{send_gcode_file} to OctoPrint.
  1244. #FIXME Currently this call blocks the UI. Make it asynchronous.
  1245. sub send_gcode {
  1246. my ($self) = @_;
  1247. $self->statusbar->StartBusy;
  1248. my $ua = LWP::UserAgent->new;
  1249. $ua->timeout(180);
  1250. my $enc_path = Slic3r::encode_path($self->{send_gcode_file});
  1251. my $res = $ua->post(
  1252. "http://" . $self->{config}->octoprint_host . "/api/files/local",
  1253. Content_Type => 'form-data',
  1254. 'X-Api-Key' => $self->{config}->octoprint_apikey,
  1255. Content => [
  1256. # OctoPrint doesn't like Windows paths so we use basename()
  1257. # Also, since we need to read from filesystem we process it through encode_path()
  1258. file => [ $enc_path, basename($enc_path) ],
  1259. ],
  1260. );
  1261. $self->statusbar->StopBusy;
  1262. if ($res->is_success) {
  1263. $self->statusbar->SetStatusText("G-code file successfully uploaded to the OctoPrint server");
  1264. } else {
  1265. my $message = "Error while uploading to the OctoPrint server: " . $res->status_line;
  1266. Slic3r::GUI::show_error($self, $message);
  1267. $self->statusbar->SetStatusText($message);
  1268. }
  1269. }
  1270. sub export_stl {
  1271. my ($self) = @_;
  1272. return if !@{$self->{objects}};
  1273. # Ask user for a file name to write into.
  1274. my $output_file = $self->_get_export_file('STL') or return;
  1275. # Store a binary STL.
  1276. $self->{model}->store_stl($output_file, 1);
  1277. $self->statusbar->SetStatusText("STL file exported to $output_file");
  1278. }
  1279. sub reload_from_disk {
  1280. my ($self) = @_;
  1281. my ($obj_idx, $object) = $self->selected_object;
  1282. return if !defined $obj_idx;
  1283. my $model_object = $self->{model}->objects->[$obj_idx];
  1284. return if !$model_object->input_file
  1285. || !-e $model_object->input_file;
  1286. my @new_obj_idx = $self->load_files([$model_object->input_file]);
  1287. return if !@new_obj_idx;
  1288. foreach my $new_obj_idx (@new_obj_idx) {
  1289. my $o = $self->{model}->objects->[$new_obj_idx];
  1290. $o->clear_instances;
  1291. $o->add_instance($_) for @{$model_object->instances};
  1292. if ($o->volumes_count == $model_object->volumes_count) {
  1293. for my $i (0..($o->volumes_count-1)) {
  1294. $o->get_volume($i)->config->apply($model_object->get_volume($i)->config);
  1295. }
  1296. }
  1297. }
  1298. $self->remove($obj_idx);
  1299. }
  1300. sub export_object_stl {
  1301. my ($self) = @_;
  1302. my ($obj_idx, $object) = $self->selected_object;
  1303. return if !defined $obj_idx;
  1304. my $model_object = $self->{model}->objects->[$obj_idx];
  1305. # Ask user for a file name to write into.
  1306. my $output_file = $self->_get_export_file('STL') or return;
  1307. $model_object->mesh->write_binary($output_file);
  1308. $self->statusbar->SetStatusText("STL file exported to $output_file");
  1309. }
  1310. sub export_amf {
  1311. my ($self) = @_;
  1312. return if !@{$self->{objects}};
  1313. # Ask user for a file name to write into.
  1314. my $output_file = $self->_get_export_file('AMF') or return;
  1315. $self->{model}->store_amf($output_file);
  1316. $self->statusbar->SetStatusText("AMF file exported to $output_file");
  1317. }
  1318. # Ask user to select an output file for a given file format (STl, AMF, 3MF).
  1319. # Propose a default file name based on the 'output_filename_format' configuration value.
  1320. sub _get_export_file {
  1321. my ($self, $format) = @_;
  1322. my $suffix = $format eq 'STL' ? '.stl' : '.amf.xml';
  1323. my $output_file = $self->{print}->output_filepath($main::opt{output} // '');
  1324. $output_file =~ s/\.[gG][cC][oO][dD][eE]$/$suffix/;
  1325. my $dlg = Wx::FileDialog->new($self, "Save $format file as:", dirname($output_file),
  1326. basename($output_file), &Slic3r::GUI::MODEL_WILDCARD, wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
  1327. if ($dlg->ShowModal != wxID_OK) {
  1328. $dlg->Destroy;
  1329. return undef;
  1330. }
  1331. $output_file = $dlg->GetPath;
  1332. $dlg->Destroy;
  1333. return $output_file;
  1334. }
  1335. sub reset_thumbnail {
  1336. my ($self, $obj_idx) = @_;
  1337. $self->{objects}[$obj_idx]->thumbnail(undef);
  1338. }
  1339. # this method gets called whenever print center is changed or the objects' bounding box changes
  1340. # (i.e. when an object is added/removed/moved/rotated/scaled)
  1341. sub update {
  1342. my ($self, $force_autocenter) = @_;
  1343. if (wxTheApp->{app_config}->get("autocenter") || $force_autocenter) {
  1344. $self->{model}->center_instances_around_point($self->bed_centerf);
  1345. }
  1346. my $running = $self->pause_background_process;
  1347. my $invalidated = $self->{print}->reload_model_instances();
  1348. # The mere fact that no steps were invalidated when reloading model instances
  1349. # doesn't mean that all steps were done: for example, validation might have
  1350. # failed upon previous instance move, so we have no running thread and no steps
  1351. # are invalidated on this move, thus we need to schedule a new run.
  1352. if ($invalidated || !$running) {
  1353. $self->schedule_background_process;
  1354. } else {
  1355. $self->resume_background_process;
  1356. }
  1357. $self->{canvas}->reload_scene if $self->{canvas};
  1358. $self->{canvas3D}->reload_scene if $self->{canvas3D};
  1359. $self->{preview3D}->reload_print if $self->{preview3D};
  1360. }
  1361. # When a number of extruders changes, the UI needs to be updated to show a single filament selection combo box per extruder.
  1362. # Also the wxTheApp->{preset_bundle}->filament_presets needs to be resized accordingly
  1363. # and some reasonable default has to be selected for the additional extruders.
  1364. sub on_extruders_change {
  1365. my ($self, $num_extruders) = @_;
  1366. my $choices = $self->{preset_choosers}{filament};
  1367. while (int(@$choices) < $num_extruders) {
  1368. # copy strings from first choice
  1369. my @presets = $choices->[0]->GetStrings;
  1370. # initialize new choice
  1371. my $choice = Wx::BitmapComboBox->new($self, -1, "", wxDefaultPosition, wxDefaultSize, [@presets], wxCB_READONLY);
  1372. my $extruder_idx = scalar @$choices;
  1373. EVT_LEFT_DOWN($choice, sub { $self->filament_color_box_lmouse_down($extruder_idx, @_); } );
  1374. push @$choices, $choice;
  1375. # copy icons from first choice
  1376. $choice->SetItemBitmap($_, $choices->[0]->GetItemBitmap($_)) for 0..$#presets;
  1377. # insert new choice into sizer
  1378. $self->{presets_sizer}->Insert(4 + ($#$choices-1)*2, 0, 0);
  1379. $self->{presets_sizer}->Insert(5 + ($#$choices-1)*2, $choice, 0, wxEXPAND | wxBOTTOM, FILAMENT_CHOOSERS_SPACING);
  1380. # setup the listener
  1381. EVT_COMBOBOX($choice, $choice, sub {
  1382. my ($choice) = @_;
  1383. wxTheApp->CallAfter(sub {
  1384. $self->_on_select_preset('filament', $choice, $extruder_idx);
  1385. });
  1386. });
  1387. # initialize selection
  1388. wxTheApp->{preset_bundle}->update_platter_filament_ui($extruder_idx, $choice);
  1389. }
  1390. # remove unused choices if any
  1391. while (@$choices > $num_extruders) {
  1392. $self->{presets_sizer}->Remove(4 + ($#$choices-1)*2); # label
  1393. $self->{presets_sizer}->Remove(4 + ($#$choices-1)*2); # wxChoice
  1394. $choices->[-1]->Destroy;
  1395. pop @$choices;
  1396. }
  1397. $self->Layout;
  1398. }
  1399. sub on_config_change {
  1400. my ($self, $config) = @_;
  1401. my $update_scheduled;
  1402. foreach my $opt_key (@{$self->{config}->diff($config)}) {
  1403. $self->{config}->set($opt_key, $config->get($opt_key));
  1404. if ($opt_key eq 'bed_shape') {
  1405. $self->{canvas}->update_bed_size;
  1406. $self->{canvas3D}->update_bed_size if $self->{canvas3D};
  1407. $self->{preview3D}->set_bed_shape($self->{config}->bed_shape)
  1408. if $self->{preview3D};
  1409. $update_scheduled = 1;
  1410. } elsif ($opt_key =~ '^wipe_tower' || $opt_key eq 'single_extruder_multi_material') {
  1411. $update_scheduled = 1;
  1412. } elsif ($opt_key eq 'serial_port') {
  1413. $self->{btn_print}->Show($config->get('serial_port'));
  1414. $self->Layout;
  1415. } elsif ($opt_key eq 'octoprint_host') {
  1416. $self->{btn_send_gcode}->Show($config->get('octoprint_host'));
  1417. $self->Layout;
  1418. } elsif ($opt_key eq 'variable_layer_height') {
  1419. if ($config->get('variable_layer_height') != 1) {
  1420. if ($self->{htoolbar}) {
  1421. $self->{htoolbar}->EnableTool(TB_LAYER_EDITING, 0);
  1422. $self->{htoolbar}->ToggleTool(TB_LAYER_EDITING, 0);
  1423. } else {
  1424. $self->{"btn_layer_editing"}->Disable;
  1425. $self->{"btn_layer_editing"}->SetValue(0);
  1426. }
  1427. $self->{canvas3D}->layer_editing_enabled(0);
  1428. $self->{canvas3D}->Refresh;
  1429. $self->{canvas3D}->Update;
  1430. } elsif ($self->{canvas3D}->layer_editing_allowed) {
  1431. # Want to allow the layer editing, but do it only if the OpenGL supports it.
  1432. if ($self->{htoolbar}) {
  1433. $self->{htoolbar}->EnableTool(TB_LAYER_EDITING, 1);
  1434. } else {
  1435. $self->{"btn_layer_editing"}->Enable;
  1436. }
  1437. }
  1438. } elsif ($opt_key eq 'extruder_colour') {
  1439. $update_scheduled = 1;
  1440. my $extruder_colors = $config->get('extruder_colour');
  1441. $self->{preview3D}->set_number_extruders(scalar(@{$extruder_colors}));
  1442. }
  1443. }
  1444. $self->update if $update_scheduled;
  1445. return if !$self->GetFrame->is_loaded;
  1446. # (re)start timer
  1447. $self->schedule_background_process;
  1448. }
  1449. sub list_item_deselected {
  1450. my ($self, $event) = @_;
  1451. return if $PreventListEvents;
  1452. if ($self->{list}->GetFirstSelected == -1) {
  1453. $self->select_object(undef);
  1454. $self->{canvas}->Refresh;
  1455. #FIXME VBOs are being refreshed just to change a selection color?
  1456. $self->{canvas3D}->reload_scene if $self->{canvas3D};
  1457. }
  1458. }
  1459. sub list_item_selected {
  1460. my ($self, $event) = @_;
  1461. return if $PreventListEvents;
  1462. my $obj_idx = $event->GetIndex;
  1463. $self->select_object($obj_idx);
  1464. $self->{canvas}->Refresh;
  1465. #FIXME VBOs are being refreshed just to change a selection color?
  1466. $self->{canvas3D}->reload_scene if $self->{canvas3D};
  1467. }
  1468. sub list_item_activated {
  1469. my ($self, $event, $obj_idx) = @_;
  1470. $obj_idx //= $event->GetIndex;
  1471. $self->object_settings_dialog($obj_idx);
  1472. }
  1473. # Called when clicked on the filament preset combo box.
  1474. # When clicked on the icon, show the color picker.
  1475. sub filament_color_box_lmouse_down
  1476. {
  1477. my ($self, $extruder_idx, $combobox, $event) = @_;
  1478. my $pos = $event->GetLogicalPosition(Wx::ClientDC->new($combobox));
  1479. my( $x, $y ) = ( $pos->x, $pos->y );
  1480. if ($x > 24) {
  1481. # Let the combo box process the mouse click.
  1482. $event->Skip;
  1483. } else {
  1484. # Swallow the mouse click and open the color picker.
  1485. my $data = Wx::ColourData->new;
  1486. $data->SetChooseFull(1);
  1487. my $dialog = Wx::ColourDialog->new($self->GetFrame, $data);
  1488. if ($dialog->ShowModal == wxID_OK) {
  1489. my $cfg = Slic3r::Config->new;
  1490. my $colors = wxTheApp->{preset_bundle}->full_config->get('extruder_colour');
  1491. $colors->[$extruder_idx] = $dialog->GetColourData->GetColour->GetAsString(wxC2S_HTML_SYNTAX);
  1492. $cfg->set('extruder_colour', $colors);
  1493. $self->GetFrame->{options_tabs}{printer}->load_config($cfg);
  1494. wxTheApp->{preset_bundle}->update_platter_filament_ui($extruder_idx, $combobox);
  1495. }
  1496. $dialog->Destroy();
  1497. }
  1498. }
  1499. sub object_cut_dialog {
  1500. my ($self, $obj_idx) = @_;
  1501. if (!defined $obj_idx) {
  1502. ($obj_idx, undef) = $self->selected_object;
  1503. }
  1504. if (!$Slic3r::GUI::have_OpenGL) {
  1505. Slic3r::GUI::show_error($self, "Please install the OpenGL modules to use this feature (see build instructions).");
  1506. return;
  1507. }
  1508. my $dlg = Slic3r::GUI::Plater::ObjectCutDialog->new($self,
  1509. object => $self->{objects}[$obj_idx],
  1510. model_object => $self->{model}->objects->[$obj_idx],
  1511. );
  1512. return unless $dlg->ShowModal == wxID_OK;
  1513. if (my @new_objects = $dlg->NewModelObjects) {
  1514. $self->remove($obj_idx);
  1515. $self->load_model_objects(grep defined($_), @new_objects);
  1516. $self->arrange;
  1517. }
  1518. }
  1519. sub object_settings_dialog {
  1520. my ($self, $obj_idx) = @_;
  1521. ($obj_idx, undef) = $self->selected_object if !defined $obj_idx;
  1522. my $model_object = $self->{model}->objects->[$obj_idx];
  1523. # validate config before opening the settings dialog because
  1524. # that dialog can't be closed if validation fails, but user
  1525. # can't fix any error which is outside that dialog
  1526. eval { wxTheApp->{preset_bundle}->full_config->validate; };
  1527. return if Slic3r::GUI::catch_error($_[0]);
  1528. my $dlg = Slic3r::GUI::Plater::ObjectSettingsDialog->new($self,
  1529. object => $self->{objects}[$obj_idx],
  1530. model_object => $model_object,
  1531. config => wxTheApp->{preset_bundle}->full_config,
  1532. );
  1533. $self->pause_background_process;
  1534. $dlg->ShowModal;
  1535. # update thumbnail since parts may have changed
  1536. if ($dlg->PartsChanged) {
  1537. # recenter and re-align to Z = 0
  1538. $model_object->center_around_origin;
  1539. $self->reset_thumbnail($obj_idx);
  1540. }
  1541. # update print
  1542. if ($dlg->PartsChanged || $dlg->PartSettingsChanged) {
  1543. $self->stop_background_process;
  1544. $self->{print}->reload_object($obj_idx);
  1545. $self->schedule_background_process;
  1546. $self->{canvas}->reload_scene if $self->{canvas};
  1547. $self->{canvas3D}->reload_scene if $self->{canvas3D};
  1548. } else {
  1549. $self->resume_background_process;
  1550. }
  1551. }
  1552. # Called to update various buttons depending on whether there are any objects or
  1553. # whether background processing (export of a G-code, sending to Octoprint, forced background re-slicing) is active.
  1554. sub object_list_changed {
  1555. my $self = shift;
  1556. # Enable/disable buttons depending on whether there are any objects on the platter.
  1557. my $have_objects = @{$self->{objects}} ? 1 : 0;
  1558. my $variable_layer_height_allowed = $self->{config}->variable_layer_height && $self->{canvas3D}->layer_editing_allowed;
  1559. if ($self->{htoolbar}) {
  1560. # On OSX or Linux
  1561. $self->{htoolbar}->EnableTool($_, $have_objects)
  1562. for (TB_RESET, TB_ARRANGE, TB_LAYER_EDITING);
  1563. $self->{htoolbar}->EnableTool(TB_LAYER_EDITING, 0) if (! $variable_layer_height_allowed);
  1564. } else {
  1565. # On MSW
  1566. my $method = $have_objects ? 'Enable' : 'Disable';
  1567. $self->{"btn_$_"}->$method
  1568. for grep $self->{"btn_$_"}, qw(reset arrange reslice export_gcode export_stl print send_gcode layer_editing);
  1569. $self->{"btn_layer_editing"}->Disable if (! $variable_layer_height_allowed);
  1570. }
  1571. my $export_in_progress = $self->{export_gcode_output_file} || $self->{send_gcode_file};
  1572. my $method = ($have_objects && ! $export_in_progress) ? 'Enable' : 'Disable';
  1573. $self->{"btn_$_"}->$method
  1574. for grep $self->{"btn_$_"}, qw(reslice export_gcode print send_gcode);
  1575. }
  1576. # Selection of an active 3D object changed.
  1577. sub selection_changed {
  1578. my ($self) = @_;
  1579. my ($obj_idx, $object) = $self->selected_object;
  1580. my $have_sel = defined $obj_idx;
  1581. if ($self->{htoolbar}) {
  1582. # On OSX or Linux
  1583. $self->{htoolbar}->EnableTool($_, $have_sel)
  1584. for (TB_REMOVE, TB_MORE, TB_FEWER, TB_45CW, TB_45CCW, TB_SCALE, TB_SPLIT, TB_CUT, TB_SETTINGS);
  1585. } else {
  1586. # On MSW
  1587. my $method = $have_sel ? 'Enable' : 'Disable';
  1588. $self->{"btn_$_"}->$method
  1589. for grep $self->{"btn_$_"}, qw(remove increase decrease rotate45cw rotate45ccw changescale split cut settings);
  1590. }
  1591. if ($self->{object_info_size}) { # have we already loaded the info pane?
  1592. if ($have_sel) {
  1593. my $model_object = $self->{model}->objects->[$obj_idx];
  1594. #FIXME print_info runs model fixing in two rounds, it is very slow, it should not be performed here!
  1595. # $model_object->print_info;
  1596. my $model_instance = $model_object->instances->[0];
  1597. $self->{object_info_size}->SetLabel(sprintf("%.2f x %.2f x %.2f", @{$model_object->instance_bounding_box(0)->size}));
  1598. $self->{object_info_materials}->SetLabel($model_object->materials_count);
  1599. if (my $stats = $model_object->mesh_stats) {
  1600. $self->{object_info_volume}->SetLabel(sprintf('%.2f', $stats->{volume} * ($model_instance->scaling_factor**3)));
  1601. $self->{object_info_facets}->SetLabel(sprintf('%d (%d shells)', $model_object->facets_count, $stats->{number_of_parts}));
  1602. if (my $errors = sum(@$stats{qw(degenerate_facets edges_fixed facets_removed facets_added facets_reversed backwards_edges)})) {
  1603. $self->{object_info_manifold}->SetLabel(sprintf("Auto-repaired (%d errors)", $errors));
  1604. $self->{object_info_manifold_warning_icon}->Show;
  1605. # we don't show normals_fixed because we never provide normals
  1606. # to admesh, so it generates normals for all facets
  1607. my $message = sprintf '%d degenerate facets, %d edges fixed, %d facets removed, %d facets added, %d facets reversed, %d backwards edges',
  1608. @$stats{qw(degenerate_facets edges_fixed facets_removed facets_added facets_reversed backwards_edges)};
  1609. $self->{object_info_manifold}->SetToolTipString($message);
  1610. $self->{object_info_manifold_warning_icon}->SetToolTipString($message);
  1611. } else {
  1612. $self->{object_info_manifold}->SetLabel("Yes");
  1613. }
  1614. } else {
  1615. $self->{object_info_facets}->SetLabel($object->facets);
  1616. }
  1617. } else {
  1618. $self->{"object_info_$_"}->SetLabel("") for qw(size volume facets materials manifold);
  1619. $self->{object_info_manifold_warning_icon}->Hide;
  1620. $self->{object_info_manifold}->SetToolTipString("");
  1621. }
  1622. $self->Layout;
  1623. }
  1624. # prepagate the event to the frame (a custom Wx event would be cleaner)
  1625. $self->GetFrame->on_plater_selection_changed($have_sel);
  1626. }
  1627. sub select_object {
  1628. my ($self, $obj_idx) = @_;
  1629. $_->selected(0) for @{ $self->{objects} };
  1630. if (defined $obj_idx) {
  1631. $self->{objects}->[$obj_idx]->selected(1);
  1632. # We use this flag to avoid circular event handling
  1633. # Select() happens to fire a wxEVT_LIST_ITEM_SELECTED on Windows,
  1634. # whose event handler calls this method again and again and again
  1635. $PreventListEvents = 1;
  1636. $self->{list}->Select($obj_idx, 1);
  1637. $PreventListEvents = 0;
  1638. } else {
  1639. # TODO: deselect all in list
  1640. }
  1641. $self->selection_changed(1);
  1642. }
  1643. sub selected_object {
  1644. my ($self) = @_;
  1645. my $obj_idx = first { $self->{objects}[$_]->selected } 0..$#{ $self->{objects} };
  1646. return defined $obj_idx ? ($obj_idx, $self->{objects}[$obj_idx]) : undef;
  1647. }
  1648. sub statusbar {
  1649. return $_[0]->GetFrame->{statusbar};
  1650. }
  1651. sub object_menu {
  1652. my ($self) = @_;
  1653. my $frame = $self->GetFrame;
  1654. my $menu = Wx::Menu->new;
  1655. $frame->_append_menu_item($menu, "Delete\t\xA0Del", 'Remove the selected object', sub {
  1656. $self->remove;
  1657. }, undef, 'brick_delete.png');
  1658. $frame->_append_menu_item($menu, "Increase copies\t\xA0+", 'Place one more copy of the selected object', sub {
  1659. $self->increase;
  1660. }, undef, 'add.png');
  1661. $frame->_append_menu_item($menu, "Decrease copies\t\xA0-", 'Remove one copy of the selected object', sub {
  1662. $self->decrease;
  1663. }, undef, 'delete.png');
  1664. $frame->_append_menu_item($menu, "Set number of copies…", 'Change the number of copies of the selected object', sub {
  1665. $self->set_number_of_copies;
  1666. }, undef, 'textfield.png');
  1667. $menu->AppendSeparator();
  1668. $frame->_append_menu_item($menu, "Rotate 45° clockwise\t\xA0l", 'Rotate the selected object by 45° clockwise', sub {
  1669. $self->rotate(-45, Z, 'relative');
  1670. }, undef, 'arrow_rotate_clockwise.png');
  1671. $frame->_append_menu_item($menu, "Rotate 45° counter-clockwise\t\xA0r", 'Rotate the selected object by 45° counter-clockwise', sub {
  1672. $self->rotate(+45, Z, 'relative');
  1673. }, undef, 'arrow_rotate_anticlockwise.png');
  1674. my $rotateMenu = Wx::Menu->new;
  1675. my $rotateMenuItem = $menu->AppendSubMenu($rotateMenu, "Rotate", 'Rotate the selected object by an arbitrary angle');
  1676. $frame->_set_menu_item_icon($rotateMenuItem, 'textfield.png');
  1677. $frame->_append_menu_item($rotateMenu, "Around X axis…", 'Rotate the selected object by an arbitrary angle around X axis', sub {
  1678. $self->rotate(undef, X);
  1679. }, undef, 'bullet_red.png');
  1680. $frame->_append_menu_item($rotateMenu, "Around Y axis…", 'Rotate the selected object by an arbitrary angle around Y axis', sub {
  1681. $self->rotate(undef, Y);
  1682. }, undef, 'bullet_green.png');
  1683. $frame->_append_menu_item($rotateMenu, "Around Z axis…", 'Rotate the selected object by an arbitrary angle around Z axis', sub {
  1684. $self->rotate(undef, Z);
  1685. }, undef, 'bullet_blue.png');
  1686. my $mirrorMenu = Wx::Menu->new;
  1687. my $mirrorMenuItem = $menu->AppendSubMenu($mirrorMenu, "Mirror", 'Mirror the selected object');
  1688. $frame->_set_menu_item_icon($mirrorMenuItem, 'shape_flip_horizontal.png');
  1689. $frame->_append_menu_item($mirrorMenu, "Along X axis…", 'Mirror the selected object along the X axis', sub {
  1690. $self->mirror(X);
  1691. }, undef, 'bullet_red.png');
  1692. $frame->_append_menu_item($mirrorMenu, "Along Y axis…", 'Mirror the selected object along the Y axis', sub {
  1693. $self->mirror(Y);
  1694. }, undef, 'bullet_green.png');
  1695. $frame->_append_menu_item($mirrorMenu, "Along Z axis…", 'Mirror the selected object along the Z axis', sub {
  1696. $self->mirror(Z);
  1697. }, undef, 'bullet_blue.png');
  1698. my $scaleMenu = Wx::Menu->new;
  1699. my $scaleMenuItem = $menu->AppendSubMenu($scaleMenu, "Scale", 'Scale the selected object along a single axis');
  1700. $frame->_set_menu_item_icon($scaleMenuItem, 'arrow_out.png');
  1701. $frame->_append_menu_item($scaleMenu, "Uniformly…\t\xA0s", 'Scale the selected object along the XYZ axes', sub {
  1702. $self->changescale(undef);
  1703. });
  1704. $frame->_append_menu_item($scaleMenu, "Along X axis…", 'Scale the selected object along the X axis', sub {
  1705. $self->changescale(X);
  1706. }, undef, 'bullet_red.png');
  1707. $frame->_append_menu_item($scaleMenu, "Along Y axis…", 'Scale the selected object along the Y axis', sub {
  1708. $self->changescale(Y);
  1709. }, undef, 'bullet_green.png');
  1710. $frame->_append_menu_item($scaleMenu, "Along Z axis…", 'Scale the selected object along the Z axis', sub {
  1711. $self->changescale(Z);
  1712. }, undef, 'bullet_blue.png');
  1713. my $scaleToSizeMenu = Wx::Menu->new;
  1714. my $scaleToSizeMenuItem = $menu->AppendSubMenu($scaleToSizeMenu, "Scale to size", 'Scale the selected object along a single axis');
  1715. $frame->_set_menu_item_icon($scaleToSizeMenuItem, 'arrow_out.png');
  1716. $frame->_append_menu_item($scaleToSizeMenu, "Uniformly…", 'Scale the selected object along the XYZ axes', sub {
  1717. $self->changescale(undef, 1);
  1718. });
  1719. $frame->_append_menu_item($scaleToSizeMenu, "Along X axis…", 'Scale the selected object along the X axis', sub {
  1720. $self->changescale(X, 1);
  1721. }, undef, 'bullet_red.png');
  1722. $frame->_append_menu_item($scaleToSizeMenu, "Along Y axis…", 'Scale the selected object along the Y axis', sub {
  1723. $self->changescale(Y, 1);
  1724. }, undef, 'bullet_green.png');
  1725. $frame->_append_menu_item($scaleToSizeMenu, "Along Z axis…", 'Scale the selected object along the Z axis', sub {
  1726. $self->changescale(Z, 1);
  1727. }, undef, 'bullet_blue.png');
  1728. $frame->_append_menu_item($menu, "Split", 'Split the selected object into individual parts', sub {
  1729. $self->split_object;
  1730. }, undef, 'shape_ungroup.png');
  1731. $frame->_append_menu_item($menu, "Cut…", 'Open the 3D cutting tool', sub {
  1732. $self->object_cut_dialog;
  1733. }, undef, 'package.png');
  1734. $menu->AppendSeparator();
  1735. $frame->_append_menu_item($menu, "Settings…", 'Open the object editor dialog', sub {
  1736. $self->object_settings_dialog;
  1737. }, undef, 'cog.png');
  1738. $menu->AppendSeparator();
  1739. $frame->_append_menu_item($menu, "Reload from Disk", 'Reload the selected file from Disk', sub {
  1740. $self->reload_from_disk;
  1741. }, undef, 'arrow_refresh.png');
  1742. $frame->_append_menu_item($menu, "Export object as STL…", 'Export this single object as STL file', sub {
  1743. $self->export_object_stl;
  1744. }, undef, 'brick_go.png');
  1745. return $menu;
  1746. }
  1747. # Set a camera direction, zoom to all objects.
  1748. sub select_view {
  1749. my ($self, $direction) = @_;
  1750. my $idx_page = $self->{preview_notebook}->GetSelection;
  1751. my $page = ($idx_page == &Wx::wxNOT_FOUND) ? '3D' : $self->{preview_notebook}->GetPageText($idx_page);
  1752. if ($page eq 'Preview') {
  1753. $self->{preview3D}->canvas->select_view($direction);
  1754. $self->{canvas3D}->set_viewport_from_scene($self->{preview3D}->canvas);
  1755. } else {
  1756. $self->{canvas3D}->select_view($direction);
  1757. $self->{preview3D}->canvas->set_viewport_from_scene($self->{canvas3D});
  1758. }
  1759. }
  1760. package Slic3r::GUI::Plater::DropTarget;
  1761. use Wx::DND;
  1762. use base 'Wx::FileDropTarget';
  1763. sub new {
  1764. my ($class, $window) = @_;
  1765. my $self = $class->SUPER::new;
  1766. $self->{window} = $window;
  1767. return $self;
  1768. }
  1769. sub OnDropFiles {
  1770. my ($self, $x, $y, $filenames) = @_;
  1771. # stop scalars leaking on older perl
  1772. # https://rt.perl.org/rt3/Public/Bug/Display.html?id=70602
  1773. @_ = ();
  1774. # only accept STL, OBJ and AMF files
  1775. return 0 if grep !/\.(?:[sS][tT][lL]|[oO][bB][jJ]|[aA][mM][fF](?:\.[xX][mM][lL])?|[pP][rR][uU][sS][aA])$/, @$filenames;
  1776. $self->{window}->load_files($filenames);
  1777. }
  1778. # 2D preview of an object. Each object is previewed by its convex hull.
  1779. package Slic3r::GUI::Plater::Object;
  1780. use Moo;
  1781. has 'name' => (is => 'rw', required => 1);
  1782. has 'thumbnail' => (is => 'rw'); # ExPolygon::Collection in scaled model units with no transforms
  1783. has 'transformed_thumbnail' => (is => 'rw');
  1784. has 'instance_thumbnails' => (is => 'ro', default => sub { [] }); # array of ExPolygon::Collection objects, each one representing the actual placed thumbnail of each instance in pixel units
  1785. has 'selected' => (is => 'rw', default => sub { 0 });
  1786. sub make_thumbnail {
  1787. my ($self, $model, $obj_idx) = @_;
  1788. # make method idempotent
  1789. $self->thumbnail->clear;
  1790. # raw_mesh is the non-transformed (non-rotated, non-scaled, non-translated) sum of non-modifier object volumes.
  1791. my $mesh = $model->objects->[$obj_idx]->raw_mesh;
  1792. #FIXME The "correct" variant could be extremely slow.
  1793. # if ($mesh->facets_count <= 5000) {
  1794. # # remove polygons with area <= 1mm
  1795. # my $area_threshold = Slic3r::Geometry::scale 1;
  1796. # $self->thumbnail->append(
  1797. # grep $_->area >= $area_threshold,
  1798. # @{ $mesh->horizontal_projection }, # horizontal_projection returns scaled expolygons
  1799. # );
  1800. # $self->thumbnail->simplify(0.5);
  1801. # } else {
  1802. my $convex_hull = Slic3r::ExPolygon->new($mesh->convex_hull);
  1803. $self->thumbnail->append($convex_hull);
  1804. # }
  1805. return $self->thumbnail;
  1806. }
  1807. sub transform_thumbnail {
  1808. my ($self, $model, $obj_idx) = @_;
  1809. return unless defined $self->thumbnail;
  1810. my $model_object = $model->objects->[$obj_idx];
  1811. my $model_instance = $model_object->instances->[0];
  1812. # the order of these transformations MUST be the same everywhere, including
  1813. # in Slic3r::Print->add_model_object()
  1814. my $t = $self->thumbnail->clone;
  1815. $t->rotate($model_instance->rotation, Slic3r::Point->new(0,0));
  1816. $t->scale($model_instance->scaling_factor);
  1817. $self->transformed_thumbnail($t);
  1818. }
  1819. 1;