-
-
Notifications
You must be signed in to change notification settings - Fork 919
Expand file tree
/
Copy pathTreeModelVolumes.cpp
More file actions
1296 lines (1146 loc) · 61.4 KB
/
TreeModelVolumes.cpp
File metadata and controls
1296 lines (1146 loc) · 61.4 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
// Copyright (c) 2023 UltiMaker
// CuraEngine is released under the terms of the AGPLv3 or higher
#include "TreeModelVolumes.h"
#include <range/v3/view/enumerate.hpp>
#include <range/v3/view/iota.hpp>
#include <range/v3/view/reverse.hpp>
#include <spdlog/spdlog.h>
#include "PrimeTower/PrimeTower.h"
#include "TreeSupport.h"
#include "TreeSupportEnums.h"
#include "progress/Progress.h"
#include "sliceDataStorage.h"
#include "utils/ThreadPool.h"
#include "utils/algorithm.h"
namespace cura
{
TreeModelVolumes::TreeModelVolumes(
const SliceDataStorage& storage,
const coord_t max_move,
const coord_t max_move_slow,
const coord_t min_offset_per_step,
size_t current_mesh_idx,
double progress_multiplier,
double progress_offset,
const std::vector<Shape>& additional_excluded_areas)
: max_move_{ std::max(max_move - 2, coord_t(0)) }
, // -2 to avoid rounding errors
max_move_slow_{ std::max(max_move_slow - 2, coord_t(0)) }
, // -2 to avoid rounding errors
min_offset_per_step_{ min_offset_per_step }
, progress_multiplier_{ progress_multiplier }
, progress_offset_{ progress_offset }
, machine_border_{ calculateMachineBorderCollision(storage.getMachineBorder()) }
, machine_area_{ storage.getMachineBorder() }
{
anti_overhang_ = std::vector<Shape>(storage.support.supportLayers.size(), Shape());
std::unordered_map<size_t, size_t> mesh_to_layeroutline_idx;
// Get, for all participating meshes, simplification settings, and support settings that can be set per mesh.
// NOTE: The setting 'support_type' (used here for 'support_rests_on_model' is not settable per mesh, if this stays that way, we could simplify the code a bit.
// Currently in the middle of rethinking support, so this stays.
coord_t min_maximum_resolution = std::numeric_limits<coord_t>::max();
coord_t min_maximum_deviation = std::numeric_limits<coord_t>::max();
coord_t min_maximum_area_deviation = std::numeric_limits<coord_t>::max();
for (auto [mesh_idx, mesh_ptr] : storage.meshes | ranges::views::enumerate)
{
auto& mesh = *mesh_ptr;
bool added = false;
for (auto [idx, layer_outline] : layer_outlines_ | ranges::views::enumerate)
{
if (checkSettingsEquality(layer_outline.first, mesh.settings))
{
added = true;
mesh_to_layeroutline_idx[mesh_idx] = idx;
}
}
if (! added)
{
mesh_to_layeroutline_idx[mesh_idx] = layer_outlines_.size();
layer_outlines_.emplace_back(mesh.settings, std::vector<Shape>(storage.support.supportLayers.size(), Shape()));
}
}
for (const auto data_pair : layer_outlines_)
{
support_rests_on_model_ |= data_pair.first.get<ESupportType>("support_type") == ESupportType::EVERYWHERE;
min_maximum_deviation = std::min(min_maximum_deviation, data_pair.first.get<coord_t>("meshfix_maximum_deviation"));
min_maximum_resolution = std::min(min_maximum_resolution, data_pair.first.get<coord_t>("meshfix_maximum_resolution"));
min_maximum_area_deviation = std::min(min_maximum_area_deviation, data_pair.first.get<coord_t>("meshfix_maximum_extrusion_area_deviation"));
}
// Figure out the rest of the setting(-like variable)s relevant to the class a whole.
current_outline_idx_ = mesh_to_layeroutline_idx[current_mesh_idx];
const TreeSupportSettings config(layer_outlines_[current_outline_idx_].first);
if (config.support_overrides == SupportDistPriority::Z_OVERRIDES_XY)
{
current_min_xy_dist_ = config.xy_min_distance;
if (TreeSupportSettings::has_to_rely_on_min_xy_dist_only)
{
current_min_xy_dist_ = std::max(current_min_xy_dist_, coord_t(FUDGE_LENGTH * 2));
}
current_min_xy_dist_delta_ = std::max(config.xy_distance - current_min_xy_dist_, coord_t(0));
}
else
{
current_min_xy_dist_ = config.xy_distance;
current_min_xy_dist_delta_ = 0;
}
increase_until_radius_ = config.increase_radius_until_radius;
// Retrieve all layer outlines. Done in this way because normally we don't do this per mesh, but for the whole buildplate.
// (So we can handle some settings on a per-mesh basis.)
for (auto [mesh_idx, mesh] : storage.meshes | ranges::views::enumerate)
{
// Workaround for compiler bug on apple-clang -- Closure won't properly capture variables in capture lists in outer scope.
const auto& mesh_idx_l = mesh_idx;
const auto& mesh_l = *mesh;
// ^^^ Remove when fixed (and rename accordingly in the below parallel-for).
cura::parallel_for<coord_t>(
0,
LayerIndex(layer_outlines_[mesh_to_layeroutline_idx[mesh_idx_l]].second.size()),
[&](const LayerIndex layer_idx)
{
if (mesh_l.layer_nr_max_filled_layer < layer_idx)
{
return; // Can't break as parallel_for wont allow it, this is equivalent to a continue.
}
Shape outline = extractOutlineFromMesh(mesh_l, layer_idx);
layer_outlines_[mesh_to_layeroutline_idx[mesh_idx_l]].second[layer_idx].push_back(outline);
});
}
// Merge all the layer outlines together.
for (auto& layer_outline : layer_outlines_)
{
cura::parallel_for<coord_t>(
0,
LayerIndex(anti_overhang_.size()),
[&](const LayerIndex layer_idx)
{
layer_outline.second[layer_idx] = layer_outline.second[layer_idx].unionPolygons();
});
}
// Gather all excluded areas, like support-blockers and trees that where already generated.
cura::parallel_for<coord_t>(
0,
LayerIndex(anti_overhang_.size()),
[&](const LayerIndex layer_idx)
{
if (layer_idx < coord_t(additional_excluded_areas.size()))
{
anti_overhang_[layer_idx].push_back(additional_excluded_areas[layer_idx]);
}
if (SUPPORT_TREE_AVOID_SUPPORT_BLOCKER)
{
anti_overhang_[layer_idx].push_back(storage.support.supportLayers[layer_idx].anti_overhang);
}
if (storage.prime_tower_)
{
anti_overhang_[layer_idx].push_back(storage.prime_tower_->getOccupiedOutline(layer_idx));
}
anti_overhang_[layer_idx] = anti_overhang_[layer_idx].unionPolygons();
});
for (max_layer_idx_without_blocker_ = 0; max_layer_idx_without_blocker_ + 1 < anti_overhang_.size(); max_layer_idx_without_blocker_++)
{
if (! anti_overhang_[max_layer_idx_without_blocker_ + 1].empty())
{
break;
}
}
// Cache some handy settings in the object itself.
radius_0_ = config.getRadius(0);
support_rest_preference_ = config.support_rest_preference;
simplifier_ = Simplify(min_maximum_resolution, min_maximum_deviation, min_maximum_area_deviation);
}
void TreeModelVolumes::precalculate(coord_t max_layer)
{
const auto t_start = std::chrono::high_resolution_clock::now();
precalculated_ = true;
// Get the config corresponding to one mesh that is in the current group. Which one has to be irrelevant.
// Not the prettiest way to do this, but it ensures some calculations that may be a bit more complex like initial layer diameter are only done in once.
const TreeSupportSettings config(layer_outlines_[current_outline_idx_].first);
// Calculate which radius each layer in the tip may have.
std::unordered_set<coord_t> possible_tip_radiis;
for (const auto dtt : ranges::views::iota(0UL, config.tip_layers + 1))
{
possible_tip_radiis.emplace(ceilRadius(config.getRadius(dtt)));
possible_tip_radiis.emplace(ceilRadius(config.getRadius(dtt) + current_min_xy_dist_delta_));
}
// It theoretically may happen in the tip, that the radius can change so much in-between 2 layers, that a ceil step is skipped (as in there is a radius r so that
// ceilRadius(radius(dtt))<ceilRadius(r)<ceilRadius(radius(dtt+1))). As such a radius will not reasonable happen in the tree and it will most likely not be requested, there is
// no need to calculate them. So just skip these.
for (coord_t radius_eval = ceilRadius(1); radius_eval <= config.branch_radius; radius_eval = ceilRadius(radius_eval + 1))
{
if (! possible_tip_radiis.count(radius_eval))
{
ignorable_radii_.emplace(radius_eval);
}
}
// Since we possibly have a required max/min size branches can be on the build-plate, and also of course a restricted rate at wich a radius normally is altered,
// (also) pre-calculate the restriction(s) on the radius at each layer which maximum these restrictions impose.
// It may seem that the required avoidance can be of a smaller radius when going to model (no initial layer diameter for to model branches)
// but as for every branch going towards the bp, the to model avoidance is required to check for possible merges with to model branches, this assumption is in-fact wrong.
std::unordered_map<coord_t, LayerIndex> radius_until_layer;
// while it is possible to calculate, up to which layer the avoidance should be calculated, this simulation is easier to understand, and does not need to be adjusted if
// something of the radius calculation is changed. Tested overhead was neligable (milliseconds for thounds of layers).
for (LayerIndex simulated_dtt = 0; simulated_dtt <= max_layer; simulated_dtt++)
{
const LayerIndex current_layer = max_layer - simulated_dtt;
const coord_t max_regular_radius = ceilRadius(config.getRadius(simulated_dtt, 0) + current_min_xy_dist_delta_);
const coord_t max_min_radius = ceilRadius(config.getRadius(simulated_dtt, 0)); // the maximal radius that the radius with the min_xy_dist can achieve
const coord_t max_initial_layer_diameter_radius = ceilRadius(config.recommendedMinRadius(current_layer) + current_min_xy_dist_delta_);
if (! radius_until_layer.count(max_regular_radius))
{
radius_until_layer[max_regular_radius] = current_layer;
}
if (! radius_until_layer.count(max_min_radius))
{
radius_until_layer[max_min_radius] = current_layer;
}
if (! radius_until_layer.count(max_initial_layer_diameter_radius))
{
radius_until_layer[max_initial_layer_diameter_radius] = current_layer;
}
}
// Copy these deques, as the methods we provide them to will loop over them using parallel-for.
// NOTE: While it might seem that one of these could be removed, they are here in case the parallel loop becomes no-wait.
std::deque<RadiusLayerPair> relevant_avoidance_radiis;
std::deque<RadiusLayerPair> relevant_avoidance_radiis_to_model;
relevant_avoidance_radiis.insert(relevant_avoidance_radiis.end(), radius_until_layer.begin(), radius_until_layer.end());
relevant_avoidance_radiis_to_model.insert(relevant_avoidance_radiis_to_model.end(), radius_until_layer.begin(), radius_until_layer.end());
// Append additional radiis needed for collision.
radius_until_layer[ceilRadius(increase_until_radius_, false)]
= max_layer; // To calculate collision holefree for every radius, the collision of radius increase_until_radius will be required.
// Collision for radius 0 needs to be calculated everywhere, as it will be used to ensure valid xy_distance in drawAreas.
radius_until_layer[0] = max_layer;
if (current_min_xy_dist_delta_ != 0)
{
radius_until_layer[current_min_xy_dist_delta_] = max_layer;
}
std::deque<RadiusLayerPair> relevant_collision_radiis;
relevant_collision_radiis.insert(
relevant_collision_radiis.end(),
radius_until_layer.begin(),
radius_until_layer.end()); // Now that required_avoidance_limit contains the maximum of old and regular required radius just copy.
// ### Calculate the relevant collisions
calculateCollision(relevant_collision_radiis);
// Calculate a separate Collisions with all holes removed. These are relevant for some avoidances that try to avoid holes (called safe).
std::deque<RadiusLayerPair> relevant_hole_collision_radiis;
for (RadiusLayerPair key : relevant_avoidance_radiis)
{
spdlog::debug("Calculating avoidance of radius {} up to layer {}", key.first, key.second);
if (key.first < increase_until_radius_ + current_min_xy_dist_delta_)
{
relevant_hole_collision_radiis.emplace_back(key);
}
}
// ### Calculate collisions without holes, build from regular collision
calculateCollisionHolefree(relevant_hole_collision_radiis);
const auto t_coll = std::chrono::high_resolution_clock::now();
auto t_acc = std::chrono::high_resolution_clock::now();
if (max_layer_idx_without_blocker_ < max_layer && support_rests_on_model_)
{
calculateAccumulatedPlaceable0(max_layer);
t_acc = std::chrono::high_resolution_clock::now();
}
// ### Calculate the relevant avoidances in parallel as far as possible
{
std::future<void> placeable_waiter;
std::future<void> avoidance_waiter;
if (support_rests_on_model_)
{
calculatePlaceables(relevant_avoidance_radiis_to_model);
}
if (support_rest_preference_ == RestPreference::BUILDPLATE)
{
calculateAvoidance(relevant_avoidance_radiis);
}
calculateWallRestrictions(relevant_avoidance_radiis);
if (support_rests_on_model_)
{
// FIXME: When nowait (parellel-for) is implemented, ensure here the following is calculated: calculatePlaceables.
calculateAvoidanceToModel(relevant_avoidance_radiis_to_model);
// FIXME: When nowait (parellel-for) is implemented, ensure here the following is calculated: calculateAvoidanceToModel.
}
if (support_rest_preference_ == RestPreference::BUILDPLATE)
{
// FIXME: When nowait (parellel-for) is implemented, ensure here the following is calculated: calculateAvoidance.
}
// FIXME: When nowait (parellel-for) is implemented, ensure here the following is calculated: calculateWallRestrictions.
}
const auto t_avo = std::chrono::high_resolution_clock::now();
auto t_colAvo = std::chrono::high_resolution_clock::now();
if (max_layer_idx_without_blocker_ < max_layer && support_rests_on_model_)
{
// FIXME: When nowait (parellel-for) is implemented, ensure here the following is calculated: calculateAccumulatedPlaceable0.
calculateCollisionAvoidance(relevant_avoidance_radiis);
t_colAvo = std::chrono::high_resolution_clock::now();
}
precalculation_finished_ = true;
const auto dur_col = 0.001 * std::chrono::duration_cast<std::chrono::microseconds>(t_coll - t_start).count();
const auto dur_acc = 0.001 * std::chrono::duration_cast<std::chrono::microseconds>(t_acc - t_coll).count();
const auto dur_avo = 0.001 * std::chrono::duration_cast<std::chrono::microseconds>(t_avo - t_acc).count();
const auto dur_col_avo = 0.001 * std::chrono::duration_cast<std::chrono::microseconds>(t_colAvo - t_avo).count();
spdlog::info(
"Pre-calculating collision took {} ms. Pre-calculating avoidance took {} ms. Pre-calculating accumulated Placeables with radius 0 took {} ms. Pre-calculating "
"collision-avoidance took {} ms. ",
dur_col,
dur_avo,
dur_acc,
dur_col_avo);
}
const Shape& TreeModelVolumes::getCollision(coord_t radius, LayerIndex layer_idx, bool min_xy_dist)
{
const coord_t orig_radius = radius;
std::optional<std::reference_wrapper<const Shape>> result;
if (! min_xy_dist)
{
radius += current_min_xy_dist_delta_;
}
// special case as if a radius 0 is requested it could be to ensure correct xy distance. As such it is beneficial if the collision is as close to the configured values as
// possible.
if (orig_radius != 0)
{
radius = ceilRadius(radius);
}
RadiusLayerPair key{ radius, layer_idx };
{
std::lock_guard<std::mutex> critical_section_support_max_layer_nr(*critical_avoidance_cache_);
result = getArea(collision_cache_, key);
}
if (result)
{
return result.value().get();
}
if (precalculated_)
{
spdlog::warn("Had to calculate collision at radius {} and layer {}, but precalculate was called. Performance may suffer!", key.first, key.second);
}
calculateCollision(key);
return getCollision(orig_radius, layer_idx, min_xy_dist);
}
const Shape& TreeModelVolumes::getCollisionHolefree(coord_t radius, LayerIndex layer_idx, bool min_xy_dist)
{
const coord_t orig_radius = radius;
std::optional<std::reference_wrapper<const Shape>> result;
if (! min_xy_dist)
{
radius += current_min_xy_dist_delta_;
}
if (radius >= increase_until_radius_ + current_min_xy_dist_delta_)
{
return getCollision(orig_radius, layer_idx, min_xy_dist);
}
RadiusLayerPair key{ radius, layer_idx };
{
std::lock_guard<std::mutex> critical_section_support_max_layer_nr(*critical_collision_cache_holefree_);
result = getArea(collision_cache_holefree_, key);
}
if (result)
{
return result.value().get();
}
if (precalculated_)
{
spdlog::warn("Had to calculate collision holefree at radius {} and layer {}, but precalculate was called. Performance may suffer!", key.first, key.second);
}
calculateCollisionHolefree(key);
return getCollisionHolefree(orig_radius, layer_idx, min_xy_dist);
}
const Shape& TreeModelVolumes::getAccumulatedPlaceable0(LayerIndex layer_idx)
{
{
std::lock_guard<std::mutex> critical_section_support_max_layer_nr(*critical_accumulated_placeables_cache_radius_0_);
if (accumulated_placeables_cache_radius_0_.count(layer_idx))
{
return accumulated_placeables_cache_radius_0_[layer_idx];
}
}
calculateAccumulatedPlaceable0(layer_idx);
return getAccumulatedPlaceable0(layer_idx);
}
const Shape& TreeModelVolumes::getAvoidance(coord_t radius, LayerIndex layer_idx, AvoidanceType type, bool to_model, bool min_xy_dist)
{
if (layer_idx == 0) // What on the layer directly above buildplate do i have to avoid to reach the buildplate ...
{
return getCollision(radius, layer_idx, min_xy_dist);
}
const coord_t orig_radius = radius;
std::optional<std::reference_wrapper<const Shape>> result;
radius += (min_xy_dist ? 0 : current_min_xy_dist_delta_);
radius = ceilRadius(radius);
if (radius >= increase_until_radius_ + current_min_xy_dist_delta_ && type == AvoidanceType::FAST_SAFE) // no holes anymore by definition at this request
{
type = AvoidanceType::FAST;
}
const RadiusLayerPair key{ radius, layer_idx };
std::unordered_map<RadiusLayerPair, Shape>* cache_ptr = nullptr;
std::mutex* mutex_ptr = nullptr;
switch (type)
{
case AvoidanceType::FAST:
cache_ptr = to_model ? &avoidance_cache_to_model_ : &avoidance_cache_;
mutex_ptr = to_model ? critical_avoidance_cache_to_model_.get() : critical_avoidance_cache_.get();
break;
case AvoidanceType::SLOW:
cache_ptr = to_model ? &avoidance_cache_to_model_slow_ : &avoidance_cache_slow_;
mutex_ptr = to_model ? critical_avoidance_cache_to_model_slow_.get() : critical_avoidance_cache_slow_.get();
break;
case AvoidanceType::FAST_SAFE:
cache_ptr = to_model ? &avoidance_cache_hole_to_model_ : &avoidance_cache_hole_;
mutex_ptr = to_model ? critical_avoidance_cache_holefree_to_model_.get() : critical_avoidance_cache_holefree_.get();
break;
case AvoidanceType::COLLISION:
if (layer_idx <= max_layer_idx_without_blocker_)
{
return getCollision(radius, layer_idx, true);
}
else
{
cache_ptr = &avoidance_cache_collision_;
mutex_ptr = critical_avoidance_cache_collision_.get();
}
break;
default:
spdlog::error("Invalid Avoidance Request");
break;
}
{
std::lock_guard<std::mutex> critical_section(*mutex_ptr);
result = getArea(*cache_ptr, key);
}
if (result)
{
return result.value().get();
}
if (precalculated_)
{
spdlog::warn(
"Had to calculate Avoidance (to model-bool: {}) at radius {} and layer {} and type {}, but precalculate was called. Performance may suffer!",
to_model,
key.first,
key.second,
coord_t(type));
}
if (type == AvoidanceType::COLLISION)
{
calculateCollisionAvoidance(key);
}
else if (to_model)
{
calculateAvoidanceToModel(key);
}
else
{
calculateAvoidance(key);
}
return getAvoidance(orig_radius, layer_idx, type, to_model, min_xy_dist); // retrive failed and correct result was calculated. Now it has to be retrived.
}
const Shape& TreeModelVolumes::getPlaceableAreas(coord_t radius, LayerIndex layer_idx)
{
std::optional<std::reference_wrapper<const Shape>> result;
const coord_t orig_radius = radius;
radius = ceilRadius(radius);
RadiusLayerPair key{ radius, layer_idx };
{
std::lock_guard<std::mutex> critical_section(*critical_placeable_areas_cache_);
result = getArea(placeable_areas_cache_, key);
}
if (result)
{
return result.value().get();
}
if (precalculated_)
{
spdlog::warn("Had to calculate Placeable Areas at radius {} and layer {}, but precalculate was called. Performance may suffer!", radius, layer_idx);
}
if (radius != 0)
{
calculatePlaceables(key);
}
else
{
getCollision(0, layer_idx, true);
}
return getPlaceableAreas(orig_radius, layer_idx);
}
const Shape& TreeModelVolumes::getWallRestriction(coord_t radius, LayerIndex layer_idx, bool min_xy_dist)
{
if (layer_idx == 0) // Should never be requested as there will be no going below layer 0 ..., but just to be sure some semi-sane catch. Alternative would be empty Polygon.
{
return getCollision(radius, layer_idx, min_xy_dist);
}
const coord_t orig_radius = radius;
min_xy_dist = min_xy_dist && current_min_xy_dist_delta_ > 0;
std::optional<std::reference_wrapper<const Shape>> result;
radius = ceilRadius(radius);
const RadiusLayerPair key{ radius, layer_idx };
std::unordered_map<RadiusLayerPair, Shape>* cache_ptr = min_xy_dist ? &wall_restrictions_cache_min_ : &wall_restrictions_cache_;
{
std::lock_guard<std::mutex> critical_section(min_xy_dist ? *critical_wall_restrictions_cache_min_ : *critical_wall_restrictions_cache_);
result = getArea(*cache_ptr, key);
}
if (result)
{
return result.value().get();
}
if (precalculated_)
{
spdlog::warn("Had to calculate Wall restrictions at radius {} and layer {}, but precalculate was called. Performance may suffer!", key.first, key.second);
}
calculateWallRestrictions(key);
return getWallRestriction(orig_radius, layer_idx, min_xy_dist); // Retrieve failed and correct result was calculated. Now it has to be retrieved.
}
coord_t TreeModelVolumes::ceilRadius(coord_t radius, bool min_xy_dist) const
{
return ceilRadius(radius + (min_xy_dist ? 0 : current_min_xy_dist_delta_));
}
coord_t TreeModelVolumes::getRadiusNextCeil(coord_t radius, bool min_xy_dist) const
{
return ceilRadius(radius, min_xy_dist) - (min_xy_dist ? 0 : current_min_xy_dist_delta_);
}
bool TreeModelVolumes::checkSettingsEquality(const Settings& me, const Settings& other) const
{
return TreeSupportSettings(me) == TreeSupportSettings(other);
}
Shape TreeModelVolumes::extractOutlineFromMesh(const SliceMeshStorage& mesh, LayerIndex layer_idx) const
{
// Similar to SliceDataStorage.getLayerOutlines but only for one mesh instead of for all of them.
constexpr bool external_polys_only = false;
Shape total;
if (mesh.settings.get<bool>("infill_mesh") || mesh.settings.get<bool>("anti_overhang_mesh"))
{
return Shape();
}
const SliceLayer& layer = mesh.layers[layer_idx];
layer.getOutlines(total, external_polys_only);
if (mesh.settings.get<ESurfaceMode>("magic_mesh_surface_mode") != ESurfaceMode::NORMAL)
{
total = total.unionPolygons(layer.open_polylines.offset(FUDGE_LENGTH * 2));
}
const coord_t maximum_resolution = mesh.settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t maximum_deviation = mesh.settings.get<coord_t>("meshfix_maximum_deviation");
const coord_t maximum_area_deviation = mesh.settings.get<coord_t>("meshfix_maximum_extrusion_area_deviation");
return Simplify(maximum_resolution, maximum_deviation, maximum_area_deviation).polygon(total);
}
LayerIndex TreeModelVolumes::getMaxCalculatedLayer(coord_t radius, const std::unordered_map<RadiusLayerPair, Shape>& map) const
{
LayerIndex max_layer = -1;
// the placeable on model areas do not exist on layer 0, as there can not be model below it. As such it may be possible that layer 1 is available, but layer 0 does not exist.
const RadiusLayerPair key_layer_1(radius, 1);
if (getArea(map, key_layer_1))
{
max_layer = 1;
}
while (map.count(RadiusLayerPair(radius, max_layer + 1)))
{
max_layer++;
}
return max_layer;
}
void TreeModelVolumes::calculateCollision(const std::deque<RadiusLayerPair>& keys)
{
cura::parallel_for<size_t>(
0,
keys.size(),
[&](const size_t i)
{
const coord_t radius = keys[i].first;
RadiusLayerPair key(radius, 0);
std::unordered_map<RadiusLayerPair, Shape> data_outer;
std::unordered_map<RadiusLayerPair, Shape> data_placeable_outer;
for (const auto outline_idx : ranges::views::iota(0UL, layer_outlines_.size()))
{
std::unordered_map<RadiusLayerPair, Shape> data;
std::unordered_map<RadiusLayerPair, Shape> data_placeable;
const coord_t layer_height = layer_outlines_[outline_idx].first.get<coord_t>("layer_height");
const bool support_rests_on_this_model = layer_outlines_[outline_idx].first.get<ESupportType>("support_type") == ESupportType::EVERYWHERE;
const coord_t z_distance_bottom = layer_outlines_[outline_idx].first.get<coord_t>("support_bottom_distance");
const size_t z_distance_bottom_layers = round_up_divide(z_distance_bottom, layer_height);
const coord_t z_distance_top_layers = round_up_divide(layer_outlines_[outline_idx].first.get<coord_t>("support_top_distance"), layer_height);
const LayerIndex max_anti_overhang_layer = anti_overhang_.size() - 1;
const LayerIndex max_required_layer = keys[i].second + std::max(coord_t(1), z_distance_top_layers);
const coord_t xy_distance = outline_idx == current_outline_idx_ ? current_min_xy_dist_ : layer_outlines_[outline_idx].first.get<coord_t>("support_xy_distance");
// Technically this causes collision for the normal xy_distance to be larger by current_min_xy_dist_delta for all not currently processing meshes as this delta will
// be added at request time. Avoiding this would require saving each collision for each outline_idx separately,
// and later for each avoidance... But avoidance calculation has to be for the whole scene and can NOT be done for each outline_idx separately and combined later.
// So avoiding this inaccuracy seems infeasible as it would require 2x the avoidance calculations => 0.5x the performance.
coord_t min_layer_bottom;
{
std::lock_guard<std::mutex> critical_section(*critical_collision_cache_);
min_layer_bottom = getMaxCalculatedLayer(radius, collision_cache_) - z_distance_bottom_layers;
}
if (min_layer_bottom < 0)
{
min_layer_bottom = 0;
}
for (const auto layer_idx : ranges::views::iota(min_layer_bottom, max_required_layer + 1))
{
key.second = layer_idx;
Shape collision_areas = machine_border_;
if (size_t(layer_idx) < layer_outlines_[outline_idx].second.size())
{
collision_areas.push_back(layer_outlines_[outline_idx].second[layer_idx]);
}
collision_areas = collision_areas.offset(
radius
+ xy_distance); // jtRound is not needed here, as the overshoot can not cause errors in the algorithm, because no assumptions are made about the model.
data[key].push_back(collision_areas); // if a key does not exist when it is accessed it is added!
}
// Add layers below, to ensure correct support_bottom_distance. Also save placeable areas of radius 0, if required for this mesh.
for (const auto layer_idx : ranges::views::iota(min_layer_bottom, max_required_layer + 1) | ranges::views::reverse)
{
key.second = layer_idx;
for (size_t layer_offset = 1; layer_offset <= z_distance_bottom_layers && layer_idx - coord_t(layer_offset) > min_layer_bottom; layer_offset++)
{
data[key].push_back(data[RadiusLayerPair(radius, layer_idx - layer_offset)]);
}
// Placeable areas also have to be calculated when a collision has to be calculated if called outside of precalculate to prevent an infinite loop when they are
// invalidly requested...
if ((support_rests_on_this_model || precalculation_finished_ || ! precalculated_) && radius == 0 && layer_idx < coord_t(1 + keys[i].second))
{
data[key] = data[key].unionPolygons();
Shape above = data[RadiusLayerPair(radius, layer_idx + 1)];
above = above.unionPolygons(max_anti_overhang_layer >= layer_idx + 1 ? anti_overhang_[layer_idx] : Shape());
// Empty polygons on condition: Just to be sure the area is correctly unioned as otherwise difference may behave unexpectedly.
Shape placeable = data[key].unionPolygons().difference(above);
data_placeable[RadiusLayerPair(radius, layer_idx + 1)] = data_placeable[RadiusLayerPair(radius, layer_idx + 1)].unionPolygons(placeable);
}
}
// Add collision layers above to ensure correct support_top_distance.
for (const auto layer_idx : ranges::views::iota(min_layer_bottom, max_required_layer + 1))
{
key.second = layer_idx;
for (coord_t layer_offset = 1; layer_offset <= z_distance_top_layers
&& layer_offset + layer_idx < std::min(coord_t(layer_outlines_[outline_idx].second.size()), coord_t(max_required_layer + 1));
layer_offset++)
{
// If just the collision (including the xy distance) of the layers above is accumulated, it leads to the following issue:
// Example: assuming the z distance is 2 layer
// + = xy_distance
// - = model
// o = overhang of the area two layers above that should result in tips on this layer
//
// +-----+
// +-----+
// +-----+
// o +-----+
// If just the collision above is accumulated the overhang will get overwritten by the xy_distance of the layer below the overhang...
//
// This only causes issues if the overhang area is thinner than xy_distance
// Just accumulating areas of the model above without the xy distance is also problematic, as then support may get closer to the model (on the diagonal
// downwards) than the user intended. Example (s = support):
// +-----+
// +-----+
// +-----+
// s+-----+
// Technically the calculation below is off by one layer, as the actual distance between plastic one layer down is 0 not layer height, as this layer is
// filled with said plastic. But otherwise a part of the overhang that is expected to be supported is overwritten by the remaining part of the xy distance
// of the layer below the to be supported area.
const coord_t required_range_x = coord_t(xy_distance - ((layer_offset - (z_distance_top_layers == 1 ? 0.5 : 0)) * xy_distance / z_distance_top_layers));
// ^^^ The conditional -0.5 ensures that plastic can never touch on the diagonal downward when the z_distance_top_layers = 1.
// It is assumed to be better to not support an overhang<90� than to risk fusing to it.
data[key].push_back(layer_outlines_[outline_idx].second[layer_idx + layer_offset].offset(radius + required_range_x));
}
data[key] = data[key].unionPolygons(max_anti_overhang_layer >= layer_idx ? anti_overhang_[layer_idx].offset(radius) : Shape());
}
for (const auto layer_idx : ranges::views::iota(static_cast<size_t>(keys[i].second) + 1UL, max_required_layer + 1UL) | ranges::views::reverse)
{
data.erase(RadiusLayerPair(radius, layer_idx)); // all these dont have the correct z_distance_top_layers as they can still have areas above them
}
for (auto pair : data)
{
pair.second = simplifier_.polygon(pair.second);
data_outer[pair.first] = data_outer[pair.first].unionPolygons(pair.second);
}
if (radius == 0)
{
for (auto pair : data_placeable)
{
pair.second = simplifier_.polygon(pair.second);
data_placeable_outer[pair.first] = data_placeable_outer[pair.first].unionPolygons(pair.second);
}
}
}
{
std::lock_guard<std::mutex> critical_section(*critical_progress_);
if (precalculated_ && precalculation_progress_ < TREE_PROGRESS_PRECALC_COLL)
{
precalculation_progress_ += TREE_PROGRESS_PRECALC_COLL / keys.size();
Progress::messageProgress(Progress::Stage::SUPPORT, precalculation_progress_ * progress_multiplier_ + progress_offset_, TREE_PROGRESS_TOTAL);
}
}
{
std::lock_guard<std::mutex> critical_section(*critical_collision_cache_);
collision_cache_.insert(data_outer.begin(), data_outer.end());
}
if (radius == 0)
{
{
std::lock_guard<std::mutex> critical_section(*critical_placeable_areas_cache_);
placeable_areas_cache_.insert(data_placeable_outer.begin(), data_placeable_outer.end());
}
}
});
}
void TreeModelVolumes::calculateCollisionHolefree(const std::deque<RadiusLayerPair>& keys)
{
LayerIndex max_layer = 0;
for (long long unsigned int i = 0; i < keys.size(); i++)
{
max_layer = std::max(max_layer, keys[i].second);
}
cura::parallel_for<coord_t>(
0,
LayerIndex(max_layer + 1),
[&](const LayerIndex layer_idx)
{
std::unordered_map<RadiusLayerPair, Shape> data;
for (RadiusLayerPair key : keys)
{
// Logically increase the collision by increase_until_radius
const coord_t radius = key.first;
const coord_t increase_radius_ceil = ceilRadius(increase_until_radius_, false) - ceilRadius(radius, true);
Shape col = getCollision(increase_until_radius_, layer_idx, false).offset(EPSILON - increase_radius_ceil, ClipperLib::jtRound).unionPolygons();
// ^^^ That last 'unionPolygons' is important as otherwise holes(in form of lines that will increase to holes in a later step) can get unioned onto the area.
col = simplifier_.polygon(col);
data[RadiusLayerPair(radius, layer_idx)] = col;
}
{
std::lock_guard<std::mutex> critical_section(*critical_collision_cache_holefree_);
collision_cache_holefree_.insert(data.begin(), data.end());
}
});
}
void TreeModelVolumes::calculateAccumulatedPlaceable0(const LayerIndex max_layer)
{
LayerIndex start_layer = -1;
// the placeable on model areas do not exist on layer 0, as there can not be model below it. As such it may be possible that layer 1 is available, but layer 0 does not exist.
{
std::lock_guard<std::mutex> critical_section(*critical_accumulated_placeables_cache_radius_0_);
while (accumulated_placeables_cache_radius_0_.count(start_layer + 1))
{
start_layer++;
}
start_layer = std::max(LayerIndex{ start_layer + 1 }, LayerIndex{ 1 });
}
if (start_layer > max_layer)
{
spdlog::debug("Requested calculation for value already calculated ?");
return;
}
Shape accumulated_placeable_0
= start_layer == 1 ? machine_area_ : getAccumulatedPlaceable0(start_layer - 1).offset(FUDGE_LENGTH + (current_min_xy_dist_ + current_min_xy_dist_delta_));
// ^^^ The calculation here is done on the areas that are increased by xy_distance, but the result is saved without xy_distance,
// so here it "restores" the previous state to continue calculating from about where it ended.
// It would be better to ensure placeable areas of radius 0 do not include the xy distance, and removing the code compensating for it here and in calculatePlaceables.
std::vector<std::pair<LayerIndex, Shape>> data(max_layer + 1, std::pair<LayerIndex, Shape>(-1, Shape()));
for (LayerIndex layer = start_layer; layer <= max_layer; layer++)
{
accumulated_placeable_0 = accumulated_placeable_0.unionPolygons(getPlaceableAreas(0, layer).offset(FUDGE_LENGTH)).difference(anti_overhang_[layer]);
std::lock_guard<std::mutex> critical_section(*critical_accumulated_placeables_cache_radius_0_);
accumulated_placeable_0 = simplifier_.polygon(accumulated_placeable_0);
data[layer] = std::pair(layer, accumulated_placeable_0);
}
cura::parallel_for<size_t>(
std::max(LayerIndex{ start_layer - 1 }, LayerIndex{ 1 }),
data.size(),
[&](const coord_t layer_idx)
{
data[layer_idx].second = data[layer_idx].second.offset(-(current_min_xy_dist_ + current_min_xy_dist_delta_));
});
{
std::lock_guard<std::mutex> critical_section(*critical_accumulated_placeables_cache_radius_0_);
accumulated_placeables_cache_radius_0_.insert(data.begin(), data.end());
}
}
void TreeModelVolumes::calculateCollisionAvoidance(const std::deque<RadiusLayerPair>& keys)
{
cura::parallel_for<size_t>(
0,
keys.size(),
[&, keys](const size_t key_idx)
{
const coord_t radius = keys[key_idx].first;
const LayerIndex max_required_layer = keys[key_idx].second;
const coord_t max_step_move = std::max(1.9 * radius, current_min_xy_dist_ * 1.9);
LayerIndex start_layer = 0;
{
std::lock_guard<std::mutex> critical_section(*critical_avoidance_cache_collision_);
start_layer = 1 + std::max(getMaxCalculatedLayer(radius, avoidance_cache_collision_), max_layer_idx_without_blocker_);
}
if (start_layer > max_required_layer)
{
return;
}
std::vector<std::pair<RadiusLayerPair, Shape>> data(max_required_layer + 1, std::pair<RadiusLayerPair, Shape>(RadiusLayerPair(radius, -1), Shape()));
RadiusLayerPair key(radius, 0);
Shape latest_avoidance = getAvoidance(radius, start_layer - 1, AvoidanceType::COLLISION, true, true);
for (const LayerIndex layer : ranges::views::iota(static_cast<size_t>(start_layer), max_required_layer + 1UL))
{
key.second = layer;
Shape col = getCollision(radius, layer, true);
latest_avoidance = safeOffset(latest_avoidance, -max_move_, ClipperLib::jtRound, -max_step_move, col);
Shape placeable0RadiusCompensated = getAccumulatedPlaceable0(layer).offset(-std::max(radius, increase_until_radius_), ClipperLib::jtRound);
latest_avoidance = latest_avoidance.difference(placeable0RadiusCompensated).unionPolygons(getCollision(radius, layer, true));
Shape next_latest_avoidance = simplifier_.polygon(latest_avoidance);
latest_avoidance = next_latest_avoidance.unionPolygons(latest_avoidance);
// ^^^ Ensure the simplification only causes the avoidance to become larger.
// If the deviation of the simplification causes the avoidance to become smaller than it should be it can cause issues, if it is larger the worst case is that the
// xy distance is effectively increased by deviation. If there would be an option to ensure the resulting polygon only gets larger by simplifying, it should improve
// performance further.
data[layer] = std::pair<RadiusLayerPair, Shape>(key, latest_avoidance);
}
{
std::lock_guard<std::mutex> critical_section(*critical_avoidance_cache_collision_);
avoidance_cache_collision_.insert(data.begin(), data.end());
}
});
}
// Ensures offsets are only done in sizes with a max step size per offset while adding the collision offset after each step, this ensures that areas cannot glitch through walls
// defined by the collision when offsetting to fast.
Shape TreeModelVolumes::safeOffset(const Shape& me, coord_t distance, ClipperLib::JoinType jt, coord_t max_safe_step_distance, const Shape& collision) const
{
assert(distance * max_safe_step_distance >= 0); // Make sure they are the same sign (or one of them is null)
const uint8_t offset_sign = sign(distance);
const coord_t step_distance = offset_sign * std::max(min_offset_per_step_, std::abs(max_safe_step_distance));
const size_t steps = std::abs(distance / step_distance);
Shape ret = me;
for (size_t i = 0; i < steps; ++i)
{
ret = ret.offset(step_distance, jt).unionPolygons(collision);
}
ret = ret.offset(distance % step_distance, jt);
return ret.unionPolygons(collision);
}
void TreeModelVolumes::calculateAvoidance(const std::deque<RadiusLayerPair>& keys)
{
// For every RadiusLayer pair there are 3 avoidances that have to be calculate, calculated in the same paralell_for loop for better parallelization.
const std::vector<AvoidanceType> all_types = { AvoidanceType::SLOW, AvoidanceType::FAST_SAFE, AvoidanceType::FAST };
// TODO: This should be a parallel for nowait (non-blocking), but as the parallel-for situation (as in, proper compiler support) continues to change, we're using the 'normal'
// one right now.
cura::parallel_for<size_t>(
0,
keys.size() * 3,
[&, keys, all_types](const size_t iter_idx)
{
const size_t key_idx = iter_idx / 3;
const size_t type_idx = iter_idx % all_types.size();
const AvoidanceType type = all_types[type_idx];
const bool slow = type == AvoidanceType::SLOW;
const bool holefree = type == AvoidanceType::FAST_SAFE;
const coord_t radius = keys[key_idx].first;
const LayerIndex max_required_layer = keys[key_idx].second;
// do not calculate not needed safe avoidances
if (holefree && radius >= increase_until_radius_ + current_min_xy_dist_delta_)
{
return;
}
const coord_t offset_speed = slow ? max_move_slow_ : max_move_;
const coord_t max_step_move = std::max(1.9 * radius, current_min_xy_dist_ * 1.9);
RadiusLayerPair key(radius, 0);
Shape latest_avoidance;
LayerIndex start_layer;
{
std::lock_guard<std::mutex> critical_section(*(slow ? critical_avoidance_cache_slow_ : holefree ? critical_avoidance_cache_holefree_ : critical_avoidance_cache_));
start_layer = 1 + getMaxCalculatedLayer(radius, slow ? avoidance_cache_slow_ : holefree ? avoidance_cache_hole_ : avoidance_cache_);
}
if (start_layer > max_required_layer)
{
spdlog::debug("Requested calculation for value already calculated ?");
return;
}
start_layer = std::max(start_layer, LayerIndex(1)); // Ensure StartLayer is at least 1 as if no avoidance was calculated getMaxCalculatedLayer returns -1
std::vector<std::pair<RadiusLayerPair, Shape>> data(max_required_layer + 1, std::pair<RadiusLayerPair, Shape>(RadiusLayerPair(radius, -1), Shape()));
latest_avoidance
= getAvoidance(radius, start_layer - 1, type, false, true); // minDist as the delta was already added, also avoidance for layer 0 will return the collision.
// ### main loop doing the calculation
for (const LayerIndex layer : ranges::views::iota(static_cast<size_t>(start_layer), max_required_layer + 1UL))
{
key.second = layer;
Shape col;
if ((slow && radius < increase_until_radius_ + current_min_xy_dist_delta_) || holefree)
{
col = getCollisionHolefree(radius, layer, true);
}
else
{
col = getCollision(radius, layer, true);
}
latest_avoidance = safeOffset(latest_avoidance, -offset_speed, ClipperLib::jtRound, -max_step_move, col);
Shape next_latest_avoidance = simplifier_.polygon(latest_avoidance);
latest_avoidance = next_latest_avoidance.unionPolygons(latest_avoidance);
// ^^^ Ensure the simplification only causes the avoidance to become larger.
// If the deviation of the simplification causes the avoidance to become smaller than it should be it can cause issues, if it is larger the worst case is that the
// xy distance is effectively increased by deviation. If there would be an option to ensure the resulting polygon only gets larger by simplifying, it should improve
// performance further.
data[layer] = std::pair<RadiusLayerPair, Shape>(key, latest_avoidance);
}
{
std::lock_guard<std::mutex> critical_section(*critical_progress_);
if (precalculated_ && precalculation_progress_ < TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_PRECALC_AVO)
{
precalculation_progress_ += support_rests_on_model_ ? 0.4 : 1 * TREE_PROGRESS_PRECALC_AVO / (keys.size() * 3);
Progress::messageProgress(Progress::Stage::SUPPORT, precalculation_progress_ * progress_multiplier_ + progress_offset_, TREE_PROGRESS_TOTAL);
}
}
{