Plater.pm 100 KB

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