Print.pm 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. package Slic3r::Print;
  2. use Moo;
  3. use File::Basename qw(basename fileparse);
  4. use File::Spec;
  5. use List::Util qw(min max first);
  6. use Math::ConvexHull::MonotoneChain qw(convex_hull);
  7. use Slic3r::ExtrusionPath ':roles';
  8. use Slic3r::Geometry qw(X Y Z X1 Y1 X2 Y2 MIN MAX PI scale unscale move_points chained_path);
  9. use Slic3r::Geometry::Clipper qw(diff_ex union_ex union_pt intersection_ex offset
  10. offset2 traverse_pt JT_ROUND JT_SQUARE PFT_EVENODD);
  11. use Time::HiRes qw(gettimeofday tv_interval);
  12. has 'config' => (is => 'rw', default => sub { Slic3r::Config->new_from_defaults }, trigger => 1);
  13. has 'extra_variables' => (is => 'rw', default => sub {{}});
  14. has 'objects' => (is => 'rw', default => sub {[]});
  15. has 'total_extrusion_length' => (is => 'rw');
  16. has 'processing_time' => (is => 'rw');
  17. has 'extruders' => (is => 'rw', default => sub {[]});
  18. has 'regions' => (is => 'rw', default => sub {[]});
  19. has 'support_material_flow' => (is => 'rw');
  20. has 'first_layer_support_material_flow' => (is => 'rw');
  21. has 'has_support_material' => (is => 'lazy');
  22. # ordered collection of extrusion paths to build skirt loops
  23. has 'skirt' => (
  24. is => 'rw',
  25. #isa => 'ArrayRef[Slic3r::ExtrusionLoop]',
  26. default => sub { [] },
  27. );
  28. # ordered collection of extrusion paths to build a brim
  29. has 'brim' => (
  30. is => 'rw',
  31. #isa => 'ArrayRef[Slic3r::ExtrusionLoop]',
  32. default => sub { [] },
  33. );
  34. sub BUILD {
  35. my $self = shift;
  36. # call this manually because the 'default' coderef doesn't trigger the trigger
  37. $self->_trigger_config;
  38. }
  39. sub _trigger_config {
  40. my $self = shift;
  41. # store config in a handy place
  42. $Slic3r::Config = $self->config;
  43. # legacy with existing config files
  44. $self->config->set('first_layer_height', $self->config->layer_height)
  45. if !$self->config->first_layer_height;
  46. $self->config->set_ifndef('small_perimeter_speed', $self->config->perimeter_speed);
  47. $self->config->set_ifndef('bridge_speed', $self->config->infill_speed);
  48. $self->config->set_ifndef('solid_infill_speed', $self->config->infill_speed);
  49. $self->config->set_ifndef('top_solid_infill_speed', $self->config->solid_infill_speed);
  50. $self->config->set_ifndef('top_solid_layers', $self->config->solid_layers);
  51. $self->config->set_ifndef('bottom_solid_layers', $self->config->solid_layers);
  52. # G-code flavors
  53. $self->config->set('extrusion_axis', 'A') if $self->config->gcode_flavor eq 'mach3';
  54. $self->config->set('extrusion_axis', '') if $self->config->gcode_flavor eq 'no-extrusion';
  55. # enforce some settings when spiral_vase is set
  56. if ($self->config->spiral_vase) {
  57. $self->config->set('perimeters', 1);
  58. $self->config->set('fill_density', 0);
  59. $self->config->set('top_solid_layers', 0);
  60. $self->config->set('support_material', 0);
  61. $self->config->set('support_material_enforce_layers', 0);
  62. $self->config->set('retract_layer_change', [0]); # TODO: only apply this to the spiral layers
  63. }
  64. # force all retraction lift values to be the same
  65. $self->config->set('retract_lift', [ map $self->config->retract_lift->[0], @{$self->config->retract_lift} ]);
  66. }
  67. sub _build_has_support_material {
  68. my $self = shift;
  69. return (first { $_->config->support_material } @{$self->objects})
  70. || (first { $_->config->raft_layers > 0 } @{$self->objects})
  71. || (first { $_->config->support_material_enforce_layers > 0 } @{$self->objects});
  72. }
  73. # caller is responsible for supplying models whose objects don't collide
  74. # and have explicit instance positions
  75. sub add_model {
  76. my $self = shift;
  77. my ($model) = @_;
  78. # optimization: if avoid_crossing_perimeters is enabled, split
  79. # this mesh into distinct objects so that we reduce the complexity
  80. # of the graphs
  81. # -- Disabling this one because there are too many legit objects having nested shells
  82. # -- It also caused a bug where plater rotation was applied to each single object by the
  83. # -- code below (thus around its own center), instead of being applied to the whole
  84. # -- thing before the split.
  85. ###$model->split_meshes if $Slic3r::Config->avoid_crossing_perimeters && !$Slic3r::Config->complete_objects;
  86. my %unmapped_materials = ();
  87. foreach my $object (@{ $model->objects }) {
  88. # we align object to origin before applying transformations
  89. my @align = $object->align_to_origin;
  90. # extract meshes by material
  91. my @meshes = (); # by region_id
  92. foreach my $volume (@{$object->volumes}) {
  93. my $region_id;
  94. if (defined $volume->material_id) {
  95. if ($object->material_mapping) {
  96. $region_id = $object->material_mapping->{$volume->material_id} - 1
  97. if defined $object->material_mapping->{$volume->material_id};
  98. }
  99. $region_id //= $unmapped_materials{$volume->material_id};
  100. if (!defined $region_id) {
  101. $region_id = $unmapped_materials{$volume->material_id} = scalar(keys %unmapped_materials);
  102. }
  103. }
  104. $region_id //= 0;
  105. my $mesh = $volume->mesh->clone;
  106. # should the object contain multiple volumes of the same material, merge them
  107. $meshes[$region_id] = $meshes[$region_id]
  108. ? Slic3r::TriangleMesh->merge($meshes[$region_id], $mesh)
  109. : $mesh;
  110. }
  111. $self->regions->[$_] //= Slic3r::Print::Region->new for 0..$#meshes;
  112. foreach my $mesh (grep $_, @meshes) {
  113. $mesh->check_manifoldness;
  114. # the order of these transformations must be the same as the one used in plater
  115. # to make the object positioning consistent with the visual preview
  116. # we ignore the per-instance transformations currently and only
  117. # consider the first one
  118. if ($object->instances && @{$object->instances}) {
  119. $mesh->rotate($object->instances->[0]->rotation, $object->center);
  120. $mesh->scale($object->instances->[0]->scaling_factor);
  121. }
  122. $mesh->scale(1 / &Slic3r::SCALING_FACTOR);
  123. }
  124. # we also align object after transformations so that we only work with positive coordinates
  125. # and the assumption that bounding_box === size works
  126. my $bb = Slic3r::Geometry::BoundingBox->new_from_points_3D([ map @{$_->used_vertices}, grep $_, @meshes ]);
  127. my @align2 = map -$bb->extents->[$_][MIN], (X,Y,Z);
  128. $_->move(@align2) for grep $_, @meshes;
  129. # initialize print object
  130. push @{$self->objects}, Slic3r::Print::Object->new(
  131. print => $self,
  132. meshes => [ @meshes ],
  133. copies => [
  134. $object->instances
  135. ? (map [ scale($_->offset->[X] - $align[X]) - $align2[X], scale($_->offset->[Y] - $align[Y]) - $align2[Y] ], @{$object->instances})
  136. : [0,0],
  137. ],
  138. size => $bb->size, # transformed size
  139. input_file => $object->input_file,
  140. config_overrides => $object->config,
  141. layer_height_ranges => $object->layer_height_ranges,
  142. );
  143. }
  144. }
  145. sub validate {
  146. my $self = shift;
  147. if ($Slic3r::Config->complete_objects) {
  148. # check horizontal clearance
  149. {
  150. my @a = ();
  151. for my $obj_idx (0 .. $#{$self->objects}) {
  152. my $clearance;
  153. {
  154. my @points = map [ @$_[X,Y] ], map @{$_->vertices}, @{$self->objects->[$obj_idx]->meshes};
  155. my $convex_hull = Slic3r::Polygon->new(@{convex_hull(\@points)});
  156. ($clearance) = map Slic3r::Polygon->new(@$_),
  157. @{Slic3r::Geometry::Clipper::offset(
  158. [$convex_hull], scale $Slic3r::Config->extruder_clearance_radius / 2, 1, JT_ROUND)};
  159. }
  160. for my $copy (@{$self->objects->[$obj_idx]->copies}) {
  161. my $copy_clearance = $clearance->clone;
  162. $copy_clearance->translate(@$copy);
  163. if (@{ intersection_ex(\@a, [$copy_clearance]) }) {
  164. die "Some objects are too close; your extruder will collide with them.\n";
  165. }
  166. @a = map @$_, @{union_ex([ @a, $copy_clearance ])};
  167. }
  168. }
  169. }
  170. # check vertical clearance
  171. {
  172. my @object_height = ();
  173. foreach my $object (@{$self->objects}) {
  174. my $height = $object->size->[Z];
  175. push @object_height, $height for @{$object->copies};
  176. }
  177. @object_height = sort { $a <=> $b } @object_height;
  178. # ignore the tallest *copy* (this is why we repeat height for all of them):
  179. # it will be printed as last one so its height doesn't matter
  180. pop @object_height;
  181. if (@object_height && max(@object_height) > scale $Slic3r::Config->extruder_clearance_height) {
  182. die "Some objects are too tall and cannot be printed without extruder collisions.\n";
  183. }
  184. }
  185. }
  186. if ($Slic3r::Config->spiral_vase) {
  187. if ((map @{$_->copies}, @{$self->objects}) > 1) {
  188. die "The Spiral Vase option can only be used when printing a single object.\n";
  189. }
  190. if (@{$self->regions} > 1) {
  191. die "The Spiral Vase option can only be used when printing single material objects.\n";
  192. }
  193. }
  194. }
  195. sub init_extruders {
  196. my $self = shift;
  197. # map regions to extruders (ghetto mapping for now)
  198. my %extruder_mapping = map { $_ => $_ } 0..$#{$self->regions};
  199. # initialize all extruder(s) we need
  200. my @used_extruders = (
  201. 0,
  202. (map $self->config->get("${_}_extruder")-1, qw(perimeter infill support_material support_material_interface)),
  203. (values %extruder_mapping),
  204. );
  205. for my $extruder_id (keys %{{ map {$_ => 1} @used_extruders }}) {
  206. $self->extruders->[$extruder_id] = Slic3r::Extruder->new(
  207. id => $extruder_id,
  208. map { $_ => $self->config->get($_)->[$extruder_id] // $self->config->get($_)->[0] } #/
  209. @{&Slic3r::Extruder::OPTIONS}
  210. );
  211. }
  212. # calculate regions' flows
  213. for my $region_id (0 .. $#{$self->regions}) {
  214. my $region = $self->regions->[$region_id];
  215. # per-role extruders and flows
  216. for (qw(perimeter infill solid_infill top_infill)) {
  217. my $extruder_name = $_;
  218. $extruder_name =~ s/^(?:solid|top)_//;
  219. $region->extruders->{$_} = ($self->regions_count > 1)
  220. ? $self->extruders->[$extruder_mapping{$region_id}]
  221. : $self->extruders->[$self->config->get("${extruder_name}_extruder")-1];
  222. $region->flows->{$_} = $region->extruders->{$_}->make_flow(
  223. width => $self->config->get("${_}_extrusion_width") || $self->config->extrusion_width,
  224. role => $_,
  225. );
  226. $region->first_layer_flows->{$_} = $region->extruders->{$_}->make_flow(
  227. layer_height => $self->config->get_value('first_layer_height'),
  228. width => $self->config->first_layer_extrusion_width,
  229. role => $_,
  230. ) if $self->config->first_layer_extrusion_width;
  231. }
  232. }
  233. # calculate support material flow
  234. # Note: we should calculate a different flow for support material interface
  235. if ($self->has_support_material) {
  236. my $extruder = $self->extruders->[$self->config->support_material_extruder-1];
  237. $self->support_material_flow($extruder->make_flow(
  238. width => $self->config->support_material_extrusion_width || $self->config->extrusion_width,
  239. role => 'support_material',
  240. ));
  241. $self->first_layer_support_material_flow($extruder->make_flow(
  242. layer_height => $self->config->get_value('first_layer_height'),
  243. width => $self->config->first_layer_extrusion_width,
  244. role => 'support_material',
  245. ));
  246. }
  247. }
  248. sub layer_count {
  249. my $self = shift;
  250. return max(map { scalar @{$_->layers} } @{$self->objects});
  251. }
  252. sub regions_count {
  253. my $self = shift;
  254. return scalar @{$self->regions};
  255. }
  256. sub bounding_box {
  257. my $self = shift;
  258. my @points = ();
  259. foreach my $object (@{$self->objects}) {
  260. foreach my $copy (@{$object->copies}) {
  261. push @points,
  262. [ $copy->[X], $copy->[Y] ],
  263. [ $copy->[X] + $object->size->[X], $copy->[Y] + $object->size->[Y] ];
  264. }
  265. }
  266. return Slic3r::Geometry::BoundingBox->new_from_points([ map Slic3r::Point->new(@$_), @points ]);
  267. }
  268. sub size {
  269. my $self = shift;
  270. return $self->bounding_box->size;
  271. }
  272. sub _simplify_slices {
  273. my $self = shift;
  274. my ($distance) = @_;
  275. foreach my $layer (map @{$_->layers}, @{$self->objects}) {
  276. my @new = map $_->simplify($distance), map $_->clone, @{$layer->slices};
  277. $layer->slices->clear;
  278. $layer->slices->append(@new);
  279. foreach my $layerm (@{$layer->regions}) {
  280. my @new = map $_->simplify($distance), map $_->clone, @{$layerm->slices};
  281. $layerm->slices->clear;
  282. $layerm->slices->append(@new);
  283. }
  284. }
  285. }
  286. sub export_gcode {
  287. my $self = shift;
  288. my %params = @_;
  289. $self->init_extruders;
  290. my $status_cb = $params{status_cb} || sub {};
  291. my $t0 = [gettimeofday];
  292. # skein the STL into layers
  293. # each layer has surfaces with holes
  294. $status_cb->(10, "Processing triangulated mesh");
  295. $_->slice for @{$self->objects};
  296. # remove empty layers and abort if there are no more
  297. # as some algorithms assume all objects have at least one layer
  298. # note: this will change object indexes
  299. @{$self->objects} = grep @{$_->layers}, @{$self->objects};
  300. die "No layers were detected. You might want to repair your STL file(s) or check their size and retry.\n"
  301. if !@{$self->objects};
  302. if ($Slic3r::Config->resolution) {
  303. $status_cb->(15, "Simplifying input");
  304. $self->_simplify_slices(scale $Slic3r::Config->resolution);
  305. }
  306. # make perimeters
  307. # this will add a set of extrusion loops to each layer
  308. # as well as generate infill boundaries
  309. $status_cb->(20, "Generating perimeters");
  310. $_->make_perimeters for @{$self->objects};
  311. # simplify slices (both layer and region slices),
  312. # we only need the max resolution for perimeters
  313. $self->_simplify_slices(&Slic3r::SCALED_RESOLUTION);
  314. # this will assign a type (top/bottom/internal) to $layerm->slices
  315. # and transform $layerm->fill_surfaces from expolygon
  316. # to typed top/bottom/internal surfaces;
  317. $status_cb->(30, "Detecting solid surfaces");
  318. $_->detect_surfaces_type for @{$self->objects};
  319. # decide what surfaces are to be filled
  320. $status_cb->(35, "Preparing infill surfaces");
  321. $_->prepare_fill_surfaces for map @{$_->regions}, map @{$_->layers}, @{$self->objects};
  322. # this will detect bridges and reverse bridges
  323. # and rearrange top/bottom/internal surfaces
  324. $status_cb->(45, "Detect bridges");
  325. $_->process_external_surfaces for map @{$_->regions}, map @{$_->layers}, @{$self->objects};
  326. # detect which fill surfaces are near external layers
  327. # they will be split in internal and internal-solid surfaces
  328. $status_cb->(60, "Generating horizontal shells");
  329. $_->discover_horizontal_shells for @{$self->objects};
  330. $_->clip_fill_surfaces for @{$self->objects};
  331. # the following step needs to be done before combination because it may need
  332. # to remove only half of the combined infill
  333. $_->bridge_over_infill for @{$self->objects};
  334. # combine fill surfaces to honor the "infill every N layers" option
  335. $status_cb->(70, "Combining infill");
  336. $_->combine_infill for @{$self->objects};
  337. # this will generate extrusion paths for each layer
  338. $status_cb->(80, "Infilling layers");
  339. {
  340. Slic3r::parallelize(
  341. items => sub {
  342. my @items = (); # [obj_idx, layer_id]
  343. for my $obj_idx (0 .. $#{$self->objects}) {
  344. for my $region_id (0 .. ($self->regions_count-1)) {
  345. push @items, map [$obj_idx, $_, $region_id], 0..($self->objects->[$obj_idx]->layer_count-1);
  346. }
  347. }
  348. @items;
  349. },
  350. thread_cb => sub {
  351. my $q = shift;
  352. $Slic3r::Geometry::Clipper::clipper = Math::Clipper->new;
  353. while (defined (my $obj_layer = $q->dequeue)) {
  354. my ($obj_idx, $layer_id, $region_id) = @$obj_layer;
  355. my $object = $self->objects->[$obj_idx];
  356. my $layerm = $object->layers->[$layer_id]->regions->[$region_id];
  357. $layerm->fills->append( $object->fill_maker->make_fill($layerm) );
  358. }
  359. },
  360. collect_cb => sub {},
  361. no_threads_cb => sub {
  362. foreach my $layerm (map @{$_->regions}, map @{$_->layers}, @{$self->objects}) {
  363. $layerm->fills->append($layerm->layer->object->fill_maker->make_fill($layerm));
  364. }
  365. },
  366. );
  367. }
  368. # generate support material
  369. if ($self->has_support_material) {
  370. $status_cb->(85, "Generating support material");
  371. $_->generate_support_material for @{$self->objects};
  372. }
  373. # free memory (note that support material needs fill_surfaces)
  374. $_->fill_surfaces->clear for map @{$_->regions}, map @{$_->layers}, @{$self->objects};
  375. # make skirt
  376. $status_cb->(88, "Generating skirt");
  377. $self->make_skirt;
  378. $self->make_brim; # must come after make_skirt
  379. # time to make some statistics
  380. if (0) {
  381. eval "use Devel::Size";
  382. print "MEMORY USAGE:\n";
  383. printf " meshes = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->meshes), @{$self->objects})/1024/1024;
  384. printf " layer slices = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->slices), map @{$_->layers}, @{$self->objects})/1024/1024;
  385. printf " region slices = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->slices), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  386. printf " perimeters = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->perimeters), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  387. printf " fills = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->fills), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  388. printf " print object = %.1fMb\n", Devel::Size::total_size($self)/1024/1024;
  389. }
  390. if (0) {
  391. eval "use Slic3r::Test::SectionCut";
  392. Slic3r::Test::SectionCut->new(print => $self)->export_svg("section_cut.svg");
  393. }
  394. # output everything to a G-code file
  395. my $output_file = $self->expanded_output_filepath($params{output_file});
  396. $status_cb->(90, "Exporting G-code" . ($output_file ? " to $output_file" : ""));
  397. $self->write_gcode($params{output_fh} || $output_file);
  398. # run post-processing scripts
  399. if (@{$Slic3r::Config->post_process}) {
  400. $status_cb->(95, "Running post-processing scripts");
  401. $Slic3r::Config->setenv;
  402. for (@{$Slic3r::Config->post_process}) {
  403. Slic3r::debugf " '%s' '%s'\n", $_, $output_file;
  404. system($_, $output_file);
  405. }
  406. }
  407. # output some statistics
  408. unless ($params{quiet}) {
  409. $self->processing_time(tv_interval($t0));
  410. printf "Done. Process took %d minutes and %.3f seconds\n",
  411. int($self->processing_time/60),
  412. $self->processing_time - int($self->processing_time/60)*60;
  413. # TODO: more statistics!
  414. printf "Filament required: %.1fmm (%.1fcm3)\n",
  415. $self->total_extrusion_length, $self->total_extrusion_volume;
  416. }
  417. }
  418. sub export_svg {
  419. my $self = shift;
  420. my %params = @_;
  421. # this shouldn't be needed, but we're currently relying on ->make_surfaces() which
  422. # calls ->perimeter_flow
  423. $self->init_extruders;
  424. $_->slice for @{$self->objects};
  425. my $fh = $params{output_fh};
  426. if ($params{output_file}) {
  427. my $output_file = $self->expanded_output_filepath($params{output_file});
  428. $output_file =~ s/\.gcode$/.svg/i;
  429. Slic3r::open(\$fh, ">", $output_file) or die "Failed to open $output_file for writing\n";
  430. print "Exporting to $output_file..." unless $params{quiet};
  431. }
  432. my $print_size = $self->size;
  433. print $fh sprintf <<"EOF", unscale($print_size->[X]), unscale($print_size->[Y]);
  434. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  435. <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
  436. <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">
  437. <!--
  438. Generated using Slic3r $Slic3r::VERSION
  439. http://slic3r.org/
  440. -->
  441. EOF
  442. my $print_polygon = sub {
  443. my ($polygon, $type) = @_;
  444. printf $fh qq{ <polygon slic3r:type="%s" points="%s" style="fill: %s" />\n},
  445. $type, (join ' ', map { join ',', map unscale $_, @$_ } @$polygon),
  446. ($type eq 'contour' ? 'white' : 'black');
  447. };
  448. my @previous_layer_slices = ();
  449. for my $layer_id (0..$self->layer_count-1) {
  450. my @layers = map $_->layers->[$layer_id], @{$self->objects};
  451. printf $fh qq{ <g id="layer%d" slic3r:z="%s">\n}, $layer_id, unscale +(grep defined $_, @layers)[0]->slice_z;
  452. my @current_layer_slices = ();
  453. for my $obj_idx (0 .. $#{$self->objects}) {
  454. my $layer = $self->objects->[$obj_idx]->layers->[$layer_id] or next;
  455. # sort slices so that the outermost ones come first
  456. my @slices = sort { $a->contour->encloses_point($b->contour->[0]) ? 0 : 1 } @{$layer->slices};
  457. foreach my $copy (@{$self->objects->[$obj_idx]->copies}) {
  458. foreach my $slice (@slices) {
  459. my $expolygon = $slice->clone;
  460. $expolygon->translate(@$copy);
  461. $print_polygon->($expolygon->contour, 'contour');
  462. $print_polygon->($_, 'hole') for @{$expolygon->holes};
  463. push @current_layer_slices, $expolygon;
  464. }
  465. }
  466. }
  467. # generate support material
  468. if ($self->has_support_material && $layer_id > 0) {
  469. my (@supported_slices, @unsupported_slices) = ();
  470. foreach my $expolygon (@current_layer_slices) {
  471. my $intersection = intersection_ex(
  472. [ map @$_, @previous_layer_slices ],
  473. $expolygon,
  474. );
  475. @$intersection
  476. ? push @supported_slices, $expolygon
  477. : push @unsupported_slices, $expolygon;
  478. }
  479. my @supported_points = map @$_, @$_, @supported_slices;
  480. foreach my $expolygon (@unsupported_slices) {
  481. # look for the nearest point to this island among all
  482. # supported points
  483. my $contour = $expolygon->contour;
  484. my $support_point = $contour->first_point->nearest_point(\@supported_points)
  485. or next;
  486. my $anchor_point = $support_point->nearest_point([ @$contour ]);
  487. printf $fh qq{ <line x1="%s" y1="%s" x2="%s" y2="%s" style="stroke-width: 2; stroke: white" />\n},
  488. map @$_, $support_point, $anchor_point;
  489. }
  490. }
  491. print $fh qq{ </g>\n};
  492. @previous_layer_slices = @current_layer_slices;
  493. }
  494. print $fh "</svg>\n";
  495. close $fh;
  496. print "Done.\n" unless $params{quiet};
  497. }
  498. sub make_skirt {
  499. my $self = shift;
  500. return unless $Slic3r::Config->skirts > 0;
  501. # collect points from all layers contained in skirt height
  502. my @points = ();
  503. foreach my $obj_idx (0 .. $#{$self->objects}) {
  504. my $object = $self->objects->[$obj_idx];
  505. my @layers = map $object->layers->[$_], 0..min($Slic3r::Config->skirt_height-1, $#{$object->layers});
  506. my @layer_points = (
  507. (map @$_, map @$_, map @{$_->slices}, @layers),
  508. (map @$_, map @{$_->thin_walls}, map @{$_->regions}, @layers),
  509. );
  510. if (@{ $object->support_layers }) {
  511. my @support_layers = map $object->support_layers->[$_], 0..min($Slic3r::Config->skirt_height-1, $#{$object->support_layers});
  512. push @layer_points,
  513. (map @{$_->unpack->polyline}, map @{$_->support_fills->paths}, grep $_->support_fills, @support_layers),
  514. (map @{$_->unpack->polyline}, map @{$_->support_interface_fills->paths}, grep $_->support_interface_fills, @support_layers);
  515. }
  516. push @points, map move_points($_, @layer_points), @{$object->copies};
  517. }
  518. return if @points < 3; # at least three points required for a convex hull
  519. # find out convex hull
  520. my $convex_hull = convex_hull([ map $_->arrayref, @points ]);
  521. my @extruded_length = (); # for each extruder
  522. # TODO: use each extruder's own flow
  523. my $spacing = $self->objects->[0]->layers->[0]->regions->[0]->perimeter_flow->spacing;
  524. my $first_layer_height = $Slic3r::Config->get_value('first_layer_height');
  525. my @extruders_e_per_mm = ();
  526. my $extruder_idx = 0;
  527. # draw outlines from outside to inside
  528. # loop while we have less skirts than required or any extruder hasn't reached the min length if any
  529. my $distance = scale $Slic3r::Config->skirt_distance;
  530. for (my $i = $Slic3r::Config->skirts; $i > 0; $i--) {
  531. $distance += scale $spacing;
  532. my $loop = Slic3r::Geometry::Clipper::offset([$convex_hull], $distance, 0.0001, JT_ROUND)->[0];
  533. push @{$self->skirt}, Slic3r::ExtrusionLoop->new(
  534. polygon => Slic3r::Polygon->new(@$loop),
  535. role => EXTR_ROLE_SKIRT,
  536. flow_spacing => $spacing,
  537. );
  538. if ($Slic3r::Config->min_skirt_length > 0) {
  539. $extruded_length[$extruder_idx] ||= 0;
  540. $extruders_e_per_mm[$extruder_idx] ||= $self->extruders->[$extruder_idx]->e_per_mm($spacing, $first_layer_height);
  541. $extruded_length[$extruder_idx] += unscale $loop->length * $extruders_e_per_mm[$extruder_idx];
  542. $i++ if defined first { ($extruded_length[$_] // 0) < $Slic3r::Config->min_skirt_length } 0 .. $#{$self->extruders};
  543. if ($extruded_length[$extruder_idx] >= $Slic3r::Config->min_skirt_length) {
  544. if ($extruder_idx < $#{$self->extruders}) {
  545. $extruder_idx++;
  546. next;
  547. }
  548. }
  549. }
  550. }
  551. @{$self->skirt} = reverse @{$self->skirt};
  552. }
  553. sub make_brim {
  554. my $self = shift;
  555. return unless $Slic3r::Config->brim_width > 0;
  556. my $flow = $self->objects->[0]->layers->[0]->regions->[0]->perimeter_flow;
  557. my $grow_distance = $flow->scaled_width / 2;
  558. my @islands = (); # array of polygons
  559. foreach my $obj_idx (0 .. $#{$self->objects}) {
  560. my $object = $self->objects->[$obj_idx];
  561. my $layer0 = $object->layers->[0];
  562. my @object_islands = (
  563. (map $_->contour, @{$layer0->slices}),
  564. (map { $_->isa('Slic3r::Polygon') ? $_ : $_->grow($grow_distance) } map @{$_->thin_walls}, @{$layer0->regions}),
  565. );
  566. if (@{ $object->support_layers }) {
  567. my $support_layer0 = $object->support_layers->[0];
  568. push @object_islands,
  569. (map $_->unpack->polyline->grow($grow_distance), @{$support_layer0->support_fills->paths})
  570. if $support_layer0->support_fills;
  571. push @object_islands,
  572. (map $_->unpack->polyline->grow($grow_distance), @{$support_layer0->support_interface_fills->paths})
  573. if $support_layer0->support_interface_fills;
  574. }
  575. foreach my $copy (@{$object->copies}) {
  576. push @islands, map $_->clone->translate(@$copy), @object_islands;
  577. }
  578. }
  579. # if brim touches skirt, make it around skirt too
  580. # TODO: calculate actual skirt width (using each extruder's flow in multi-extruder setups)
  581. if ($Slic3r::Config->skirt_distance + (($Slic3r::Config->skirts - 1) * $flow->spacing) <= $Slic3r::Config->brim_width) {
  582. push @islands, map $_->split_at_first_point->polyline->grow($grow_distance), @{$self->skirt};
  583. }
  584. my @loops = ();
  585. my $num_loops = sprintf "%.0f", $Slic3r::Config->brim_width / $flow->width;
  586. for my $i (reverse 1 .. $num_loops) {
  587. # JT_SQUARE ensures no vertex is outside the given offset distance
  588. # -0.5 because islands are not represented by their centerlines
  589. # (first offset more, then step back - reverse order than the one used for
  590. # perimeters because here we're offsetting outwards)
  591. push @loops, @{offset2(\@islands, ($i + 0.5) * $flow->scaled_spacing, -1.0 * $flow->scaled_spacing, 100000, JT_SQUARE)};
  592. }
  593. @{$self->brim} = map Slic3r::ExtrusionLoop->new(
  594. polygon => Slic3r::Polygon->new(@$_),
  595. role => EXTR_ROLE_SKIRT,
  596. flow_spacing => $flow->spacing,
  597. ), reverse traverse_pt( union_pt(\@loops) );
  598. }
  599. sub write_gcode {
  600. my $self = shift;
  601. my ($file) = @_;
  602. # open output gcode file if we weren't supplied a file-handle
  603. my $fh;
  604. if (ref $file eq 'IO::Scalar') {
  605. $fh = $file;
  606. } else {
  607. Slic3r::open(\$fh, ">", $file)
  608. or die "Failed to open $file for writing\n";
  609. }
  610. # write some information
  611. my @lt = localtime;
  612. printf $fh "; generated by Slic3r $Slic3r::VERSION on %04d-%02d-%02d at %02d:%02d:%02d\n\n",
  613. $lt[5] + 1900, $lt[4]+1, $lt[3], $lt[2], $lt[1], $lt[0];
  614. print $fh "; $_\n" foreach split /\R/, $Slic3r::Config->notes;
  615. print $fh "\n" if $Slic3r::Config->notes;
  616. for (qw(layer_height perimeters top_solid_layers bottom_solid_layers fill_density perimeter_speed infill_speed travel_speed)) {
  617. printf $fh "; %s = %s\n", $_, $Slic3r::Config->$_;
  618. }
  619. for (qw(nozzle_diameter filament_diameter extrusion_multiplier)) {
  620. printf $fh "; %s = %s\n", $_, $Slic3r::Config->$_->[0];
  621. }
  622. printf $fh "; perimeters extrusion width = %.2fmm\n", $self->regions->[0]->flows->{perimeter}->width;
  623. printf $fh "; infill extrusion width = %.2fmm\n", $self->regions->[0]->flows->{infill}->width;
  624. printf $fh "; solid infill extrusion width = %.2fmm\n", $self->regions->[0]->flows->{solid_infill}->width;
  625. printf $fh "; top infill extrusion width = %.2fmm\n", $self->regions->[0]->flows->{top_infill}->width;
  626. printf $fh "; support material extrusion width = %.2fmm\n", $self->support_material_flow->width
  627. if $self->support_material_flow;
  628. printf $fh "; first layer extrusion width = %.2fmm\n", $self->regions->[0]->first_layer_flows->{perimeter}->width
  629. if $self->regions->[0]->first_layer_flows->{perimeter};
  630. print $fh "\n";
  631. # set up our extruder object
  632. my $gcodegen = Slic3r::GCode->new(
  633. config => $self->config,
  634. extruders => $self->extruders, # we should only pass the *used* extruders (but maintain the Tx indices right!)
  635. layer_count => $self->layer_count,
  636. );
  637. print $fh "G21 ; set units to millimeters\n" if $Slic3r::Config->gcode_flavor ne 'makerware';
  638. print $fh $gcodegen->set_fan(0, 1) if $Slic3r::Config->cooling && $Slic3r::Config->disable_fan_first_layers;
  639. # set bed temperature
  640. if ((my $temp = $Slic3r::Config->first_layer_bed_temperature) && $Slic3r::Config->start_gcode !~ /M(?:190|140)/i) {
  641. printf $fh $gcodegen->set_bed_temperature($temp, 1);
  642. }
  643. # set extruder(s) temperature before and after start G-code
  644. my $print_first_layer_temperature = sub {
  645. my ($wait) = @_;
  646. return if $Slic3r::Config->start_gcode =~ /M(?:109|104)/i;
  647. for my $t (0 .. $#{$self->extruders}) {
  648. my $temp = $self->extruders->[$t]->first_layer_temperature;
  649. printf $fh $gcodegen->set_temperature($temp, $wait, $t) if $temp > 0;
  650. }
  651. };
  652. $print_first_layer_temperature->(0);
  653. printf $fh "%s\n", $Slic3r::Config->replace_options($Slic3r::Config->start_gcode);
  654. $print_first_layer_temperature->(1);
  655. # set other general things
  656. print $fh "G90 ; use absolute coordinates\n" if $Slic3r::Config->gcode_flavor ne 'makerware';
  657. if ($Slic3r::Config->gcode_flavor =~ /^(?:reprap|teacup)$/) {
  658. printf $fh $gcodegen->reset_e;
  659. if ($Slic3r::Config->use_relative_e_distances) {
  660. print $fh "M83 ; use relative distances for extrusion\n";
  661. } else {
  662. print $fh "M82 ; use absolute distances for extrusion\n";
  663. }
  664. }
  665. # always start with first extruder
  666. # TODO: make sure we select the first *used* extruder
  667. print $fh $gcodegen->set_extruder($self->extruders->[0]);
  668. # calculate X,Y shift to center print around specified origin
  669. my $print_bb = $self->bounding_box;
  670. my $print_size = $print_bb->size;
  671. my @shift = (
  672. $Slic3r::Config->print_center->[X] - unscale($print_size->[X]/2 + $print_bb->x_min),
  673. $Slic3r::Config->print_center->[Y] - unscale($print_size->[Y]/2 + $print_bb->y_min),
  674. );
  675. # initialize a motion planner for object-to-object travel moves
  676. if ($Slic3r::Config->avoid_crossing_perimeters) {
  677. my $distance_from_objects = 1;
  678. # compute the offsetted convex hull for each object and repeat it for each copy.
  679. my @islands = ();
  680. foreach my $obj_idx (0 .. $#{$self->objects}) {
  681. my $convex_hull = convex_hull([
  682. map @{$_->contour->pp}, map @{$_->slices}, @{$self->objects->[$obj_idx]->layers},
  683. ]);
  684. # discard layers only containing thin walls (offset would fail on an empty polygon)
  685. if (@$convex_hull) {
  686. my $expolygon = Slic3r::ExPolygon->new($convex_hull);
  687. $expolygon->translate(scale $shift[X], scale $shift[Y]);
  688. my @island = @{$expolygon->offset_ex(scale $distance_from_objects, 1, JT_SQUARE)};
  689. foreach my $copy (@{ $self->objects->[$obj_idx]->copies }) {
  690. push @islands, map $_->clone->translate(@$copy), @island;
  691. }
  692. }
  693. }
  694. $gcodegen->external_mp(Slic3r::GCode::MotionPlanner->new(
  695. islands => union_ex([ map @$_, @islands ]),
  696. no_internal => 1,
  697. ));
  698. }
  699. # prepare the layer processor
  700. my $layer_gcode = Slic3r::GCode::Layer->new(
  701. print => $self,
  702. gcodegen => $gcodegen,
  703. shift => \@shift,
  704. );
  705. # do all objects for each layer
  706. if ($Slic3r::Config->complete_objects) {
  707. # print objects from the smallest to the tallest to avoid collisions
  708. # when moving onto next object starting point
  709. my @obj_idx = sort { $self->objects->[$a]->size->[Z] <=> $self->objects->[$b]->size->[Z] } 0..$#{$self->objects};
  710. my $finished_objects = 0;
  711. for my $obj_idx (@obj_idx) {
  712. for my $copy (@{ $self->objects->[$obj_idx]->copies }) {
  713. # move to the origin position for the copy we're going to print.
  714. # this happens before Z goes down to layer 0 again, so that
  715. # no collision happens hopefully.
  716. if ($finished_objects > 0) {
  717. $gcodegen->set_shift(map $shift[$_] + unscale $copy->[$_], X,Y);
  718. print $fh $gcodegen->retract;
  719. print $fh $gcodegen->G0(Slic3r::Point->new(0,0), undef, 0, 'move to origin position for next object');
  720. }
  721. my $buffer = Slic3r::GCode::CoolingBuffer->new(
  722. config => $Slic3r::Config,
  723. gcodegen => $gcodegen,
  724. );
  725. my $object = $self->objects->[$obj_idx];
  726. my @layers = sort { $a->print_z <=> $b->print_z } @{$object->layers}, @{$object->support_layers};
  727. for my $layer (@layers) {
  728. # if we are printing the bottom layer of an object, and we have already finished
  729. # another one, set first layer temperatures. this happens before the Z move
  730. # is triggered, so machine has more time to reach such temperatures
  731. if ($layer->id == 0 && $finished_objects > 0) {
  732. printf $fh $gcodegen->set_bed_temperature($Slic3r::Config->first_layer_bed_temperature),
  733. if $Slic3r::Config->first_layer_bed_temperature;
  734. $print_first_layer_temperature->();
  735. }
  736. print $fh $buffer->append(
  737. $layer_gcode->process_layer($layer, [$copy]),
  738. $layer->object."",
  739. $layer->id,
  740. $layer->print_z,
  741. );
  742. }
  743. print $fh $buffer->flush;
  744. $finished_objects++;
  745. }
  746. }
  747. } else {
  748. # order objects using a nearest neighbor search
  749. my @obj_idx = chained_path([ map Slic3r::Point->new(@{$_->copies->[0]}), @{$self->objects} ]);
  750. # sort layers by Z
  751. my %layers = (); # print_z => [ [layers], [layers], [layers] ] by obj_idx
  752. foreach my $obj_idx (0 .. $#{$self->objects}) {
  753. my $object = $self->objects->[$obj_idx];
  754. foreach my $layer (@{$object->layers}, @{$object->support_layers}) {
  755. $layers{ $layer->print_z } ||= [];
  756. $layers{ $layer->print_z }[$obj_idx] ||= [];
  757. push @{$layers{ $layer->print_z }[$obj_idx]}, $layer;
  758. }
  759. }
  760. my $buffer = Slic3r::GCode::CoolingBuffer->new(
  761. config => $Slic3r::Config,
  762. gcodegen => $gcodegen,
  763. );
  764. foreach my $print_z (sort { $a <=> $b } keys %layers) {
  765. foreach my $obj_idx (@obj_idx) {
  766. foreach my $layer (@{ $layers{$print_z}[$obj_idx] // [] }) {
  767. print $fh $buffer->append(
  768. $layer_gcode->process_layer($layer, $layer->object->copies),
  769. $layer->object . ref($layer), # differentiate $obj_id between normal layers and support layers
  770. $layer->id,
  771. $layer->print_z,
  772. );
  773. }
  774. }
  775. }
  776. print $fh $buffer->flush;
  777. }
  778. # save statistic data
  779. $self->total_extrusion_length($gcodegen->total_extrusion_length);
  780. # write end commands to file
  781. print $fh $gcodegen->retract if $gcodegen->extruder; # empty prints don't even set an extruder
  782. print $fh $gcodegen->set_fan(0);
  783. printf $fh "%s\n", $Slic3r::Config->replace_options($Slic3r::Config->end_gcode);
  784. printf $fh "; filament used = %.1fmm (%.1fcm3)\n",
  785. $self->total_extrusion_length, $self->total_extrusion_volume;
  786. if ($Slic3r::Config->gcode_comments) {
  787. # append full config
  788. print $fh "\n";
  789. foreach my $opt_key (sort keys %{$Slic3r::Config}) {
  790. next if $Slic3r::Config::Options->{$opt_key}{shortcut};
  791. next if $Slic3r::Config::Options->{$opt_key}{gui_only};
  792. printf $fh "; %s = %s\n", $opt_key, $Slic3r::Config->serialize($opt_key);
  793. }
  794. }
  795. # close our gcode file
  796. close $fh;
  797. }
  798. sub total_extrusion_volume {
  799. my $self = shift;
  800. return $self->total_extrusion_length * ($self->extruders->[0]->filament_diameter**2) * PI/4 / 1000;
  801. }
  802. # this method will return the supplied input file path after expanding its
  803. # format variables with their values
  804. sub expanded_output_filepath {
  805. my $self = shift;
  806. my ($path, $input_file) = @_;
  807. # if no input file was supplied, take the first one from our objects
  808. $input_file ||= $self->objects->[0]->input_file;
  809. return undef if !defined $input_file;
  810. # if output path is an existing directory, we take that and append
  811. # the specified filename format
  812. $path = File::Spec->join($path, $Slic3r::Config->output_filename_format) if ($path && -d $path);
  813. # if no explicit output file was defined, we take the input
  814. # file directory and append the specified filename format
  815. $path ||= (fileparse($input_file))[1] . $Slic3r::Config->output_filename_format;
  816. my $input_filename = my $input_filename_base = basename($input_file);
  817. $input_filename_base =~ s/\.(?:stl|amf(?:\.xml)?)$//i;
  818. return $Slic3r::Config->replace_options($path, {
  819. input_filename => $input_filename,
  820. input_filename_base => $input_filename_base,
  821. %{ $self->extra_variables },
  822. });
  823. }
  824. 1;