GCode.pm 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. package Slic3r::GCode;
  2. use Moo;
  3. use List::Util qw(min max first);
  4. use Slic3r::ExtrusionPath ':roles';
  5. use Slic3r::Geometry qw(epsilon scale unscale scaled_epsilon points_coincide PI X Y B);
  6. use Slic3r::Geometry::Clipper qw(union_ex);
  7. use Slic3r::Surface ':types';
  8. has 'config' => (is => 'ro', required => 1);
  9. has 'extruders' => (is => 'ro', default => sub {0}, required => 1);
  10. has 'multiple_extruders' => (is => 'lazy');
  11. has 'enable_loop_clipping' => (is => 'rw', default => sub {1});
  12. has 'enable_wipe' => (is => 'lazy'); # at least one extruder has wipe enabled
  13. has 'layer_count' => (is => 'ro', required => 1 );
  14. has 'layer' => (is => 'rw');
  15. has '_layer_islands' => (is => 'rw');
  16. has '_upper_layer_islands' => (is => 'rw');
  17. has '_layer_overhangs' => (is => 'rw');
  18. has 'shift_x' => (is => 'rw', default => sub {0} );
  19. has 'shift_y' => (is => 'rw', default => sub {0} );
  20. has 'z' => (is => 'rw');
  21. has 'speed' => (is => 'rw');
  22. has 'speeds' => (is => 'lazy'); # mm/min
  23. has 'external_mp' => (is => 'rw');
  24. has 'layer_mp' => (is => 'rw');
  25. has 'new_object' => (is => 'rw', default => sub {0});
  26. has 'straight_once' => (is => 'rw', default => sub {1});
  27. has 'extruder' => (is => 'rw');
  28. has 'elapsed_time' => (is => 'rw', default => sub {0} ); # seconds
  29. has 'total_extrusion_length' => (is => 'rw', default => sub {0} );
  30. has 'lifted' => (is => 'rw', default => sub {0} );
  31. has 'last_pos' => (is => 'rw', default => sub { Slic3r::Point->new(0,0) } );
  32. has 'last_speed' => (is => 'rw', default => sub {""});
  33. has 'last_f' => (is => 'rw', default => sub {""});
  34. has 'last_fan_speed' => (is => 'rw', default => sub {0});
  35. has 'wipe_path' => (is => 'rw');
  36. has 'dec' => (is => 'ro', default => sub { 3 } );
  37. # used for vibration limit:
  38. has 'last_dir' => (is => 'ro', default => sub { [0,0] });
  39. has 'dir_time' => (is => 'ro', default => sub { [0,0] });
  40. sub _build_speeds {
  41. my $self = shift;
  42. return {
  43. map { $_ => 60 * $self->config->get_value("${_}_speed") }
  44. qw(travel perimeter small_perimeter external_perimeter infill
  45. solid_infill top_solid_infill support_material bridge gap_fill retract),
  46. };
  47. }
  48. # assign speeds to roles
  49. my %role_speeds = (
  50. &EXTR_ROLE_PERIMETER => 'perimeter',
  51. &EXTR_ROLE_EXTERNAL_PERIMETER => 'external_perimeter',
  52. &EXTR_ROLE_OVERHANG_PERIMETER => 'bridge',
  53. &EXTR_ROLE_CONTOUR_INTERNAL_PERIMETER => 'perimeter',
  54. &EXTR_ROLE_FILL => 'infill',
  55. &EXTR_ROLE_SOLIDFILL => 'solid_infill',
  56. &EXTR_ROLE_TOPSOLIDFILL => 'top_solid_infill',
  57. &EXTR_ROLE_BRIDGE => 'bridge',
  58. &EXTR_ROLE_INTERNALBRIDGE => 'solid_infill',
  59. &EXTR_ROLE_SKIRT => 'perimeter',
  60. &EXTR_ROLE_SUPPORTMATERIAL => 'support_material',
  61. &EXTR_ROLE_GAPFILL => 'gap_fill',
  62. );
  63. sub _build_multiple_extruders {
  64. my $self = shift;
  65. return @{$self->extruders} > 1;
  66. }
  67. sub _build_enable_wipe {
  68. my $self = shift;
  69. return (first { $_->wipe } @{$self->extruders}) ? 1 : 0;
  70. }
  71. sub set_shift {
  72. my ($self, @shift) = @_;
  73. # if shift increases (goes towards right), last_pos decreases because it goes towards left
  74. my @translate = (
  75. scale ($self->shift_x - $shift[X]),
  76. scale ($self->shift_y - $shift[Y]),
  77. );
  78. $self->last_pos->translate(@translate);
  79. $self->wipe_path->translate(@translate) if $self->wipe_path;
  80. $self->shift_x($shift[X]);
  81. $self->shift_y($shift[Y]);
  82. }
  83. sub change_layer {
  84. my ($self, $layer) = @_;
  85. $self->layer($layer);
  86. # avoid computing islands and overhangs if they're not needed
  87. if ($self->config->only_retract_when_crossing_perimeters) {
  88. $self->_layer_islands([ $layer->islands ]);
  89. $self->_upper_layer_islands([ $layer->upper_layer_islands ]);
  90. } else {
  91. $self->_layer_islands([]);
  92. $self->_upper_layer_islands([]);
  93. }
  94. $self->_layer_overhangs(
  95. $layer->id > 0 && ($layer->config->overhangs || $Slic3r::Config->start_perimeters_at_non_overhang)
  96. ? [ map $_->expolygon, grep $_->surface_type == S_TYPE_BOTTOM, map @{$_->slices}, @{$layer->regions} ]
  97. : []
  98. );
  99. if ($self->config->avoid_crossing_perimeters) {
  100. $self->layer_mp(Slic3r::GCode::MotionPlanner->new(
  101. islands => union_ex([ map @$_, @{$layer->slices} ], 1),
  102. ));
  103. }
  104. my $gcode = "";
  105. if ($self->config->gcode_flavor =~ /^(?:makerware|sailfish)$/) {
  106. $gcode .= sprintf "M73 P%s%s\n",
  107. int(99 * ($layer->id / ($self->layer_count - 1))),
  108. ($self->config->gcode_comments ? ' ; update progress' : '');
  109. }
  110. if ($self->config->first_layer_acceleration) {
  111. if ($layer->id == 0) {
  112. $gcode .= $self->set_acceleration($self->config->first_layer_acceleration);
  113. } elsif ($layer->id == 1) {
  114. $gcode .= $self->set_acceleration($self->config->default_acceleration);
  115. }
  116. }
  117. $gcode .= $self->move_z($layer->print_z);
  118. return $gcode;
  119. }
  120. # this method accepts Z in unscaled coordinates
  121. sub move_z {
  122. my ($self, $z, $comment) = @_;
  123. $z += $self->config->z_offset;
  124. my $gcode = "";
  125. my $current_z = $self->z;
  126. if (!defined $self->z || $z > $self->z) {
  127. # if we're going over the current Z we won't be lifted anymore
  128. $self->lifted(0);
  129. # this retraction may alter $self->z
  130. $gcode .= $self->retract(move_z => $z) if $self->extruder->retract_layer_change;
  131. $self->speed('travel');
  132. $gcode .= $self->G0(undef, $z, 0, $comment || ('move to next layer (' . $self->layer->id . ')'))
  133. if !defined $self->z || abs($z - ($self->z - $self->lifted)) > epsilon;
  134. } elsif ($z < $self->z && $z > ($self->z - $self->lifted + epsilon)) {
  135. # we're moving to a layer height which is greater than the nominal current one
  136. # (nominal = actual - lifted) and less than the actual one. we're basically
  137. # advancing to next layer, whose nominal Z is still lower than the previous
  138. # layer Z with lift.
  139. $self->lifted($self->z - $z);
  140. }
  141. return $gcode;
  142. }
  143. sub extrude {
  144. my $self = shift;
  145. $_[0]->isa('Slic3r::ExtrusionLoop')
  146. ? $self->extrude_loop(@_)
  147. : $self->extrude_path(@_);
  148. }
  149. sub extrude_loop {
  150. my ($self, $loop, $description) = @_;
  151. # extrude all loops ccw
  152. my $was_clockwise = $loop->make_counter_clockwise;
  153. my $polygon = $loop->polygon;
  154. # find candidate starting points
  155. # start looking for concave vertices not being overhangs
  156. my @concave = ();
  157. if ($Slic3r::Config->start_perimeters_at_concave_points) {
  158. @concave = $polygon->concave_points;
  159. }
  160. my @candidates = ();
  161. if ($Slic3r::Config->start_perimeters_at_non_overhang) {
  162. @candidates = grep !Boost::Geometry::Utils::point_covered_by_multi_polygon($_, $self->_layer_overhangs), @concave;
  163. }
  164. if (!@candidates) {
  165. # if none, look for any concave vertex
  166. @candidates = @concave;
  167. if (!@candidates) {
  168. # if none, look for any non-overhang vertex
  169. if ($Slic3r::Config->start_perimeters_at_non_overhang) {
  170. @candidates = grep !Boost::Geometry::Utils::point_covered_by_multi_polygon($_, $self->_layer_overhangs), @{$polygon};
  171. }
  172. if (!@candidates) {
  173. # if none, all points are valid candidates
  174. @candidates = @{$polygon};
  175. }
  176. }
  177. }
  178. # find the point of the loop that is closest to the current extruder position
  179. # or randomize if requested
  180. my $last_pos = $self->last_pos;
  181. if ($self->config->randomize_start && $loop->role == EXTR_ROLE_CONTOUR_INTERNAL_PERIMETER) {
  182. $last_pos = Slic3r::Point->new(scale $self->config->print_center->[X], scale $self->config->bed_size->[Y]);
  183. $last_pos->rotate(rand(2*PI), $self->config->print_center);
  184. }
  185. # split the loop at the starting point and make a path
  186. my $start_at = $last_pos->nearest_point(\@candidates);
  187. my $extrusion_path = $loop->split_at($start_at);
  188. # clip the path to avoid the extruder to get exactly on the first point of the loop;
  189. # if polyline was shorter than the clipping distance we'd get a null polyline, so
  190. # we discard it in that case
  191. $extrusion_path->clip_end(scale $extrusion_path->flow_spacing * &Slic3r::LOOP_CLIPPING_LENGTH_OVER_SPACING)
  192. if $self->enable_loop_clipping;
  193. return '' if !@{$extrusion_path->polyline};
  194. my @paths = ();
  195. # detect overhanging/bridging perimeters
  196. if ($self->layer->config->overhangs && $extrusion_path->is_perimeter && @{$self->_layer_overhangs}) {
  197. # get non-overhang paths by subtracting overhangs from the loop
  198. push @paths,
  199. $extrusion_path->subtract_expolygons($self->_layer_overhangs);
  200. # get overhang paths by intersecting overhangs with the loop
  201. push @paths,
  202. map { $_->role(EXTR_ROLE_OVERHANG_PERIMETER); $_ }
  203. $extrusion_path->intersect_expolygons($self->_layer_overhangs);
  204. # reapply the nearest point search for starting point
  205. @paths = Slic3r::ExtrusionPath::Collection->new(@paths)->chained_path($start_at, 1);
  206. } else {
  207. push @paths, $extrusion_path;
  208. }
  209. # apply the small perimeter speed
  210. my %params = ();
  211. if ($extrusion_path->is_perimeter && abs($extrusion_path->length) <= &Slic3r::SMALL_PERIMETER_LENGTH) {
  212. $params{speed} = 'small_perimeter';
  213. }
  214. # extrude along the path
  215. my $gcode = join '', map $self->extrude_path($_, $description, %params), @paths;
  216. $self->wipe_path($extrusion_path->polyline) if $self->enable_wipe;
  217. # make a little move inwards before leaving loop
  218. if ($loop->role == EXTR_ROLE_EXTERNAL_PERIMETER && defined $self->layer && $self->layer->object->config->perimeters > 1) {
  219. # detect angle between last and first segment
  220. # the side depends on the original winding order of the polygon (left for contours, right for holes)
  221. my @points = $was_clockwise ? (-2, 1) : (1, -2);
  222. my $angle = Slic3r::Geometry::angle3points(@{$extrusion_path->polyline}[0, @points]) / 3;
  223. $angle *= -1 if $was_clockwise;
  224. # create the destination point along the first segment and rotate it
  225. # we make sure we don't exceed the segment length because we don't know
  226. # the rotation of the second segment so we might cross the object boundary
  227. my $first_segment = Slic3r::Line->new(@{$extrusion_path->polyline}[0,1]);
  228. my $distance = min(scale $extrusion_path->flow_spacing, $first_segment->length);
  229. my $point = Slic3r::Geometry::point_along_segment(@$first_segment, $distance);
  230. $point = Slic3r::Point->new(@$point);
  231. $point->rotate($angle, $extrusion_path->first_point);
  232. # generate the travel move
  233. $gcode .= $self->travel_to($point, $loop->role, "move inwards before travel");
  234. }
  235. return $gcode;
  236. }
  237. sub extrude_path {
  238. my ($self, $path, $description, %params) = @_;
  239. $path->simplify(&Slic3r::SCALED_RESOLUTION);
  240. # detect arcs
  241. if ($self->config->gcode_arcs && !$params{dont_detect_arcs}) {
  242. my $gcode = "";
  243. foreach my $arc_path ($path->detect_arcs) {
  244. $gcode .= $self->extrude_path($arc_path, $description, %params, dont_detect_arcs => 1);
  245. }
  246. return $gcode;
  247. }
  248. # go to first point of extrusion path
  249. my $gcode = "";
  250. my $first_point = $path->first_point;
  251. $gcode .= $self->travel_to($first_point, $path->role, "move to first $description point")
  252. if !defined $self->last_pos || !$self->last_pos->coincides_with($first_point);
  253. # compensate retraction
  254. $gcode .= $self->unretract;
  255. # adjust acceleration
  256. my $acceleration;
  257. if (!$self->config->first_layer_acceleration || $self->layer->id != 0) {
  258. if ($self->config->perimeter_acceleration && $path->is_perimeter) {
  259. $acceleration = $self->config->perimeter_acceleration;
  260. } elsif ($self->config->infill_acceleration && $path->is_fill) {
  261. $acceleration = $self->config->infill_acceleration;
  262. } elsif ($self->config->infill_acceleration && $path->is_bridge) {
  263. $acceleration = $self->config->bridge_acceleration;
  264. }
  265. $gcode .= $self->set_acceleration($acceleration) if $acceleration;
  266. }
  267. my $area; # mm^3 of extrudate per mm of tool movement
  268. if ($path->is_bridge) {
  269. my $s = $path->flow_spacing;
  270. $area = ($s**2) * PI/4;
  271. } else {
  272. my $s = $path->flow_spacing;
  273. my $h = (defined $path->height && $path->height != -1) ? $path->height : $self->layer->height;
  274. $area = $self->extruder->mm3_per_mm($s, $h);
  275. }
  276. # calculate extrusion length per distance unit
  277. my $e = $self->extruder->e_per_mm3 * $area;
  278. # set speed
  279. $self->speed( $params{speed} || $role_speeds{$path->role} || die "Unknown role: " . $path->role );
  280. # extrude arc or line
  281. my $path_length = 0;
  282. if ($path->isa('Slic3r::ExtrusionPath::Arc')) {
  283. $path_length = unscale $path->length;
  284. $gcode .= $self->G2_G3($path->points->[-1], $path->orientation,
  285. $path->center, $e * unscale $path_length, $description);
  286. $self->wipe_path(undef);
  287. } else {
  288. foreach my $line (@{$path->lines}) {
  289. my $line_length = unscale($line->length);
  290. $path_length += $line_length;
  291. $gcode .= $self->G1($line->[B], undef, $e * $line_length, $description);
  292. }
  293. $self->wipe_path(Slic3r::Polyline->new(reverse @{$path->points}))
  294. if $self->enable_wipe;
  295. }
  296. if ($self->config->cooling) {
  297. my $path_time = $path_length / $self->speeds->{$self->last_speed} * 60;
  298. if ($self->layer->id == 0) {
  299. $path_time = $self->config->first_layer_speed =~ /^(\d+(?:\.\d+)?)%$/
  300. ? $path_time / ($1/100)
  301. : $path_length / $self->config->first_layer_speed * 60;
  302. }
  303. $self->elapsed_time($self->elapsed_time + $path_time);
  304. }
  305. # reset acceleration
  306. $gcode .= $self->set_acceleration($self->config->default_acceleration)
  307. if $acceleration && $self->config->default_acceleration;
  308. return $gcode;
  309. }
  310. sub travel_to {
  311. my ($self, $point, $role, $comment) = @_;
  312. my $gcode = "";
  313. my $travel = Slic3r::Line->new($self->last_pos, $point);
  314. # move travel back to original layer coordinates for the island check.
  315. # note that we're only considering the current object's islands, while we should
  316. # build a more complete configuration space
  317. $travel->translate(-$self->shift_x, -$self->shift_y);
  318. # skip retraction if the travel move is contained in an island in the current layer
  319. # *and* in an island in the upper layer (so that the ooze will not be visible)
  320. if ($travel->length < scale $self->extruder->retract_before_travel
  321. || ($self->config->only_retract_when_crossing_perimeters
  322. && (first { $_->encloses_line($travel, scaled_epsilon) } @{$self->_upper_layer_islands})
  323. && (first { $_->encloses_line($travel, scaled_epsilon) } @{$self->_layer_islands}))
  324. || ($role == EXTR_ROLE_SUPPORTMATERIAL && (first { $_->encloses_line($travel, scaled_epsilon) } @{$self->layer->support_islands}))
  325. ) {
  326. $self->straight_once(0);
  327. $self->speed('travel');
  328. $gcode .= $self->G0($point, undef, 0, $comment || "");
  329. } elsif (!$self->config->avoid_crossing_perimeters || $self->straight_once) {
  330. $self->straight_once(0);
  331. $gcode .= $self->retract(travel_to => $point);
  332. $self->speed('travel');
  333. $gcode .= $self->G0($point, undef, 0, $comment || "");
  334. } else {
  335. if ($self->new_object) {
  336. $self->new_object(0);
  337. # represent $point in G-code coordinates
  338. $point = $point->clone;
  339. my @shift = ($self->shift_x, $self->shift_y);
  340. $point->translate(map scale $_, @shift);
  341. # calculate path (external_mp uses G-code coordinates so we temporary need a null shift)
  342. $self->set_shift(0,0);
  343. $gcode .= $self->_plan($self->external_mp, $point, $comment);
  344. $self->set_shift(@shift);
  345. } else {
  346. $gcode .= $self->_plan($self->layer_mp, $point, $comment);
  347. }
  348. }
  349. return $gcode;
  350. }
  351. sub _plan {
  352. my ($self, $mp, $point, $comment) = @_;
  353. my $gcode = "";
  354. my @travel = $mp->shortest_path($self->last_pos, $point)->lines;
  355. # if the path is not contained in a single island we need to retract
  356. my $need_retract = !$self->config->only_retract_when_crossing_perimeters;
  357. if (!$need_retract) {
  358. $need_retract = 1;
  359. foreach my $island ($self->layer->upper_layer_islands) {
  360. # discard the island if at any line is not enclosed in it
  361. next if first { !$island->encloses_line($_, scaled_epsilon) } @travel;
  362. # okay, this island encloses the full travel path
  363. $need_retract = 0;
  364. last;
  365. }
  366. }
  367. # do the retract (the travel_to argument is broken)
  368. $gcode .= $self->retract(travel_to => $point) if $need_retract;
  369. # append the actual path and return
  370. $self->speed('travel');
  371. # use G1 because we rely on paths being straight (G0 may make round paths)
  372. $gcode .= join '', map $self->G1($_->[B], undef, 0, $comment || ""), @travel;
  373. return $gcode;
  374. }
  375. sub retract {
  376. my ($self, %params) = @_;
  377. # get the retraction length and abort if none
  378. my ($length, $restart_extra, $comment) = $params{toolchange}
  379. ? ($self->extruder->retract_length_toolchange, $self->extruder->retract_restart_extra_toolchange, "retract for tool change")
  380. : ($self->extruder->retract_length, $self->extruder->retract_restart_extra, "retract");
  381. # if we already retracted, reduce the required amount of retraction
  382. $length -= $self->extruder->retracted;
  383. return "" unless $length > 0;
  384. my $gcode = "";
  385. # wipe
  386. my $wipe_path;
  387. if ($self->extruder->wipe && $self->wipe_path) {
  388. $wipe_path = Slic3r::Polyline->new($self->last_pos, @{$self->wipe_path}[1..$#{$self->wipe_path}])
  389. ->clip_start($self->extruder->scaled_wipe_distance);
  390. }
  391. # prepare moves
  392. my $retract = [undef, undef, -$length, $comment];
  393. my $lift = ($self->extruder->retract_lift == 0 || defined $params{move_z}) && !$self->lifted
  394. ? undef
  395. : [undef, $self->z + $self->extruder->retract_lift, 0, 'lift plate during travel'];
  396. if (($self->config->g0 || $self->config->gcode_flavor eq 'mach3') && $params{travel_to}) {
  397. $self->speed('travel');
  398. if ($lift) {
  399. # combine lift and retract
  400. $lift->[2] = $retract->[2];
  401. $gcode .= $self->G0(@$lift);
  402. } else {
  403. # combine travel and retract
  404. my $travel = [$params{travel_to}, undef, $retract->[2], "travel and $comment"];
  405. $gcode .= $self->G0(@$travel);
  406. }
  407. } elsif (($self->config->g0 || $self->config->gcode_flavor eq 'mach3') && defined $params{move_z}) {
  408. # combine Z change and retraction
  409. $self->speed('travel');
  410. my $travel = [undef, $params{move_z}, $retract->[2], "change layer and $comment"];
  411. $gcode .= $self->G0(@$travel);
  412. } else {
  413. # check that we have a positive wipe length
  414. if ($wipe_path && (my $total_wipe_length = $wipe_path->length)) {
  415. $self->speed('travel');
  416. # subdivide the retraction
  417. my $retracted = 0;
  418. for (1 .. $#$wipe_path) {
  419. my $segment_length = $wipe_path->[$_-1]->distance_to($wipe_path->[$_]);
  420. $retracted += my $e = $retract->[2] * ($segment_length / $total_wipe_length);
  421. $gcode .= $self->G1($wipe_path->[$_], undef, $e, $retract->[3] . ";_WIPE");
  422. }
  423. if ($retracted > $retract->[2]) {
  424. # if we retracted less than we had to, retract the remainder
  425. # TODO: add regression test
  426. $gcode .= $self->G1(undef, undef, $retract->[2] - $retracted, $comment);
  427. }
  428. } else {
  429. $self->speed('retract');
  430. $gcode .= $self->G1(@$retract);
  431. }
  432. if (!$self->lifted) {
  433. $self->speed('travel');
  434. if (defined $params{move_z} && $self->extruder->retract_lift > 0) {
  435. my $travel = [undef, $params{move_z} + $self->extruder->retract_lift, 0, 'move to next layer (' . $self->layer->id . ') and lift'];
  436. $gcode .= $self->G0(@$travel);
  437. $self->lifted($self->extruder->retract_lift);
  438. } elsif ($lift) {
  439. $gcode .= $self->G1(@$lift);
  440. }
  441. }
  442. }
  443. $self->extruder->retracted($self->extruder->retracted + $length);
  444. $self->extruder->restart_extra($restart_extra);
  445. $self->lifted($self->extruder->retract_lift) if $lift;
  446. # reset extrusion distance during retracts
  447. # this makes sure we leave sufficient precision in the firmware
  448. $gcode .= $self->reset_e;
  449. $gcode .= "M103 ; extruder off\n" if $self->config->gcode_flavor eq 'makerware';
  450. return $gcode;
  451. }
  452. sub unretract {
  453. my ($self) = @_;
  454. my $gcode = "";
  455. $gcode .= "M101 ; extruder on\n" if $self->config->gcode_flavor eq 'makerware';
  456. if ($self->lifted) {
  457. $self->speed('travel');
  458. $gcode .= sprintf ";AAA selfz = %s, lifted = %s\n", $self->z // 'nd', $self->lifted // 'nd';
  459. $gcode .= $self->G0(undef, $self->z - $self->lifted, 0, 'restore layer Z');
  460. $self->lifted(0);
  461. }
  462. my $to_unretract = $self->extruder->retracted + $self->extruder->restart_extra;
  463. if ($to_unretract) {
  464. $self->speed('retract');
  465. # use G1 instead of G0 because G0 will blend the restart with the previous travel move
  466. $gcode .= $self->G1(undef, undef, $to_unretract, "compensate retraction");
  467. $self->extruder->retracted(0);
  468. $self->extruder->restart_extra(0);
  469. }
  470. return $gcode;
  471. }
  472. sub reset_e {
  473. my ($self) = @_;
  474. return "" if $self->config->gcode_flavor =~ /^(?:mach3|makerware|sailfish)$/;
  475. $self->extruder->e(0) if $self->extruder;
  476. return sprintf "G92 %s0%s\n", $self->config->extrusion_axis, ($self->config->gcode_comments ? ' ; reset extrusion distance' : '')
  477. if $self->config->extrusion_axis && !$self->config->use_relative_e_distances;
  478. }
  479. sub set_acceleration {
  480. my ($self, $acceleration) = @_;
  481. return "" if !$acceleration;
  482. return sprintf "M204 S%s%s\n",
  483. $acceleration, ($self->config->gcode_comments ? ' ; adjust acceleration' : '');
  484. }
  485. sub G0 {
  486. my $self = shift;
  487. return $self->G1(@_) if !($self->config->g0 || $self->config->gcode_flavor eq 'mach3');
  488. return $self->_G0_G1("G0", @_);
  489. }
  490. sub G1 {
  491. my $self = shift;
  492. return $self->_G0_G1("G1", @_);
  493. }
  494. sub _G0_G1 {
  495. my ($self, $gcode, $point, $z, $e, $comment) = @_;
  496. my $dec = $self->dec;
  497. if (defined $point) {
  498. $gcode .= sprintf " X%.${dec}f Y%.${dec}f",
  499. ($point->x * &Slic3r::SCALING_FACTOR) + $self->shift_x - $self->extruder->extruder_offset->[X],
  500. ($point->y * &Slic3r::SCALING_FACTOR) + $self->shift_y - $self->extruder->extruder_offset->[Y]; #**
  501. $gcode = $self->_limit_frequency($point) . $gcode if $self->config->vibration_limit != 0;
  502. $self->last_pos($point->clone);
  503. }
  504. if (defined $z && (!defined $self->z || $z != $self->z)) {
  505. $self->z($z);
  506. $gcode .= sprintf " Z%.${dec}f", $z;
  507. }
  508. return $self->_Gx($gcode, $e, $comment);
  509. }
  510. sub G2_G3 {
  511. my ($self, $point, $orientation, $center, $e, $comment) = @_;
  512. my $dec = $self->dec;
  513. my $gcode = $orientation eq 'cw' ? "G2" : "G3";
  514. $gcode .= sprintf " X%.${dec}f Y%.${dec}f",
  515. ($point->x * &Slic3r::SCALING_FACTOR) + $self->shift_x - $self->extruder->extruder_offset->[X],
  516. ($point->y * &Slic3r::SCALING_FACTOR) + $self->shift_y - $self->extruder->extruder_offset->[Y]; #**
  517. # XY distance of the center from the start position
  518. $gcode .= sprintf " I%.${dec}f J%.${dec}f",
  519. ($center->[X] - $self->last_pos->[X]) * &Slic3r::SCALING_FACTOR,
  520. ($center->[Y] - $self->last_pos->[Y]) * &Slic3r::SCALING_FACTOR;
  521. $self->last_pos($point);
  522. return $self->_Gx($gcode, $e, $comment);
  523. }
  524. sub _Gx {
  525. my ($self, $gcode, $e, $comment) = @_;
  526. my $dec = $self->dec;
  527. # output speed if it's different from last one used
  528. # (goal: reduce gcode size)
  529. my $append_bridge_off = 0;
  530. my $F;
  531. if ($self->speed ne $self->last_speed) {
  532. if ($self->speed eq 'bridge') {
  533. $gcode = ";_BRIDGE_FAN_START\n$gcode";
  534. } elsif ($self->last_speed eq 'bridge') {
  535. $append_bridge_off = 1;
  536. }
  537. # apply the speed reduction for print moves on bottom layer
  538. $F = $self->speed eq 'retract'
  539. ? ($self->extruder->retract_speed_mm_min)
  540. : $self->speeds->{$self->speed} // $self->speed;
  541. if ($e && $self->layer && $self->layer->id == 0 && $comment !~ /retract/) {
  542. $F = $self->config->first_layer_speed =~ /^(\d+(?:\.\d+)?)%$/
  543. ? ($F * $1/100)
  544. : $self->config->first_layer_speed * 60;
  545. }
  546. $self->last_speed($self->speed);
  547. $self->last_f($F);
  548. }
  549. $gcode .= sprintf " F%.${dec}f", $F if defined $F;
  550. # output extrusion distance
  551. if ($e && $self->config->extrusion_axis) {
  552. $self->extruder->e(0) if $self->config->use_relative_e_distances;
  553. $self->extruder->e($self->extruder->e + $e);
  554. $self->total_extrusion_length($self->total_extrusion_length + $e);
  555. $gcode .= sprintf " %s%.5f", $self->config->extrusion_axis, $self->extruder->e;
  556. }
  557. $gcode .= sprintf " ; %s", $comment if $comment && $self->config->gcode_comments;
  558. if ($append_bridge_off) {
  559. $gcode = ";_BRIDGE_FAN_END\n$gcode";
  560. }
  561. return "$gcode\n";
  562. }
  563. sub set_extruder {
  564. my ($self, $extruder) = @_;
  565. # return nothing if this extruder was already selected
  566. return "" if (defined $self->extruder) && ($self->extruder->id == $extruder->id);
  567. # if we are running a single-extruder setup, just set the extruder and return nothing
  568. if (!$self->multiple_extruders) {
  569. $self->extruder($extruder);
  570. return "";
  571. }
  572. # trigger retraction on the current extruder (if any)
  573. my $gcode = "";
  574. $gcode .= $self->retract(toolchange => 1) if defined $self->extruder;
  575. # append custom toolchange G-code
  576. if (defined $self->extruder && $self->config->toolchange_gcode) {
  577. $gcode .= sprintf "%s\n", $self->config->replace_options($self->config->toolchange_gcode, {
  578. previous_extruder => $self->extruder->id,
  579. next_extruder => $extruder->id,
  580. });
  581. }
  582. # set the new extruder
  583. $self->extruder($extruder);
  584. $gcode .= sprintf "%s%d%s\n",
  585. ($self->config->gcode_flavor eq 'makerware'
  586. ? 'M135 T'
  587. : $self->config->gcode_flavor eq 'sailfish'
  588. ? 'M108 T'
  589. : 'T'),
  590. $extruder->id,
  591. ($self->config->gcode_comments ? ' ; change extruder' : '');
  592. $gcode .= $self->reset_e;
  593. return $gcode;
  594. }
  595. sub set_fan {
  596. my ($self, $speed, $dont_save) = @_;
  597. if ($self->last_fan_speed != $speed || $dont_save) {
  598. $self->last_fan_speed($speed) if !$dont_save;
  599. if ($speed == 0) {
  600. my $code = $self->config->gcode_flavor eq 'teacup'
  601. ? 'M106 S0'
  602. : $self->config->gcode_flavor =~ /^(?:makerware|sailfish)$/
  603. ? 'M127'
  604. : 'M107';
  605. return sprintf "$code%s\n", ($self->config->gcode_comments ? ' ; disable fan' : '');
  606. } else {
  607. if ($self->config->gcode_flavor =~ /^(?:makerware|sailfish)$/) {
  608. return sprintf "M126%s\n", ($self->config->gcode_comments ? ' ; enable fan' : '');
  609. } else {
  610. return sprintf "M106 %s%d%s\n", ($self->config->gcode_flavor eq 'mach3' ? 'P' : 'S'),
  611. (255 * $speed / 100), ($self->config->gcode_comments ? ' ; enable fan' : '');
  612. }
  613. }
  614. }
  615. return "";
  616. }
  617. sub set_temperature {
  618. my ($self, $temperature, $wait, $tool) = @_;
  619. return "" if $wait && $self->config->gcode_flavor =~ /^(?:makerware|sailfish)$/;
  620. my ($code, $comment) = ($wait && $self->config->gcode_flavor ne 'teacup')
  621. ? ('M109', 'wait for temperature to be reached')
  622. : ('M104', 'set temperature');
  623. my $gcode = sprintf "$code %s%d %s; $comment\n",
  624. ($self->config->gcode_flavor eq 'mach3' ? 'P' : 'S'), $temperature,
  625. (defined $tool && ($self->multiple_extruders || $self->config->gcode_flavor =~ /^(?:makerware|sailfish)$/)) ? "T$tool " : "";
  626. $gcode .= "M116 ; wait for temperature to be reached\n"
  627. if $self->config->gcode_flavor eq 'teacup' && $wait;
  628. return $gcode;
  629. }
  630. sub set_bed_temperature {
  631. my ($self, $temperature, $wait) = @_;
  632. my ($code, $comment) = ($wait && $self->config->gcode_flavor ne 'teacup')
  633. ? (($self->config->gcode_flavor =~ /^(?:makerware|sailfish)$/ ? 'M109' : 'M190'), 'wait for bed temperature to be reached')
  634. : ('M140', 'set bed temperature');
  635. my $gcode = sprintf "$code %s%d ; $comment\n",
  636. ($self->config->gcode_flavor eq 'mach3' ? 'P' : 'S'), $temperature;
  637. $gcode .= "M116 ; wait for bed temperature to be reached\n"
  638. if $self->config->gcode_flavor eq 'teacup' && $wait;
  639. return $gcode;
  640. }
  641. # http://hydraraptor.blogspot.it/2010/12/frequency-limit.html
  642. sub _limit_frequency {
  643. my ($self, $point) = @_;
  644. my $min_time = 1 / ($self->config->vibration_limit * 60); # in minutes
  645. # calculate the move vector and move direction
  646. my $vector = Slic3r::Line->new($self->last_pos, $point)->vector;
  647. my @dir = map { $vector->[B][$_] <=> 0 } X,Y;
  648. my $time = (unscale $vector->length) / $self->speeds->{$self->speed}; # in minutes
  649. if ($time > 0) {
  650. my @pause = ();
  651. foreach my $axis (X,Y) {
  652. if ($dir[$axis] != 0 && $self->last_dir->[$axis] != $dir[$axis]) {
  653. if ($self->last_dir->[$axis] != 0) {
  654. # this axis is changing direction: check whether we need to pause
  655. if ($self->dir_time->[$axis] < $min_time) {
  656. push @pause, ($min_time - $self->dir_time->[$axis]);
  657. }
  658. }
  659. $self->last_dir->[$axis] = $dir[$axis];
  660. $self->dir_time->[$axis] = 0;
  661. }
  662. $self->dir_time->[$axis] += $time;
  663. }
  664. if (@pause) {
  665. return sprintf "G4 P%d\n", max(@pause) * 60 * 1000;
  666. }
  667. }
  668. return '';
  669. }
  670. 1;