Print.pm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. # The slicing work horse.
  2. # Extends C++ class Slic3r::Print
  3. package Slic3r::Print;
  4. use strict;
  5. use warnings;
  6. use File::Basename qw(basename fileparse);
  7. use File::Spec;
  8. use List::Util qw(min max first sum);
  9. use Slic3r::ExtrusionLoop ':roles';
  10. use Slic3r::ExtrusionPath ':roles';
  11. use Slic3r::Flow ':roles';
  12. use Slic3r::Geometry qw(X Y Z X1 Y1 X2 Y2 MIN MAX PI scale unscale convex_hull);
  13. use Slic3r::Geometry::Clipper qw(diff_ex union_ex intersection_ex intersection offset
  14. offset2 union union_pt_chained JT_ROUND JT_SQUARE diff_pl);
  15. use Slic3r::Print::State ':steps';
  16. use Slic3r::Surface qw(S_TYPE_BOTTOM);
  17. our $status_cb;
  18. sub set_status_cb {
  19. my ($class, $cb) = @_;
  20. $status_cb = $cb;
  21. }
  22. sub status_cb {
  23. return $status_cb // sub {};
  24. }
  25. # this value is not supposed to be compared with $layer->id
  26. # since they have different semantics
  27. sub total_layer_count {
  28. my $self = shift;
  29. return max(map $_->total_layer_count, @{$self->objects});
  30. }
  31. sub size {
  32. my $self = shift;
  33. return $self->bounding_box->size;
  34. }
  35. sub process {
  36. my ($self) = @_;
  37. ### No need to call this as we call it as part of prepare_infill()
  38. ### until we fix the idempotency issue.
  39. ###$self->status_cb->(20, "Generating perimeters");
  40. ###$_->make_perimeters for @{$self->objects};
  41. $self->status_cb->(70, "Infilling layers");
  42. $_->infill for @{$self->objects};
  43. $_->generate_support_material for @{$self->objects};
  44. $self->make_skirt;
  45. $self->make_brim; # must come after make_skirt
  46. # time to make some statistics
  47. if (0) {
  48. eval "use Devel::Size";
  49. print "MEMORY USAGE:\n";
  50. printf " meshes = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->meshes), @{$self->objects})/1024/1024;
  51. printf " layer slices = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->slices), map @{$_->layers}, @{$self->objects})/1024/1024;
  52. printf " region slices = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->slices), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  53. printf " perimeters = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->perimeters), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  54. printf " fills = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->fills), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  55. printf " print object = %.1fMb\n", Devel::Size::total_size($self)/1024/1024;
  56. }
  57. if (0) {
  58. eval "use Slic3r::Test::SectionCut";
  59. Slic3r::Test::SectionCut->new(print => $self)->export_svg("section_cut.svg");
  60. }
  61. }
  62. sub escaped_split {
  63. my ($line) = @_;
  64. # Free up three characters for temporary replacement
  65. $line =~ s/%/%%/g;
  66. $line =~ s/#/##/g;
  67. $line =~ s/\?/\?\?/g;
  68. # replace escaped !'s
  69. $line =~ s/\!\!/%#\?/g;
  70. # split on non-escaped whitespace
  71. my @split = split /(?<=[^\!])\s+/, $line, -1;
  72. for my $part (@split) {
  73. # replace escaped whitespace with the whitespace
  74. $part =~ s/\!(\s+)/$1/g;
  75. # resub temp symbols
  76. $part =~ s/%#\?/\!/g;
  77. $part =~ s/%%/%/g;
  78. $part =~ s/##/#/g;
  79. $part =~ s/\?\?/\?/g;
  80. }
  81. return @split;
  82. }
  83. sub export_gcode {
  84. my $self = shift;
  85. my %params = @_;
  86. # prerequisites
  87. $self->process;
  88. # output everything to a G-code file
  89. my $output_file = $self->output_filepath($params{output_file} // '');
  90. $self->status_cb->(90, "Exporting G-code" . ($output_file ? " to $output_file" : ""));
  91. {
  92. # open output gcode file if we weren't supplied a file-handle
  93. my ($fh, $tempfile);
  94. if ($params{output_fh}) {
  95. $fh = $params{output_fh};
  96. } else {
  97. $tempfile = "$output_file.tmp";
  98. Slic3r::open(\$fh, ">", $tempfile)
  99. or die "Failed to open $tempfile for writing\n";
  100. # enable UTF-8 output since user might have entered Unicode characters in fields like notes
  101. binmode $fh, ':utf8';
  102. }
  103. Slic3r::Print::GCode->new(
  104. print => $self,
  105. fh => $fh,
  106. )->export;
  107. # close our gcode file
  108. close $fh;
  109. if ($tempfile) {
  110. my $renamed = 0;
  111. for my $i (1..5) {
  112. last if $renamed = rename Slic3r::encode_path($tempfile), Slic3r::encode_path($output_file);
  113. # Wait for 1/4 seconds and try to rename once again.
  114. select(undef, undef, undef, 0.25);
  115. }
  116. Slic3r::debugf "Failed to remove the output G-code file from $tempfile to $output_file. Is $tempfile locked?\n"
  117. if !$renamed;
  118. }
  119. }
  120. # run post-processing scripts
  121. if (@{$self->config->post_process}) {
  122. $self->status_cb->(95, "Running post-processing scripts");
  123. $self->config->setenv;
  124. for my $script (@{$self->config->post_process}) {
  125. Slic3r::debugf " '%s' '%s'\n", $script, $output_file;
  126. my @parsed_script = escaped_split $script;
  127. my $executable = shift @parsed_script ;
  128. push @parsed_script, $output_file;
  129. # -x doesn't return true on Windows except for .exe files
  130. if (($^O eq 'MSWin32') ? !(-e $executable) : !(-x $executable)) {
  131. die "The configured post-processing script is not executable: check permissions or escape whitespace/exclamation points. ($executable) \n";
  132. }
  133. system($executable, @parsed_script);
  134. }
  135. }
  136. }
  137. # Export SVG slices for the offline SLA printing.
  138. sub export_svg {
  139. my $self = shift;
  140. my %params = @_;
  141. $_->slice for @{$self->objects};
  142. my $fh = $params{output_fh};
  143. if (!$fh) {
  144. my $output_file = $self->output_filepath($params{output_file});
  145. $output_file =~ s/\.gcode$/.svg/i;
  146. Slic3r::open(\$fh, ">", $output_file) or die "Failed to open $output_file for writing\n";
  147. print "Exporting to $output_file..." unless $params{quiet};
  148. }
  149. my $print_bb = $self->bounding_box;
  150. my $print_size = $print_bb->size;
  151. print $fh sprintf <<"EOF", unscale($print_size->[X]), unscale($print_size->[Y]);
  152. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  153. <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
  154. <svg width="%s" height="%s" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:slic3r="http://slic3r.org/namespaces/slic3r">
  155. <!--
  156. Generated using Slic3r $Slic3r::VERSION
  157. http://slic3r.org/
  158. -->
  159. EOF
  160. my $print_polygon = sub {
  161. my ($polygon, $type) = @_;
  162. printf $fh qq{ <polygon slic3r:type="%s" points="%s" style="fill: %s" />\n},
  163. $type, (join ' ', map { join ',', map unscale $_, @$_ } @$polygon),
  164. ($type eq 'contour' ? 'white' : 'black');
  165. };
  166. my @layers = sort { $a->print_z <=> $b->print_z }
  167. map { @{$_->layers}, @{$_->support_layers} }
  168. @{$self->objects};
  169. my $layer_id = -1;
  170. my @previous_layer_slices = ();
  171. for my $layer (@layers) {
  172. $layer_id++;
  173. if ($layer->slice_z == -1) {
  174. printf $fh qq{ <g id="layer%d">\n}, $layer_id;
  175. } else {
  176. printf $fh qq{ <g id="layer%d" slic3r:z="%s">\n}, $layer_id, unscale($layer->slice_z);
  177. }
  178. my @current_layer_slices = ();
  179. # sort slices so that the outermost ones come first
  180. my @slices = sort { $a->contour->contains_point($b->contour->first_point) ? 0 : 1 } @{$layer->slices};
  181. foreach my $copy (@{$layer->object->_shifted_copies}) {
  182. foreach my $slice (@slices) {
  183. my $expolygon = $slice->clone;
  184. $expolygon->translate(@$copy);
  185. $expolygon->translate(-$print_bb->x_min, -$print_bb->y_min);
  186. $print_polygon->($expolygon->contour, 'contour');
  187. $print_polygon->($_, 'hole') for @{$expolygon->holes};
  188. push @current_layer_slices, $expolygon;
  189. }
  190. }
  191. # generate support material
  192. if ($self->has_support_material && $layer->id > 0) {
  193. my (@supported_slices, @unsupported_slices) = ();
  194. foreach my $expolygon (@current_layer_slices) {
  195. my $intersection = intersection_ex(
  196. [ map @$_, @previous_layer_slices ],
  197. [ @$expolygon ],
  198. );
  199. @$intersection
  200. ? push @supported_slices, $expolygon
  201. : push @unsupported_slices, $expolygon;
  202. }
  203. my @supported_points = map @$_, @$_, @supported_slices;
  204. foreach my $expolygon (@unsupported_slices) {
  205. # look for the nearest point to this island among all
  206. # supported points
  207. my $contour = $expolygon->contour;
  208. my $support_point = $contour->first_point->nearest_point(\@supported_points)
  209. or next;
  210. my $anchor_point = $support_point->nearest_point([ @$contour ]);
  211. printf $fh qq{ <line x1="%s" y1="%s" x2="%s" y2="%s" style="stroke-width: 2; stroke: white" />\n},
  212. map @$_, $support_point, $anchor_point;
  213. }
  214. }
  215. print $fh qq{ </g>\n};
  216. @previous_layer_slices = @current_layer_slices;
  217. }
  218. print $fh "</svg>\n";
  219. close $fh;
  220. print "Done.\n" unless $params{quiet};
  221. }
  222. sub make_skirt {
  223. my $self = shift;
  224. # prerequisites
  225. $_->make_perimeters for @{$self->objects};
  226. $_->infill for @{$self->objects};
  227. $_->generate_support_material for @{$self->objects};
  228. return if $self->step_done(STEP_SKIRT);
  229. $self->set_step_started(STEP_SKIRT);
  230. # since this method must be idempotent, we clear skirt paths *before*
  231. # checking whether we need to generate them
  232. $self->skirt->clear;
  233. if (!$self->has_skirt) {
  234. $self->set_step_done(STEP_SKIRT);
  235. return;
  236. }
  237. $self->status_cb->(88, "Generating skirt");
  238. # First off we need to decide how tall the skirt must be.
  239. # The skirt_height option from config is expressed in layers, but our
  240. # object might have different layer heights, so we need to find the print_z
  241. # of the highest layer involved.
  242. # Note that unless has_infinite_skirt() == true
  243. # the actual skirt might not reach this $skirt_height_z value since the print
  244. # order of objects on each layer is not guaranteed and will not generally
  245. # include the thickest object first. It is just guaranteed that a skirt is
  246. # prepended to the first 'n' layers (with 'n' = skirt_height).
  247. # $skirt_height_z in this case is the highest possible skirt height for safety.
  248. my $skirt_height_z = -1;
  249. foreach my $object (@{$self->objects}) {
  250. my $skirt_height = $self->has_infinite_skirt
  251. ? $object->layer_count
  252. : min($self->config->skirt_height, $object->layer_count);
  253. my $highest_layer = $object->get_layer($skirt_height - 1);
  254. $skirt_height_z = max($skirt_height_z, $highest_layer->print_z);
  255. }
  256. # collect points from all layers contained in skirt height
  257. my @points = ();
  258. foreach my $object (@{$self->objects}) {
  259. my @object_points = ();
  260. # get object layers up to $skirt_height_z
  261. foreach my $layer (@{$object->layers}) {
  262. last if $layer->print_z > $skirt_height_z;
  263. push @object_points, map @$_, map @$_, @{$layer->slices};
  264. }
  265. # get support layers up to $skirt_height_z
  266. foreach my $layer (@{$object->support_layers}) {
  267. last if $layer->print_z > $skirt_height_z;
  268. push @object_points, map @{$_->polyline}, @{$layer->support_fills} if $layer->support_fills;
  269. push @object_points, map @{$_->polyline}, @{$layer->support_interface_fills} if $layer->support_interface_fills;
  270. }
  271. # repeat points for each object copy
  272. foreach my $copy (@{$object->_shifted_copies}) {
  273. my @copy_points = map $_->clone, @object_points;
  274. $_->translate(@$copy) for @copy_points;
  275. push @points, @copy_points;
  276. }
  277. }
  278. return if @points < 3; # at least three points required for a convex hull
  279. # find out convex hull
  280. my $convex_hull = convex_hull(\@points);
  281. my @extruded_length = (); # for each extruder
  282. # skirt may be printed on several layers, having distinct layer heights,
  283. # but loops must be aligned so can't vary width/spacing
  284. # TODO: use each extruder's own flow
  285. my $first_layer_height = $self->skirt_first_layer_height;
  286. my $flow = $self->skirt_flow;
  287. my $spacing = $flow->spacing;
  288. my $mm3_per_mm = $flow->mm3_per_mm;
  289. my @extruders_e_per_mm = ();
  290. my $extruder_idx = 0;
  291. my $skirts = $self->config->skirts;
  292. $skirts ||= 1 if $self->has_infinite_skirt;
  293. # draw outlines from outside to inside
  294. # loop while we have less skirts than required or any extruder hasn't reached the min length if any
  295. my $distance = scale max($self->config->skirt_distance, $self->config->brim_width);
  296. for (my $i = $skirts; $i > 0; $i--) {
  297. $distance += scale $spacing;
  298. my $loop = offset([$convex_hull], $distance, 1, JT_ROUND, scale(0.1))->[0];
  299. my $eloop = Slic3r::ExtrusionLoop->new_from_paths(
  300. Slic3r::ExtrusionPath->new(
  301. polyline => Slic3r::Polygon->new(@$loop)->split_at_first_point,
  302. role => EXTR_ROLE_SKIRT,
  303. mm3_per_mm => $mm3_per_mm, # this will be overridden at G-code export time
  304. width => $flow->width,
  305. height => $first_layer_height, # this will be overridden at G-code export time
  306. ),
  307. );
  308. $eloop->role(EXTRL_ROLE_SKIRT);
  309. $self->skirt->append($eloop);
  310. if ($self->config->min_skirt_length > 0) {
  311. $extruded_length[$extruder_idx] ||= 0;
  312. if (!$extruders_e_per_mm[$extruder_idx]) {
  313. my $config = Slic3r::Config::GCode->new;
  314. $config->apply_static($self->config);
  315. my $extruder = Slic3r::Extruder->new($extruder_idx, $config);
  316. $extruders_e_per_mm[$extruder_idx] = $extruder->e_per_mm($mm3_per_mm);
  317. }
  318. $extruded_length[$extruder_idx] += unscale $loop->length * $extruders_e_per_mm[$extruder_idx];
  319. $i++ if defined first { ($extruded_length[$_] // 0) < $self->config->min_skirt_length } 0 .. $#{$self->extruders};
  320. if ($extruded_length[$extruder_idx] >= $self->config->min_skirt_length) {
  321. if ($extruder_idx < $#{$self->extruders}) {
  322. $extruder_idx++;
  323. next;
  324. }
  325. }
  326. }
  327. }
  328. $self->skirt->reverse;
  329. $self->set_step_done(STEP_SKIRT);
  330. }
  331. sub make_brim {
  332. my $self = shift;
  333. # prerequisites
  334. $_->make_perimeters for @{$self->objects};
  335. $_->infill for @{$self->objects};
  336. $_->generate_support_material for @{$self->objects};
  337. $self->make_skirt;
  338. $self->status_cb->(88, "Generating brim");
  339. $self->_make_brim;
  340. }
  341. # Wrapper around the C++ Slic3r::Print::validate()
  342. # to produce a Perl exception without a hang-up on some Strawberry perls.
  343. sub validate
  344. {
  345. my $self = shift;
  346. my $err = $self->_validate;
  347. die $err . "\n" if (defined($err) && $err ne '');
  348. }
  349. 1;