Plater.pm 91 KB

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