Plater.pm 88 KB

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