-
Notifications
You must be signed in to change notification settings - Fork 902
Expand file tree
/
Copy pathPerimeterGenerator.cpp
More file actions
2084 lines (1868 loc) · 112 KB
/
Copy pathPerimeterGenerator.cpp
File metadata and controls
2084 lines (1868 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "PerimeterGenerator.hpp"
#include "BridgeDetector.hpp"
#include "ClipperUtils.hpp"
#include "ExtrusionEntityCollection.hpp"
#include "ExPolygonCollection.hpp"
#include "Geometry.hpp"
#include "ShortestPath.hpp"
#include "VariableWidth.hpp"
#include "CurveAnalyzer.hpp"
#include "Clipper2Utils.hpp"
#include "Arachne/WallToolPaths.hpp"
#include "Line.hpp"
#include "Layer.hpp"
#include <cmath>
#include <cassert>
#include <random>
#include <thread>
#include <unordered_set>
#include "OverhangDetector.hpp"
#include "FuzzySkin.hpp"
static const double narrow_loop_length_threshold = 10;
//BBS: when the width of expolygon is smaller than
//ext_perimeter_width + ext_perimeter_spacing * (1 - SMALLER_EXT_INSET_OVERLAP_TOLERANCE),
//we think it's small detail area and will generate smaller line width for it
static constexpr double SMALLER_EXT_INSET_OVERLAP_TOLERANCE = 0.22;
namespace Slic3r {
// Produces a random value between 0 and 1. Thread-safe.
static double random_value() {
thread_local std::random_device rd;
// Hash thread ID for random number seed if no hardware rng seed is available
thread_local std::mt19937 gen(rd.entropy() > 0 ? rd() : std::hash<std::thread::id>()(std::this_thread::get_id()));
thread_local std::uniform_real_distribution<double> dist(0.0, 1.0);
return dist(gen);
}
// Hierarchy of perimeters.
class PerimeterGeneratorLoop {
public:
// Polygon of this contour.
Polygon polygon;
// Is it a contour or a hole?
// Contours are CCW oriented, holes are CW oriented.
bool is_contour;
// BBS: is perimeter using smaller width
bool is_smaller_width_perimeter;
// Depth in the hierarchy. External perimeter has depth = 0. An external perimeter could be both a contour and a hole.
unsigned short depth;
// Slow down speed for circle
bool need_circle_compensation = false;
// Children contour, may be both CCW and CW oriented (outer contours or holes).
std::vector<PerimeterGeneratorLoop> children;
PerimeterGeneratorLoop(const Polygon &polygon, unsigned short depth, bool is_contour, bool is_small_width_perimeter = false, bool need_circle_compensation_ = false) :
polygon(polygon), is_contour(is_contour), is_smaller_width_perimeter(is_small_width_perimeter), depth(depth), need_circle_compensation(need_circle_compensation_) {}
// External perimeter. It may be CCW or CW oriented (outer contour or hole contour).
bool is_external() const { return this->depth == 0; }
// An island, which may have holes, but it does not have another internal island.
bool is_internal_contour() const;
};
#if 0
// Thanks Cura developers for this function.
static void fuzzy_polygon(Polygon &poly, double fuzzy_skin_thickness, double fuzzy_skin_point_distance)
{
const double min_dist_between_points = fuzzy_skin_point_distance * 3. / 4.; // hardcoded: the point distance may vary between 3/4 and 5/4 the supplied value
const double range_random_point_dist = fuzzy_skin_point_distance / 2.;
double dist_left_over = random_value() * (min_dist_between_points / 2.); // the distance to be traversed on the line before making the first new point
Point* p0 = &poly.points.back();
Points out;
out.reserve(poly.points.size());
for (Point &p1 : poly.points)
{ // 'a' is the (next) new point between p0 and p1
Vec2d p0p1 = (p1 - *p0).cast<double>();
double p0p1_size = p0p1.norm();
double p0pa_dist = dist_left_over;
for (; p0pa_dist < p0p1_size;
p0pa_dist += min_dist_between_points + random_value() * range_random_point_dist)
{
double r = random_value() * (fuzzy_skin_thickness * 2.) - fuzzy_skin_thickness;
out.emplace_back(*p0 + (p0p1 * (p0pa_dist / p0p1_size) + perp(p0p1).cast<double>().normalized() * r).cast<coord_t>());
}
dist_left_over = p0pa_dist - p0p1_size;
p0 = &p1;
}
while (out.size() < 3) {
size_t point_idx = poly.size() - 2;
out.emplace_back(poly[point_idx]);
if (point_idx == 0)
break;
-- point_idx;
}
if (out.size() >= 3)
poly.points = std::move(out);
}
// Thanks Cura developers for this function.
static void fuzzy_extrusion_line(Arachne::ExtrusionLine& ext_lines, double fuzzy_skin_thickness, double fuzzy_skin_point_dist)
{
const double min_dist_between_points = fuzzy_skin_point_dist * 3. / 4.; // hardcoded: the point distance may vary between 3/4 and 5/4 the supplied value
const double range_random_point_dist = fuzzy_skin_point_dist / 2.;
double dist_left_over = double(rand()) * (min_dist_between_points / 2) / double(RAND_MAX); // the distance to be traversed on the line before making the first new point
// do not apply hole compensation in fuzzy skin mode
auto* p0 = &ext_lines.front();
std::vector<Arachne::ExtrusionJunction> out;
out.reserve(ext_lines.size());
for (auto& p1 : ext_lines) {
if (p0->p == p1.p) { // Connect endpoints.
out.emplace_back(p1.p, p1.w, p1.perimeter_index, false);
continue;
}
// 'a' is the (next) new point between p0 and p1
Vec2d p0p1 = (p1.p - p0->p).cast<double>();
double p0p1_size = p0p1.norm();
// so that p0p1_size - dist_last_point evaulates to dist_left_over - p0p1_size
double dist_last_point = dist_left_over + p0p1_size * 2.;
for (double p0pa_dist = dist_left_over; p0pa_dist < p0p1_size; p0pa_dist += min_dist_between_points + double(rand()) * range_random_point_dist / double(RAND_MAX)) {
double r = double(rand()) * (fuzzy_skin_thickness * 2.) / double(RAND_MAX) - fuzzy_skin_thickness;
out.emplace_back(p0->p + (p0p1 * (p0pa_dist / p0p1_size) + perp(p0p1).cast<double>().normalized() * r).cast<coord_t>(), p1.w, p1.perimeter_index, false);
dist_last_point = p0pa_dist;
}
dist_left_over = p0p1_size - dist_last_point;
p0 = &p1;
}
while (out.size() < 3) {
size_t point_idx = ext_lines.size() - 2;
out.emplace_back(ext_lines[point_idx].p, ext_lines[point_idx].w, ext_lines[point_idx].perimeter_index,false);
if (point_idx == 0)
break;
--point_idx;
}
if (ext_lines.back().p == ext_lines.front().p) // Connect endpoints.
out.front().p = out.back().p;
if (out.size() >= 3)
ext_lines.junctions = std::move(out);
}
#endif
using PerimeterGeneratorLoops = std::vector<PerimeterGeneratorLoop>;
static void lowpass_filter_by_paths_overhang_degree(ExtrusionPaths& paths) {
const double filter_range = scale_(6.5);
const double threshold_length = scale_(1.2);
//0.save old overhang series first which is input of filter
const int path_num = paths.size();
if (path_num < 2)
//don't need to do filting if only has one path in vector
return;
std::vector<int> old_overhang_series;
old_overhang_series.reserve(path_num);
for (int i = 0; i < path_num; i++)
old_overhang_series.push_back(paths[i].get_overhang_degree());
//1.lowpass filter
for (int i = 0; i < path_num; i++) {
double current_length = paths[i].length();
int current_overhang_degree = old_overhang_series[i];
if (current_length < threshold_length &&
(paths[i].role() == erPerimeter || paths[i].role() == erExternalPerimeter)) {
double left_total_length = (filter_range - current_length) / 2;
double right_total_length = left_total_length;
double temp_length;
int j = i - 1;
int index;
std::vector<std::pair<double, int>> neighbor_path;
while (left_total_length > 0) {
index = (j < 0) ? path_num - 1 : j;
if (paths[index].role() == erOverhangPerimeter)
break;
temp_length = paths[index].length();
if (temp_length > left_total_length)
neighbor_path.emplace_back(std::pair<double, int>(left_total_length, old_overhang_series[index]));
else
neighbor_path.emplace_back(std::pair<double, int>(temp_length, old_overhang_series[index]));
left_total_length -= temp_length;
j = index;
j--;
}
j = i + 1;
while (right_total_length > 0) {
index = j % path_num;
if (paths[index].role() == erOverhangPerimeter)
break;
temp_length = paths[index].length();
if (temp_length > right_total_length)
neighbor_path.emplace_back(std::pair<double, int>(right_total_length, old_overhang_series[index]));
else
neighbor_path.emplace_back(std::pair<double, int>(temp_length, old_overhang_series[index]));
right_total_length -= temp_length;
j++;
}
double sum = 0;
double length_sum = 0;
for (auto it = neighbor_path.begin(); it != neighbor_path.end(); it++) {
sum += (it->first * it->second);
length_sum += it->first;
}
double average_overhang = (double)(current_length * current_overhang_degree + sum) / (length_sum + current_length);
paths[i].set_overhang_degree((int)average_overhang);
}
}
//2.merge path if have same overhang degree. from back to front to avoid data copy
int last_overhang = paths[0].get_overhang_degree();
auto it = paths.begin() + 1;
while (it != paths.end())
{
if (last_overhang == it->get_overhang_degree()) {
//BBS: don't need to append duplicated points, remove the last point
if ((it-1)->polyline.last_point() == it->polyline.first_point())
(it-1)->polyline.points.pop_back();
(it-1)->polyline.append(std::move(it->polyline));
it = paths.erase(it);
} else {
last_overhang = it->get_overhang_degree();
it++;
}
}
}
std::pair<double, double> PerimeterGenerator::dist_boundary(double width)
{
std::pair<double, double> out;
float nozzle_diameter = print_config->nozzle_diameter.get_at(config->wall_filament - 1);
float start_offset = -0.5 * width;
float end_offset = 0.5 * nozzle_diameter;
double degree_0 = scale_(start_offset + 0.5 * (end_offset - start_offset) / (overhang_sampling_number - 1));
out.first = 0;
out.second = scale_(end_offset) - degree_0;
return out;
}
static void detect_bridge_wall(const PerimeterGenerator &perimeter_generator, ExtrusionPaths &paths, const Polylines &remain_polines, ExtrusionRole role, double mm3_per_mm, float width, float height)
{
for (Polyline poly : remain_polines) {
// check if the line is straight line, which mean if the wall is bridge
Line line(poly.first_point(), poly.last_point());
if (line.length() < poly.length()) {
extrusion_paths_append(paths,
std::move(poly),
overhang_sampling_number - 1,
int(0),
role,
mm3_per_mm,
width,
height);
continue;
}
// bridge wall
extrusion_paths_append(paths,
std::move(poly),
overhang_sampling_number,
int(0),
role,
mm3_per_mm,
width,
height);
}
}
static bool is_enable_overhang_speed(const PerimeterGenerator& perimeter_generator)
{
int filament_idx = perimeter_generator.config->wall_filament - 1;
int config_idx = get_process_config_idx(*perimeter_generator.print_config, filament_idx);
bool use_filament_overhang_speed = perimeter_generator.print_config->override_process_overhang_speed.get_at(filament_idx);
return use_filament_overhang_speed ? perimeter_generator.print_config->filament_enable_overhang_speed.get_at(filament_idx) :
perimeter_generator.config->enable_overhang_speed.get_at(config_idx);
}
static bool fuzzy_skin_allows_overhang_slowdown(const PerimeterGenerator &pg)
{
const FuzzySkinType fs = pg.config->fuzzy_skin.value;
return fs == FuzzySkinType::Disabled_fuzzy || fs == FuzzySkinType::None;
}
static ExtrusionEntityCollection traverse_loops(const PerimeterGenerator &perimeter_generator, const PerimeterGeneratorLoops &loops, ThickPolylines &thin_walls)
{
// loops is an arrayref of ::Loop objects
// turn each one into an ExtrusionLoop object
ExtrusionEntityCollection coll;
for (const PerimeterGeneratorLoop &loop : loops) {
bool is_external = loop.is_external();
bool is_small_width = loop.is_smaller_width_perimeter;
CustomizeFlag flag = loop.need_circle_compensation ? CustomizeFlag::cfCircleCompensation : CustomizeFlag::cfNone;
ExtrusionRole role;
ExtrusionLoopRole loop_role;
role = is_external ? erExternalPerimeter : erPerimeter;
if (loop.is_internal_contour()) {
// Note that we set loop role to ContourInternalPerimeter
// also when loop is both internal and external (i.e.
// there's only one contour loop).
loop_role = elrContourInternalPerimeter;
} else {
loop_role = loop.is_contour? elrDefault: elrPerimeterHole;
}
if( loop.depth == 1 ) {
if (loop_role == elrDefault)
loop_role = elrSecondPerimeter;
else
loop_role = loop_role | elrSecondPerimeter;
}
// detect overhanging/bridging perimeters
ExtrusionPaths paths;
// BBS: get lower polygons series, width, mm3_per_mm
const std::vector<Polygons> *lower_polygons_series;
const std::pair<double, double> *overhang_dist_boundary;
double extrusion_mm3_per_mm;
double extrusion_width;
if (is_external) {
if (is_small_width) {
//BBS: smaller width external perimeter
lower_polygons_series = &perimeter_generator.m_smaller_external_lower_polygons_series;
overhang_dist_boundary = &perimeter_generator.m_smaller_external_overhang_dist_boundary;
extrusion_mm3_per_mm = perimeter_generator.smaller_width_ext_mm3_per_mm();
extrusion_width = perimeter_generator.smaller_ext_perimeter_flow.width();
} else {
//BBS: normal external perimeter
lower_polygons_series = &perimeter_generator.m_external_lower_polygons_series;
overhang_dist_boundary = &perimeter_generator.m_external_overhang_dist_boundary;
extrusion_mm3_per_mm = perimeter_generator.ext_mm3_per_mm();
extrusion_width = perimeter_generator.ext_perimeter_flow.width();
}
} else {
//BBS: normal perimeter
lower_polygons_series = &perimeter_generator.m_lower_polygons_series;
overhang_dist_boundary = &perimeter_generator.m_lower_overhang_dist_boundary;
extrusion_mm3_per_mm = perimeter_generator.mm3_per_mm();
extrusion_width = perimeter_generator.perimeter_flow.width();
}
// Apply fuzzy skin if it is enabled for at least some part of the polygon.
const Polygon polygon = apply_fuzzy_skin(loop.polygon, *(perimeter_generator.config), *(perimeter_generator.perimeter_regions),
perimeter_generator.layer_id, loop.depth, loop.is_contour, perimeter_generator.slice_z);
if (perimeter_generator.config->detect_overhang_wall && perimeter_generator.layer_id > perimeter_generator.object_config->raft_layers) {
// get non 100% overhang paths by intersecting this loop with the grown lower slices
// prepare grown lower layer slices for overhang detection
BoundingBox bbox(polygon.points);
bbox.offset(SCALED_EPSILON);
Polylines remain_polines;
//BBS: don't calculate overhang degree when enable fuzzy skin. It's unmeaning
Polygons lower_polygons_series_clipped = ClipperUtils::clip_clipper_polygons_with_subject_bbox(lower_polygons_series->back(), bbox);
Polylines inside_polines = intersection_pl_2({to_polyline(polygon)}, lower_polygons_series_clipped);
remain_polines = diff_pl_2({to_polyline(polygon)}, lower_polygons_series_clipped);
bool detect_overhang_speed = is_enable_overhang_speed(perimeter_generator) && fuzzy_skin_allows_overhang_slowdown(perimeter_generator);
if (!detect_overhang_speed) {
if (!inside_polines.empty())
extrusion_paths_append(
paths,
std::move(inside_polines),
0,
int(0),
role,
extrusion_mm3_per_mm,
extrusion_width,
(float)perimeter_generator.layer_height);
} else {
Polygons lower_polygons_series_clipped = ClipperUtils::clip_clipper_polygons_with_subject_bbox(lower_polygons_series->front(), bbox);
Polylines middle_overhang_polyines = diff_pl_2(inside_polines, lower_polygons_series_clipped);
//BBS: add zero_degree_path
Polylines zero_degree_polines = intersection_pl_2(inside_polines, lower_polygons_series_clipped);
if (!zero_degree_polines.empty())
extrusion_paths_append(
paths,
std::move(zero_degree_polines),
0,
int(0),
role,
extrusion_mm3_per_mm,
extrusion_width,
(float)perimeter_generator.layer_height);
//BBS: detect middle line overhang
if (!middle_overhang_polyines.empty()) {
detect_overhang_degree(lower_polygons_series->front(),
role,
extrusion_mm3_per_mm,
extrusion_width,
(float) perimeter_generator.layer_height,
middle_overhang_polyines,
overhang_dist_boundary->first,
overhang_dist_boundary->second,
paths);
}
}
// get 100% overhang paths by checking what parts of this loop fall
// outside the grown lower slices (thus where the distance between
// the loop centerline and original lower slices is >= half nozzle diameter
if (remain_polines.size() != 0) {
if (!((perimeter_generator.object_config->enable_support || perimeter_generator.object_config->enforce_support_layers > 0) &&
perimeter_generator.object_config->support_top_z_distance.value == 0)) {
//detect if the overhang perimeter is bridge
detect_bridge_wall(perimeter_generator,
paths,
remain_polines,
erOverhangPerimeter,
perimeter_generator.mm3_per_mm_overhang(),
perimeter_generator.overhang_flow.width(),
perimeter_generator.overhang_flow.height());
} else {
detect_bridge_wall( perimeter_generator,
paths,
remain_polines,
role,
extrusion_mm3_per_mm,
extrusion_width,
(float)perimeter_generator.layer_height);
}
}
if (paths.empty())
continue;
// Reapply the nearest point search for starting point.
// We allow polyline reversal because Clipper may have randomly reversed polylines during clipping.
chain_and_reorder_extrusion_paths(paths, &paths.front().first_point());
} else {
ExtrusionPath path(role);
//BBS.
path.polyline = polygon.split_at_first_point();
path.overhang_degree = 0;
path.curve_degree = 0;
path.mm3_per_mm = extrusion_mm3_per_mm;
path.width = extrusion_width;
path.height = (float)perimeter_generator.layer_height;
paths.emplace_back(std::move(path));
}
for (ExtrusionPath& path : paths) {
path.set_customize_flag(flag);
}
coll.append(ExtrusionLoop(std::move(paths), loop_role, flag));
}
// Append thin walls to the nearest-neighbor search (only for first iteration)
Point zero_point(0, 0);
if (! thin_walls.empty()) {
BoundingBox bbox;
for (auto &entity : coll.entities) { bbox.merge(entity->as_polyline().bounding_box()); }
for (auto& thin_wall : thin_walls) {
// find the corner of bbox that's farthest from the thin wall
Point corner_far = bbox.min;
if ((corner_far.cast<double>() - thin_wall.first_point().cast<double>()).squaredNorm() <
(bbox.max.cast<double>() - thin_wall.first_point().cast<double>()).squaredNorm())
corner_far = bbox.max;
zero_point = corner_far;
}
variable_width(thin_walls, erExternalPerimeter, perimeter_generator.ext_perimeter_flow, coll.entities);
thin_walls.clear();
}
// Traverse children and build the final collection.
std::vector<std::pair<size_t, bool>> chain = chain_extrusion_entities(coll.entities, &zero_point);
ExtrusionEntityCollection out;
for (const std::pair<size_t, bool> &idx : chain) {
assert(coll.entities[idx.first] != nullptr);
if (idx.first >= loops.size()) {
// This is a thin wall.
out.entities.reserve(out.entities.size() + 1);
out.entities.emplace_back(coll.entities[idx.first]);
coll.entities[idx.first] = nullptr;
if (idx.second)
out.entities.back()->reverse();
} else {
const PerimeterGeneratorLoop &loop = loops[idx.first];
assert(thin_walls.empty());
ExtrusionEntityCollection children = traverse_loops(perimeter_generator, loop.children, thin_walls);
out.entities.reserve(out.entities.size() + children.entities.size() + 1);
ExtrusionLoop *eloop = static_cast<ExtrusionLoop*>(coll.entities[idx.first]);
coll.entities[idx.first] = nullptr;
if (loop.is_contour) {
eloop->make_counter_clockwise();
out.append(std::move(children.entities));
out.entities.emplace_back(eloop);
} else {
eloop->make_clockwise();
out.entities.emplace_back(eloop);
out.append(std::move(children.entities));
}
}
}
return out;
}
struct PerimeterGeneratorArachneExtrusion
{
Arachne::ExtrusionLine* extrusion = nullptr;
// Indicates if closed ExtrusionLine is a contour or a hole. Used it only when ExtrusionLine is a closed loop.
bool is_contour = false;
// Should this extrusion be fuzzyfied on path generation?
bool fuzzify = false;
};
static void smooth_overhang_level(ExtrusionPaths &paths)
{
const double threshold_length = scale_(0.8);
const double filter_range = scale_(6.5);
// 0.save old overhang series first which is input of filter
const int path_num = paths.size();
if (path_num < 2)
// don't need to do filting if only has one path in vector
return;
std::vector<int> old_overhang_series;
old_overhang_series.reserve(path_num);
for (int i = 0; i < path_num; i++) old_overhang_series.push_back(paths[i].get_overhang_degree());
for (int i = 0; i < path_num;) {
if ((paths[i].role() != erPerimeter && paths[i].role() != erExternalPerimeter)) {
i++;
continue;
}
double current_length = paths[i].length();
int current_overhang_degree = old_overhang_series[i];
double total_lens = current_length;
int pt = i + 1;
for (; pt < path_num; pt++) {
if (paths[pt].get_overhang_degree() != current_overhang_degree || (paths[pt].role() != erPerimeter && paths[pt].role() != erExternalPerimeter)) {
break;
}
total_lens += paths[pt].length();
}
if (total_lens < threshold_length) {
double left_total_length = (filter_range - total_lens) / 2;
double right_total_length = left_total_length;
double temp_length;
int j = i - 1;
int index;
std::vector<std::pair<double, int>> neighbor_path;
while (left_total_length > 0) {
index = (j < 0) ? path_num - 1 : j;
if (paths[index].role() == erOverhangPerimeter) break;
temp_length = paths[index].length();
if (temp_length > left_total_length)
neighbor_path.emplace_back(std::pair<double, int>(left_total_length, old_overhang_series[index]));
else
neighbor_path.emplace_back(std::pair<double, int>(temp_length, old_overhang_series[index]));
left_total_length -= temp_length;
j = index;
j--;
}
j = pt;
while (right_total_length > 0) {
index = j % path_num;
if (paths[index].role() == erOverhangPerimeter) break;
temp_length = paths[index].length();
if (temp_length > right_total_length)
neighbor_path.emplace_back(std::pair<double, int>(right_total_length, old_overhang_series[index]));
else
neighbor_path.emplace_back(std::pair<double, int>(temp_length, old_overhang_series[index]));
right_total_length -= temp_length;
j++;
}
double sum = 0;
double length_sum = 0;
for (auto it = neighbor_path.begin(); it != neighbor_path.end(); it++) {
sum += (it->first * it->second);
length_sum += it->first;
}
double average_overhang = (double) (total_lens * current_overhang_degree + sum) / (length_sum + total_lens);
for (int idx=i; idx<pt;idx++)
paths[idx].set_overhang_degree((int) average_overhang);
}
i = pt;
}
}
static void detect_brigde_wall_arachne(const PerimeterGenerator &perimeter_generator, ExtrusionPaths &paths, const ClipperLib_Z::Paths &path_overhang, const ExtrusionRole role, const Flow &flow)
{
for (ClipperLib_Z::Path path : path_overhang) {
// check if the line is straight line, which mean if the wall is bridge
ThickPolyline thick_polyline = Arachne::to_thick_polyline(path);
Line line(thick_polyline.front(), thick_polyline.back());
if (line.length() < thick_polyline.length()) {
extrusion_path_append(paths,
std::move(thick_polyline),
role,
flow,
overhang_sampling_number - 1);
continue;
}
extrusion_path_append(paths,
std::move(thick_polyline),
role,
flow,
overhang_sampling_number);
}
}
static ExtrusionEntityCollection traverse_extrusions(const PerimeterGenerator& perimeter_generator, std::vector<PerimeterGeneratorArachneExtrusion>& pg_extrusions)
{
using ZPath = ClipperLib_Z::Path;
using ZPaths = ClipperLib_Z::Paths;
ExtrusionEntityCollection extrusion_coll;
if (perimeter_generator.print_config->z_direction_outwall_speed_continuous)
extrusion_coll.loop_node_range.first = perimeter_generator.loop_nodes->size();
for (PerimeterGeneratorArachneExtrusion &pg_extrusion : pg_extrusions) {
Arachne::ExtrusionLine* extrusion = pg_extrusion.extrusion;
if (extrusion->empty())
continue;
//get extrusion date
const bool is_external = extrusion->inset_idx == 0;
ExtrusionRole role = is_external ? erExternalPerimeter : erPerimeter;
if (is_external && perimeter_generator.print_config->z_direction_outwall_speed_continuous) {
LoopNode node;
NodeContour node_contour;
node_contour.is_loop = extrusion->is_closed;
for (size_t i = 0; i < extrusion->junctions.size(); i++) {
node_contour.pts.push_back(extrusion->junctions[i].p);
node_contour.widths.push_back(extrusion->junctions[i].w);
}
node.node_contour = node_contour;
node.node_id = perimeter_generator.loop_nodes->size();
node.loop_id = extrusion_coll.entities.size();
node.bbox = get_extents(node.node_contour.pts);
node.bbox.offset(perimeter_generator.config->outer_wall_line_width/2);
perimeter_generator.loop_nodes->push_back(std::move(node));
}
// Apply fuzzy skin if it is enabled for at least some part of the ExtrusionLine.
*extrusion = apply_fuzzy_skin(*extrusion, *(perimeter_generator.config), *(perimeter_generator.perimeter_regions), perimeter_generator.layer_id,
pg_extrusion.extrusion->inset_idx, !pg_extrusion.extrusion->is_closed || pg_extrusion.is_contour, perimeter_generator.slice_z);
ExtrusionPaths paths;
// detect overhanging/bridging perimeters
if (perimeter_generator.config->detect_overhang_wall && perimeter_generator.layer_id > perimeter_generator.object_config->raft_layers) {
ClipperLib_Z::Path extrusion_path;
extrusion_path.reserve(extrusion->size());
double nozzle_diameter = perimeter_generator.print_config->nozzle_diameter.get_at(perimeter_generator.config->wall_filament - 1);
Polygons lower_layer_polys = perimeter_generator.lower_slices_polygons();
coord_t max_extrusion_width = 0;
BoundingBox extrusion_path_bbox;
for (const Arachne::ExtrusionJunction &ej : extrusion->junctions) {
extrusion_path.emplace_back(ej.p.x(), ej.p.y(), ej.w);
extrusion_path_bbox.merge(Point(ej.p.x(), ej.p.y()));
max_extrusion_width = std::max(max_extrusion_width, ej.w);
}
extrusion_path_bbox.inflated(max_extrusion_width+scale_(nozzle_diameter));
Polygons new_lower_polys;
for (size_t idx = 0; idx < lower_layer_polys.size(); ++idx) {
auto new_poly = ClipperUtils::clip_clipper_polygon_with_subject_bbox(lower_layer_polys[idx], extrusion_path_bbox,true);
if (!new_poly.empty())
new_lower_polys.emplace_back(new_poly);
}
lower_layer_polys = new_lower_polys;
ZPath subject_path;
for (auto& ej : extrusion->junctions)
subject_path.emplace_back(ej.p.x(), ej.p.y(), ej.w);
ZPaths clip_paths;
for (auto& poly : lower_layer_polys) {
clip_paths.emplace_back();
for (auto& p : poly)
clip_paths.back().emplace_back(p.x(), p.y(), 0);
}
if (is_enable_overhang_speed(perimeter_generator) && fuzzy_skin_allows_overhang_slowdown(perimeter_generator)) {
bool is_external = extrusion->inset_idx == 0;
Flow flow = is_external ? perimeter_generator.ext_perimeter_flow : perimeter_generator.perimeter_flow;
ExtrusionRole role = is_external ? ExtrusionRole::erExternalPerimeter : ExtrusionRole::erPerimeter;
paths = detect_overhang_degree(flow, role, lower_layer_polys, clip_paths, subject_path, nozzle_diameter);
}
else {
ExtrusionPaths temp_paths;
ZPaths path_non_overhang = clip_extrusion(subject_path, clip_paths, ClipperLib_Z::ctIntersection);
// get non-overhang paths by intersecting this loop with the grown lower slices
extrusion_paths_append(temp_paths, path_non_overhang, role,
is_external ? perimeter_generator.ext_perimeter_flow : perimeter_generator.perimeter_flow);
paths = std::move(temp_paths);
}
// get overhang paths by checking what parts of this loop fall
// outside the grown lower slices (thus where the distance between
// the loop centerline and original lower slices is >= half nozzle diameter
// detect if the overhang perimeter is bridge
ZPaths path_overhang = clip_extrusion(subject_path, clip_paths, ClipperLib_Z::ctDifference);
bool zero_z_support = (perimeter_generator.object_config->enable_support || perimeter_generator.object_config->enforce_support_layers > 0) && perimeter_generator.object_config->support_top_z_distance.value == 0;
if(zero_z_support)
detect_brigde_wall_arachne(perimeter_generator, paths, path_overhang, role, is_external ? perimeter_generator.ext_perimeter_flow : perimeter_generator.perimeter_flow);
else
detect_brigde_wall_arachne(perimeter_generator, paths, path_overhang, erOverhangPerimeter, perimeter_generator.overhang_flow);
// Reapply the nearest point search for starting point.
// We allow polyline reversal because Clipper may have randomly reversed polylines during clipping.
// Arachne sometimes creates extrusion with zero-length (just two same endpoints);
if (!paths.empty()) {
Point start_point = paths.front().first_point();
if (!extrusion->is_closed) {
// Especially for open extrusion, we need to select a starting point that is at the start
// or the end of the extrusions to make one continuous line. Also, we prefer a non-overhang
// starting point.
struct PointInfo
{
size_t occurrence = 0;
bool is_overhang = false;
};
std::unordered_map<Point, PointInfo, PointHash> point_occurrence;
for (const ExtrusionPath& path : paths) {
++point_occurrence[path.polyline.first_point()].occurrence;
++point_occurrence[path.polyline.last_point()].occurrence;
if (path.role() == erOverhangPerimeter) {
point_occurrence[path.polyline.first_point()].is_overhang = true;
point_occurrence[path.polyline.last_point()].is_overhang = true;
}
}
// Prefer non-overhang point as a starting point.
for (const std::pair<Point, PointInfo> pt : point_occurrence)
if (pt.second.occurrence == 1) {
start_point = pt.first;
if (!pt.second.is_overhang) {
start_point = pt.first;
break;
}
}
}
chain_and_reorder_extrusion_paths(paths, &start_point);
if (is_enable_overhang_speed(perimeter_generator) && fuzzy_skin_allows_overhang_slowdown(perimeter_generator)) {
// BBS: filter the speed
smooth_overhang_level(paths);
}
}
} else {
extrusion_paths_append(paths, *extrusion, role, is_external ? perimeter_generator.ext_perimeter_flow : perimeter_generator.perimeter_flow);
}
bool apply_hole_compensation = extrusion->shouldApplyHoleCompensation();
// Append paths to collection.
if (!paths.empty()) {
if (extrusion->is_closed) {
ExtrusionLoop extrusion_loop(std::move(paths), extrusion->is_contour()? elrDefault : elrPerimeterHole);
// Restore the orientation of the extrusion loop.
if (pg_extrusion.is_contour)
extrusion_loop.make_counter_clockwise();
else
extrusion_loop.make_clockwise();
for (auto it = std::next(extrusion_loop.paths.begin()); it != extrusion_loop.paths.end(); ++it) {
assert(it->polyline.points.size() >= 2);
assert(std::prev(it)->polyline.last_point() == it->polyline.first_point());
}
assert(extrusion_loop.paths.front().first_point() == extrusion_loop.paths.back().last_point());
if (apply_hole_compensation) {
for (auto& path : extrusion_loop.paths)
path.set_customize_flag(CustomizeFlag::cfCircleCompensation);
extrusion_loop.set_customize_flag(CustomizeFlag::cfCircleCompensation);
}
extrusion_coll.append(std::move(extrusion_loop));
}
else {
// Because we are processing one ExtrusionLine all ExtrusionPaths should form one connected path.
// But there is possibility that due to numerical issue there is poss
assert([&paths = std::as_const(paths)]() -> bool {
for (auto it = std::next(paths.begin()); it != paths.end(); ++it)
if (std::prev(it)->polyline.last_point() != it->polyline.first_point())
return false;
return true;
}());
ExtrusionMultiPath multi_path;
multi_path.paths.emplace_back(std::move(paths.front()));
for (auto it_path = std::next(paths.begin()); it_path != paths.end(); ++it_path) {
if (multi_path.paths.back().last_point() != it_path->first_point()) {
extrusion_coll.append(ExtrusionMultiPath(std::move(multi_path)));
multi_path = ExtrusionMultiPath();
}
multi_path.paths.emplace_back(std::move(*it_path));
}
if (apply_hole_compensation) {
for (auto& path : multi_path.paths)
path.set_customize_flag(CustomizeFlag::cfCircleCompensation);
multi_path.set_customize_flag(CustomizeFlag::cfCircleCompensation);
}
extrusion_coll.append(ExtrusionMultiPath(std::move(multi_path)));
}
}
}
if (perimeter_generator.print_config->z_direction_outwall_speed_continuous)
extrusion_coll.loop_node_range.second = perimeter_generator.loop_nodes->size();
return extrusion_coll;
}
static Polygons to_polygons_with_flag(const ExPolygon& src, const bool contour_flag, const std::vector<int>& holes_flag, std::vector<int>& flags_out)
{
Polygons polygons;
polygons.reserve(src.num_contours());
polygons.push_back(src.contour);
polygons.insert(polygons.end(), src.holes.begin(), src.holes.end());
flags_out.reserve(holes_flag.size() + 1);
if(contour_flag == true)
flags_out.emplace_back(0);
for (size_t idx = 0; idx < holes_flag.size(); ++idx)
flags_out.emplace_back(holes_flag[idx] + 1);
return polygons;
}
void PerimeterGenerator::process_classic()
{
// other perimeters
m_mm3_per_mm = this->perimeter_flow.mm3_per_mm();
coord_t perimeter_width = this->perimeter_flow.scaled_width();
coord_t perimeter_spacing = this->perimeter_flow.scaled_spacing();
// external perimeters
m_ext_mm3_per_mm = this->ext_perimeter_flow.mm3_per_mm();
coord_t ext_perimeter_width = this->ext_perimeter_flow.scaled_width();
coord_t ext_perimeter_spacing = this->ext_perimeter_flow.scaled_spacing();
coord_t ext_perimeter_spacing2;
// Orca: ignore precise_outer_wall if wall_sequence is not InnerOuter
if (config->precise_outer_wall && config->wall_sequence == WallSequence::InnerOuter)
ext_perimeter_spacing2 = scaled<coord_t>(0.5f * (this->ext_perimeter_flow.width() + this->perimeter_flow.width()));
else
ext_perimeter_spacing2 = scaled<coord_t>(0.5f * (this->ext_perimeter_flow.spacing() + this->perimeter_flow.spacing()));
// overhang perimeters
m_mm3_per_mm_overhang = this->overhang_flow.mm3_per_mm();
// solid infill
coord_t solid_infill_spacing = this->solid_infill_flow.scaled_spacing();
// Calculate the minimum required spacing between two adjacent traces.
// This should be equal to the nominal flow spacing but we experiment
// with some tolerance in order to avoid triggering medial axis when
// some squishing might work. Loops are still spaced by the entire
// flow spacing; this only applies to collapsing parts.
// For ext_min_spacing we use the ext_perimeter_spacing calculated for two adjacent
// external loops (which is the correct way) instead of using ext_perimeter_spacing2
// which is the spacing between external and internal, which is not correct
// and would make the collapsing (thus the details resolution) dependent on
// internal flow which is unrelated.
coord_t min_spacing = coord_t(perimeter_spacing * (1 - INSET_OVERLAP_TOLERANCE));
coord_t ext_min_spacing = coord_t(ext_perimeter_spacing * (1 - INSET_OVERLAP_TOLERANCE));
bool has_gap_fill = this->config->gap_infill_speed.get_at(get_process_config_idx(*print_config, this->config->wall_filament - 1)) > 0;
// BBS: this flow is for smaller external perimeter for small area
coord_t ext_min_spacing_smaller = coord_t(ext_perimeter_spacing * (1 - SMALLER_EXT_INSET_OVERLAP_TOLERANCE));
this->smaller_ext_perimeter_flow = this->ext_perimeter_flow;
// BBS: to be checked
this->smaller_ext_perimeter_flow = this->smaller_ext_perimeter_flow.with_width(SCALING_FACTOR *
(ext_perimeter_width - 0.5 * SMALLER_EXT_INSET_OVERLAP_TOLERANCE * ext_perimeter_spacing));
m_ext_mm3_per_mm_smaller_width = this->smaller_ext_perimeter_flow.mm3_per_mm();
// prepare grown lower layer slices for overhang detection
m_lower_polygons_series = generate_lower_polygons_series(this->perimeter_flow.width());
m_lower_overhang_dist_boundary = dist_boundary(this->perimeter_flow.width());
if (ext_perimeter_width == perimeter_width){
m_external_lower_polygons_series = m_lower_polygons_series;
m_external_overhang_dist_boundary=m_lower_overhang_dist_boundary;
} else {
m_external_lower_polygons_series = generate_lower_polygons_series(this->ext_perimeter_flow.width());
m_external_overhang_dist_boundary = dist_boundary(this->ext_perimeter_flow.width());
}
m_smaller_external_lower_polygons_series = generate_lower_polygons_series(this->smaller_ext_perimeter_flow.width());
m_smaller_external_overhang_dist_boundary = dist_boundary(this->smaller_ext_perimeter_flow.width());
// we need to process each island separately because we might have different
// extra perimeters for each one
Surfaces all_surfaces = this->slices->surfaces;
process_no_bridge(all_surfaces, perimeter_spacing, ext_perimeter_width);
// BBS: don't simplify too much which influence arc fitting when export gcode if arc_fitting is enabled
double surface_simplify_resolution = (print_config->enable_arc_fitting && this->config->fuzzy_skin == FuzzySkinType::None) ? 0.2 * m_scaled_resolution : m_scaled_resolution;
//BBS: reorder the surface to reduce the travel time
ExPolygons surface_exp;
for (const Surface &surface : all_surfaces)
surface_exp.push_back(surface.expolygon);
std::vector<size_t> surface_order = chain_expolygons(surface_exp);
for (size_t order_idx = 0; order_idx < surface_order.size(); order_idx++) {
const Surface &surface = all_surfaces[surface_order[order_idx]];
// detect how many perimeters must be generated for this island
int loop_number = this->config->wall_loops + surface.extra_perimeters - 1; // 0-indexed loops
if (this->config->alternate_extra_wall && this->layer_id % 2 == 1 && !m_spiral_vase)
loop_number++;
//BBS: set the topmost and bottom most layer to be one wall
if (loop_number > 0 && ((this->object_config->top_one_wall_type != TopOneWallType::None && this->upper_slices == nullptr) || (this->object_config->only_one_wall_first_layer && layer_id == 0)))
loop_number = 0;
bool counter_circle_compensation = surface.counter_circle_compensation;
std::vector<Point> compensation_holes_centers;
for (int i : surface.holes_circle_compensation) {
Point center = surface.expolygon.holes[i].centroid();
compensation_holes_centers.emplace_back(center);
}
double eps = 1000;
auto is_compensation_hole = [&compensation_holes_centers, &eps](const Polygon &hole) -> bool {
auto iter = std::find_if(compensation_holes_centers.begin(), compensation_holes_centers.end(), [&hole, &eps](const Point &item) {
double distance = std::sqrt(std::pow(hole.centroid().x() - item.x(), 2) + std::pow(hole.centroid().y() - item.y(), 2));
return distance < eps;
});
return iter != compensation_holes_centers.end();
};
ExPolygons last = union_ex(surface.expolygon.simplify_p(surface_simplify_resolution));
if (last.size() != 1)
counter_circle_compensation = false;
ExPolygons gaps;
ExPolygons top_fills;
ExPolygons fill_clip;
std::vector<NodeContour> outwall_paths;
if (loop_number >= 0) {
// In case no perimeters are to be generated, loop_number will equal to -1.
std::vector<PerimeterGeneratorLoops> contours(loop_number+1); // depth => loops
std::vector<PerimeterGeneratorLoops> holes(loop_number+1); // depth => loops
ThickPolylines thin_walls;
// we loop one time more than needed in order to find gaps after the last perimeter was applied
for (int i = 0;; ++ i) { // outer loop is 0
// Calculate next onion shell of perimeters.
ExPolygons offsets;
ExPolygons offsets_with_smaller_width;
if (i == 0) {
// look for thin walls
if (this->config->detect_thin_wall) {
// the minimum thickness of a single loop is:
// ext_width/2 + ext_spacing/2 + spacing/2 + width/2
offsets = offset2_ex(last,
-float(ext_perimeter_width / 2. + ext_min_spacing / 2. - 1),
+float(ext_min_spacing / 2. - 1));
// the following offset2 ensures almost nothing in @thin_walls is narrower than $min_width
// (actually, something larger than that still may exist due to mitering or other causes)
coord_t min_width = coord_t(scale_(this->ext_perimeter_flow.nozzle_diameter() / 3));
ExPolygons expp = opening_ex(
// medial axis requires non-overlapping geometry
diff_ex(last, offset(offsets, float(ext_perimeter_width / 2.) + ClipperSafetyOffset)),
float(min_width / 2.));
// the maximum thickness of our thin wall area is equal to the minimum thickness of a single loop
for (ExPolygon &ex : expp)
ex.medial_axis(min_width, ext_perimeter_width + ext_perimeter_spacing2, &thin_walls);
} else {
coord_t ext_perimeter_smaller_width = this->smaller_ext_perimeter_flow.scaled_width();
for (const ExPolygon& expolygon : last) {
// BBS: judge whether it's narrow but not too long island which is hard to place two line
ExPolygons expolys;
expolys.push_back(expolygon);
ExPolygons offset_result = offset2_ex(expolys,
-float(ext_perimeter_width / 2. + ext_min_spacing_smaller / 2.),
+float(ext_min_spacing_smaller / 2.));
if (offset_result.empty() &&
expolygon.area() < (double)(ext_perimeter_width + ext_min_spacing_smaller) * scale_(narrow_loop_length_threshold)) {
// BBS: for narrow external loop, use smaller line width
ExPolygons temp_result = offset_ex(expolygon, -float(ext_perimeter_smaller_width / 2.));