~ubuntu-branches/ubuntu/utopic/slic3r/utopic

« back to all changes in this revision

Viewing changes to lib/Slic3r/GCode.pm

  • Committer: Package Import Robot
  • Author(s): Chow Loong Jin
  • Date: 2014-06-17 01:27:26 UTC
  • Revision ID: package-import@ubuntu.com-20140617012726-2wrs4zdo251nr4vg
Tags: upstream-1.1.4+dfsg
ImportĀ upstreamĀ versionĀ 1.1.4+dfsg

Show diffs side-by-side

added added

removed removed

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