forked from bambulab/BambuStudio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEdgeGrid.cpp
1632 lines (1559 loc) · 52.1 KB
/
EdgeGrid.cpp
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 <algorithm>
#include <vector>
#include <float.h>
#include <unordered_map>
#include <png.h>
#include "libslic3r.h"
#include "ClipperUtils.hpp"
#include "EdgeGrid.hpp"
#include "Geometry.hpp"
#include "SVG.hpp"
#include "PNGReadWrite.hpp"
// #define EDGE_GRID_DEBUG_OUTPUT
#if 0
// Enable debugging and assert in this file.
#define DEBUG
#define _DEBUG
#undef NDEBUG
#endif
#include <assert.h>
namespace Slic3r {
void EdgeGrid::Grid::create(const Polygons &polygons, coord_t resolution)
{
// Collect the contours.
m_contours.clear();
m_contours.reserve(std::count_if(polygons.begin(), polygons.end(), [](const Polygon &p) { return ! p.empty(); }));
for (const Polygon &polygon : polygons)
if (! polygon.empty())
m_contours.emplace_back(polygon.points, false);
create_from_m_contours(resolution);
}
void EdgeGrid::Grid::create(const std::vector<const Polygon*> &polygons, coord_t resolution)
{
// Collect the contours.
m_contours.clear();
m_contours.reserve(std::count_if(polygons.begin(), polygons.end(), [](const Polygon *p) { return ! p->empty(); }));
for (const Polygon *polygon : polygons)
if (! polygon->empty())
m_contours.emplace_back(polygon->points, false);
create_from_m_contours(resolution);
}
void EdgeGrid::Grid::create(const std::vector<Points> &polygons, coord_t resolution, bool open_polylines)
{
// Collect the contours.
m_contours.clear();
m_contours.reserve(std::count_if(polygons.begin(), polygons.end(), [](const Points &p) { return p.size() > 1; }));
for (const Points &points : polygons)
if (points.size() > 1) {
const Point *begin = points.data();
const Point *end = points.data() + points.size();
bool open = open_polylines;
if (open_polylines) {
if (*begin == end[-1]) {
open = false;
-- end;
}
} else
assert(*begin != end[-1]);
m_contours.emplace_back(begin, end, open);
}
create_from_m_contours(resolution);
}
void EdgeGrid::Grid::create(const Polygons &polygons, const Polylines &polylines, coord_t resolution)
{
// Collect the contours.
m_contours.clear();
m_contours.reserve(
std::count_if(polygons.begin(), polygons.end(), [](const Polygon &p) { return p.size() > 1; }) +
std::count_if(polylines.begin(), polylines.end(), [](const Polyline &p) { return p.size() > 1; }));
for (const Polyline &polyline : polylines)
if (polyline.size() > 1) {
const Point *begin = polyline.points.data();
const Point *end = polyline.points.data() + polyline.size();
bool open = true;
if (*begin == end[-1]) {
open = false;
-- end;
}
m_contours.emplace_back(begin, end, open);
}
for (const Polygon &polygon : polygons)
if (polygon.size() > 1)
m_contours.emplace_back(polygon.points, false);
create_from_m_contours(resolution);
}
void EdgeGrid::Grid::create(const ExPolygon &expoly, coord_t resolution)
{
m_contours.clear();
m_contours.reserve((expoly.contour.empty() ? 0 : 1) + std::count_if(expoly.holes.begin(), expoly.holes.end(), [](const Polygon &p) { return ! p.empty(); }));
if (! expoly.contour.empty())
m_contours.emplace_back(expoly.contour.points, false);
for (const Polygon &hole : expoly.holes)
if (! hole.empty())
m_contours.emplace_back(hole.points, false);
create_from_m_contours(resolution);
}
void EdgeGrid::Grid::create(const ExPolygons &expolygons, coord_t resolution)
{
// Count the contours.
size_t ncontours = 0;
for (const ExPolygon &expoly : expolygons) {
if (! expoly.contour.empty())
++ ncontours;
ncontours += std::count_if(expoly.holes.begin(), expoly.holes.end(), [](const Polygon &p) { return ! p.empty(); });
}
// Collect the contours.
m_contours.clear();
m_contours.reserve(ncontours);
for (const ExPolygon &expoly : expolygons) {
if (! expoly.contour.empty())
m_contours.emplace_back(expoly.contour.points, false);
for (const Polygon &hole : expoly.holes)
if (! hole.empty())
m_contours.emplace_back(hole.points, false);
}
create_from_m_contours(resolution);
}
// m_contours has been initialized. Now fill in the edge grid.
void EdgeGrid::Grid::create_from_m_contours(coord_t resolution)
{
assert(resolution > 0);
// 1) Measure the bounding box.
for (const Contour &contour : m_contours) {
assert(contour.num_segments() > 0);
assert(*contour.begin() != contour.end()[-1]);
for (const Slic3r::Point &pt : contour)
m_bbox.merge(pt);
}
coord_t eps = 16;
m_bbox.min(0) -= eps;
m_bbox.min(1) -= eps;
m_bbox.max(0) += eps;
m_bbox.max(1) += eps;
// 2) Initialize the edge grid.
m_resolution = resolution;
m_cols = (m_bbox.max(0) - m_bbox.min(0) + m_resolution - 1) / m_resolution;
m_rows = (m_bbox.max(1) - m_bbox.min(1) + m_resolution - 1) / m_resolution;
m_cells.assign(m_rows * m_cols, Cell());
// 3) First round of contour rasterization, count the edges per grid cell.
for (size_t i = 0; i < m_contours.size(); ++ i) {
const Contour &contour = m_contours[i];
for (size_t j = 0; j < contour.num_segments(); ++ j) {
// End points of the line segment.
Slic3r::Point p1(contour.segment_start(j));
Slic3r::Point p2(contour.segment_end(j));
p1(0) -= m_bbox.min(0);
p1(1) -= m_bbox.min(1);
p2(0) -= m_bbox.min(0);
p2(1) -= m_bbox.min(1);
// Get the cells of the end points.
coord_t ix = p1(0) / m_resolution;
coord_t iy = p1(1) / m_resolution;
coord_t ixb = p2(0) / m_resolution;
coord_t iyb = p2(1) / m_resolution;
assert(ix >= 0 && size_t(ix) < m_cols);
assert(iy >= 0 && size_t(iy) < m_rows);
assert(ixb >= 0 && size_t(ixb) < m_cols);
assert(iyb >= 0 && size_t(iyb) < m_rows);
// Account for the end points.
++ m_cells[iy*m_cols+ix].end;
if (ix == ixb && iy == iyb)
// Both ends fall into the same cell.
continue;
// Raster the centeral part of the line.
coord_t dx = std::abs(p2(0) - p1(0));
coord_t dy = std::abs(p2(1) - p1(1));
if (p1(0) < p2(0)) {
int64_t ex = int64_t((ix + 1)*m_resolution - p1(0)) * int64_t(dy);
if (p1(1) < p2(1)) {
// x positive, y positive
int64_t ey = int64_t((iy + 1)*m_resolution - p1(1)) * int64_t(dx);
do {
assert(ix <= ixb && iy <= iyb);
if (ex < ey) {
ey -= ex;
ex = int64_t(dy) * m_resolution;
ix += 1;
}
else if (ex == ey) {
ex = int64_t(dy) * m_resolution;
ey = int64_t(dx) * m_resolution;
ix += 1;
iy += 1;
}
else {
assert(ex > ey);
ex -= ey;
ey = int64_t(dx) * m_resolution;
iy += 1;
}
++m_cells[iy*m_cols + ix].end;
} while (ix != ixb || iy != iyb);
}
else {
// x positive, y non positive
int64_t ey = int64_t(p1(1) - iy*m_resolution) * int64_t(dx);
do {
assert(ix <= ixb && iy >= iyb);
if (ex <= ey) {
ey -= ex;
ex = int64_t(dy) * m_resolution;
ix += 1;
}
else {
ex -= ey;
ey = int64_t(dx) * m_resolution;
iy -= 1;
}
++m_cells[iy*m_cols + ix].end;
} while (ix != ixb || iy != iyb);
}
}
else {
int64_t ex = int64_t(p1(0) - ix*m_resolution) * int64_t(dy);
if (p1(1) < p2(1)) {
// x non positive, y positive
int64_t ey = int64_t((iy + 1)*m_resolution - p1(1)) * int64_t(dx);
do {
assert(ix >= ixb && iy <= iyb);
if (ex < ey) {
ey -= ex;
ex = int64_t(dy) * m_resolution;
ix -= 1;
}
else {
assert(ex >= ey);
ex -= ey;
ey = int64_t(dx) * m_resolution;
iy += 1;
}
++m_cells[iy*m_cols + ix].end;
} while (ix != ixb || iy != iyb);
}
else {
// x non positive, y non positive
int64_t ey = int64_t(p1(1) - iy*m_resolution) * int64_t(dx);
do {
assert(ix >= ixb && iy >= iyb);
if (ex < ey) {
ey -= ex;
ex = int64_t(dy) * m_resolution;
ix -= 1;
}
else if (ex == ey) {
// The lower edge of a grid cell belongs to the cell.
// Handle the case where the ray may cross the lower left corner of a cell in a general case,
// or a left or lower edge in a degenerate case (horizontal or vertical line).
if (dx > 0) {
ex = int64_t(dy) * m_resolution;
ix -= 1;
}
if (dy > 0) {
ey = int64_t(dx) * m_resolution;
iy -= 1;
}
}
else {
assert(ex > ey);
ex -= ey;
ey = int64_t(dx) * m_resolution;
iy -= 1;
}
++m_cells[iy*m_cols + ix].end;
} while (ix != ixb || iy != iyb);
}
}
}
}
// 4) Prefix sum the numbers of hits per cells to get an index into m_cell_data.
size_t cnt = m_cells.front().end;
for (size_t i = 1; i < m_cells.size(); ++ i) {
m_cells[i].begin = cnt;
cnt += m_cells[i].end;
m_cells[i].end = cnt;
}
// 5) Allocate the cell data.
m_cell_data.assign(cnt, std::pair<size_t, size_t>(size_t(-1), size_t(-1)));
// 6) Finally fill in m_cell_data by rasterizing the lines once again.
for (size_t i = 0; i < m_cells.size(); ++i)
m_cells[i].end = m_cells[i].begin;
struct Visitor {
Visitor(std::vector<std::pair<size_t, size_t>> &cell_data, std::vector<Cell> &cells, size_t cols) :
cell_data(cell_data), cells(cells), cols(cols), i(0), j(0) {}
inline bool operator()(coord_t iy, coord_t ix) {
cell_data[cells[iy*cols + ix].end++] = std::pair<size_t, size_t>(i, j);
// Continue traversing the grid along the edge.
return true;
}
std::vector<std::pair<size_t, size_t>> &cell_data;
std::vector<Cell> &cells;
size_t cols;
size_t i;
size_t j;
} visitor(m_cell_data, m_cells, m_cols);
assert(visitor.i == 0);
for (; visitor.i < m_contours.size(); ++ visitor.i) {
const Contour &contour = m_contours[visitor.i];
for (visitor.j = 0; visitor.j < contour.num_segments(); ++ visitor.j)
this->visit_cells_intersecting_line(contour.segment_start(visitor.j), contour.segment_end(visitor.j), visitor);
}
}
#if 0
// Divide, round to a grid coordinate.
// Divide x/y, round down. y is expected to be positive.
static inline coord_t div_floor(coord_t x, coord_t y)
{
assert(y > 0);
return ((x < 0) ? (x - y + 1) : x) / y;
}
// Walk the polyline, test whether any lines of this polyline does not intersect
// any line stored into the grid.
bool EdgeGrid::Grid::intersect(const MultiPoint &polyline, bool closed)
{
size_t n = polyline.points.size();
if (closed)
++ n;
for (size_t i = 0; i < n; ++ i) {
size_t j = i + 1;
if (j == polyline.points.size())
j = 0;
Point p1src = polyline.points[i];
Point p2src = polyline.points[j];
Point p1 = p1src;
Point p2 = p2src;
// Discretize the line segment p1, p2.
p1(0) -= m_bbox.min(0);
p1(1) -= m_bbox.min(1);
p2(0) -= m_bbox.min(0);
p2(1) -= m_bbox.min(1);
// Get the cells of the end points.
coord_t ix = div_floor(p1(0), m_resolution);
coord_t iy = div_floor(p1(1), m_resolution);
coord_t ixb = div_floor(p2(0), m_resolution);
coord_t iyb = div_floor(p2(1), m_resolution);
// assert(ix >= 0 && ix < m_cols);
// assert(iy >= 0 && iy < m_rows);
// assert(ixb >= 0 && ixb < m_cols);
// assert(iyb >= 0 && iyb < m_rows);
// Account for the end points.
if (line_cell_intersect(p1src, p2src, m_cells[iy*m_cols + ix]))
return true;
if (ix == ixb && iy == iyb)
// Both ends fall into the same cell.
continue;
// Raster the centeral part of the line.
coord_t dx = std::abs(p2(0) - p1(0));
coord_t dy = std::abs(p2(1) - p1(1));
if (p1(0) < p2(0)) {
int64_t ex = int64_t((ix + 1)*m_resolution - p1(0)) * int64_t(dy);
if (p1(1) < p2(1)) {
int64_t ey = int64_t((iy + 1)*m_resolution - p1(1)) * int64_t(dx);
do {
assert(ix <= ixb && iy <= iyb);
if (ex < ey) {
ey -= ex;
ex = int64_t(dy) * m_resolution;
ix += 1;
}
else if (ex == ey) {
ex = int64_t(dy) * m_resolution;
ey = int64_t(dx) * m_resolution;
ix += 1;
iy += 1;
}
else {
assert(ex > ey);
ex -= ey;
ey = int64_t(dx) * m_resolution;
iy += 1;
}
if (line_cell_intersect(p1src, p2src, m_cells[iy*m_cols + ix]))
return true;
} while (ix != ixb || iy != iyb);
}
else {
int64_t ey = int64_t(p1(1) - iy*m_resolution) * int64_t(dx);
do {
assert(ix <= ixb && iy >= iyb);
if (ex <= ey) {
ey -= ex;
ex = int64_t(dy) * m_resolution;
ix += 1;
}
else {
ex -= ey;
ey = int64_t(dx) * m_resolution;
iy -= 1;
}
if (line_cell_intersect(p1src, p2src, m_cells[iy*m_cols + ix]))
return true;
} while (ix != ixb || iy != iyb);
}
}
else {
int64_t ex = int64_t(p1(0) - ix*m_resolution) * int64_t(dy);
if (p1(1) < p2(1)) {
int64_t ey = int64_t((iy + 1)*m_resolution - p1(1)) * int64_t(dx);
do {
assert(ix >= ixb && iy <= iyb);
if (ex < ey) {
ey -= ex;
ex = int64_t(dy) * m_resolution;
ix -= 1;
}
else {
assert(ex >= ey);
ex -= ey;
ey = int64_t(dx) * m_resolution;
iy += 1;
}
if (line_cell_intersect(p1src, p2src, m_cells[iy*m_cols + ix]))
return true;
} while (ix != ixb || iy != iyb);
}
else {
int64_t ey = int64_t(p1(1) - iy*m_resolution) * int64_t(dx);
do {
assert(ix >= ixb && iy >= iyb);
if (ex < ey) {
ey -= ex;
ex = int64_t(dy) * m_resolution;
ix -= 1;
}
else if (ex == ey) {
if (dx > 0) {
ex = int64_t(dy) * m_resolution;
ix -= 1;
}
if (dy > 0) {
ey = int64_t(dx) * m_resolution;
iy -= 1;
}
}
else {
assert(ex > ey);
ex -= ey;
ey = int64_t(dx) * m_resolution;
iy -= 1;
}
if (line_cell_intersect(p1src, p2src, m_cells[iy*m_cols + ix]))
return true;
} while (ix != ixb || iy != iyb);
}
}
}
return false;
}
bool EdgeGrid::Grid::line_cell_intersect(const Point &p1a, const Point &p2a, const Cell &cell)
{
BoundingBox bbox(p1a, p1a);
bbox.merge(p2a);
int64_t va_x = p2a(0) - p1a(0);
int64_t va_y = p2a(1) - p1a(1);
for (size_t i = cell.begin; i != cell.end; ++ i) {
const std::pair<size_t, size_t> &cell_data = m_cell_data[i];
// Contour indexed by the ith line of this cell.
const Slic3r::Points &contour = *m_contours[cell_data.first];
// Point indices in contour indexed by the ith line of this cell.
size_t idx1 = cell_data.second;
size_t idx2 = idx1 + 1;
if (idx2 == contour.size())
idx2 = 0;
// The points of the ith line of this cell and its bounding box.
const Point &p1b = contour[idx1];
const Point &p2b = contour[idx2];
BoundingBox bbox2(p1b, p1b);
bbox2.merge(p2b);
// Do the bounding boxes intersect?
if (! bbox.overlap(bbox2))
continue;
// Now intersect the two line segments using exact arithmetics.
int64_t w1_x = p1b(0) - p1a(0);
int64_t w1_y = p1b(1) - p1a(1);
int64_t w2_x = p2b(0) - p1a(0);
int64_t w2_y = p2b(1) - p1a(1);
int64_t side1 = va_x * w1_y - va_y * w1_x;
int64_t side2 = va_x * w2_y - va_y * w2_x;
if (side1 == side2 && side1 != 0)
// The line segments don't intersect.
continue;
w1_x = p1a(0) - p1b(0);
w1_y = p1a(1) - p1b(1);
w2_x = p2a(0) - p1b(0);
w2_y = p2a(1) - p1b(1);
int64_t vb_x = p2b(0) - p1b(0);
int64_t vb_y = p2b(1) - p1b(1);
side1 = vb_x * w1_y - vb_y * w1_x;
side2 = vb_x * w2_y - vb_y * w2_x;
if (side1 == side2 && side1 != 0)
// The line segments don't intersect.
continue;
// The line segments intersect.
return true;
}
// The line segment (p1a, p2a) does not intersect any of the line segments inside this cell.
return false;
}
// Test, whether a point is inside a contour.
bool EdgeGrid::Grid::inside(const Point &pt_src)
{
Point p = pt_src;
p(0) -= m_bbox.min(0);
p(1) -= m_bbox.min(1);
// Get the cell of the point.
if (p(0) < 0 || p(1) < 0)
return false;
coord_t ix = p(0) / m_resolution;
coord_t iy = p(1) / m_resolution;
if (ix >= m_cols || iy >= m_rows)
return false;
size_t i_closest = (size_t)-1;
bool inside = false;
{
// Hit in the first cell?
const Cell &cell = m_cells[iy * m_cols + ix];
for (size_t i = cell.begin; i != cell.end; ++ i) {
const std::pair<size_t, size_t> &cell_data = m_cell_data[i];
// Contour indexed by the ith line of this cell.
const Slic3r::Points &contour = *m_contours[cell_data.first];
// Point indices in contour indexed by the ith line of this cell.
size_t idx1 = cell_data.second;
size_t idx2 = idx1 + 1;
if (idx2 == contour.size())
idx2 = 0;
const Point &p1 = contour[idx1];
const Point &p2 = contour[idx2];
if (p1(1) < p2(1)) {
if (p(1) < p1(1) || p(1) > p2(1))
continue;
//FIXME finish this!
int64_t vx = 0;// pt_src
//FIXME finish this!
int64_t det = 0;
} else if (p1(1) != p2(1)) {
assert(p1(1) > p2(1));
if (p(1) < p2(1) || p(1) > p1(1))
continue;
} else {
assert(p1(1) == p2(1));
if (p1(1) == p(1)) {
if (p(0) >= p1(0) && p(0) <= p2(0))
// On the segment.
return true;
// Before or after the segment.
size_t idx0 = idx1 - 1;
size_t idx2 = idx1 + 1;
if (idx0 == (size_t)-1)
idx0 = contour.size() - 1;
if (idx2 == contour.size())
idx2 = 0;
}
}
}
}
//FIXME This code follows only a single direction. Better to follow the direction closest to the bounding box.
}
#endif
template<const int INCX, const int INCY>
struct PropagateDanielssonSingleStep {
PropagateDanielssonSingleStep(float *aL, unsigned char *asigns, size_t astride, coord_t aresolution) :
L(aL), signs(asigns), stride(astride), resolution(aresolution) {}
inline void operator()(int r, int c, int addr_delta) {
size_t addr = r * stride + c;
if ((signs[addr] & 2) == 0) {
float *v = &L[addr << 1];
float l = v[0] * v[0] + v[1] * v[1];
float *v2s = v + (addr_delta << 1);
float v2[2] = {
v2s[0] + INCX * resolution,
v2s[1] + INCY * resolution
};
float l2 = v2[0] * v2[0] + v2[1] * v2[1];
if (l2 < l) {
v[0] = v2[0];
v[1] = v2[1];
}
}
}
float *L;
unsigned char *signs;
size_t stride;
coord_t resolution;
};
struct PropagateDanielssonSingleVStep3 {
PropagateDanielssonSingleVStep3(float *aL, unsigned char *asigns, size_t astride, coord_t aresolution) :
L(aL), signs(asigns), stride(astride), resolution(aresolution) {}
inline void operator()(int r, int c, int addr_delta, bool has_l, bool has_r) {
size_t addr = r * stride + c;
if ((signs[addr] & 2) == 0) {
float *v = &L[addr<<1];
float l = v[0]*v[0]+v[1]*v[1];
float *v2s = v+(addr_delta<<1);
float v2[2] = {
v2s[0],
v2s[1] + resolution
};
float l2 = v2[0]*v2[0]+v2[1]*v2[1];
if (l2 < l) {
v[0] = v2[0];
v[1] = v2[1];
}
if (has_l) {
float *v2sl = v2s - 1;
v2[0] = v2sl[0] + resolution;
v2[1] = v2sl[1] + resolution;
l2 = v2[0]*v2[0]+v2[1]*v2[1];
if (l2 < l) {
v[0] = v2[0];
v[1] = v2[1];
}
}
if (has_r) {
float *v2sr = v2s + 1;
v2[0] = v2sr[0] + resolution;
v2[1] = v2sr[1] + resolution;
l2 = v2[0]*v2[0]+v2[1]*v2[1];
if (l2 < l) {
v[0] = v2[0];
v[1] = v2[1];
}
}
}
}
float *L;
unsigned char *signs;
size_t stride;
coord_t resolution;
};
void EdgeGrid::Grid::calculate_sdf()
{
#ifdef EDGE_GRID_DEBUG_OUTPUT
static int iRun = 0;
++ iRun;
#endif
// 1) Initialize a signum and an unsigned vector to a zero iso surface.
size_t nrows = m_rows + 1;
size_t ncols = m_cols + 1;
// Unsigned vectors towards the closest point on the surface.
std::vector<float> L(nrows * ncols * 2, FLT_MAX);
// Bit 0 set - negative.
// Bit 1 set - original value, the distance value shall not be changed by the Danielsson propagation.
// Bit 2 set - signum not propagated yet.
std::vector<unsigned char> signs(nrows * ncols, 4);
// SDF will be initially filled with unsigned DF.
// m_signed_distance_field.assign(nrows * ncols, FLT_MAX);
float search_radius = float(m_resolution<<1);
m_signed_distance_field.assign(nrows * ncols, search_radius);
// For each cell:
for (int r = 0; r < (int)m_rows; ++ r) {
for (int c = 0; c < (int)m_cols; ++ c) {
const Cell &cell = m_cells[r * m_cols + c];
// For each segment in the cell:
for (size_t i = cell.begin; i != cell.end; ++ i) {
const Contour &contour = m_contours[m_cell_data[i].first];
assert(contour.closed());
size_t ipt = m_cell_data[i].second;
// End points of the line segment.
const Slic3r::Point &p1 = contour.segment_start(ipt);
const Slic3r::Point &p2 = contour.segment_end(ipt);
// Segment vector
const Slic3r::Point v_seg = p2 - p1;
// l2 of v_seg
const int64_t l2_seg = int64_t(v_seg(0)) * int64_t(v_seg(0)) + int64_t(v_seg(1)) * int64_t(v_seg(1));
// For each corner of this cell and its 1 ring neighbours:
for (int corner_y = -1; corner_y < 3; ++ corner_y) {
coord_t corner_r = r + corner_y;
if (corner_r < 0 || (size_t)corner_r >= nrows)
continue;
for (int corner_x = -1; corner_x < 3; ++ corner_x) {
coord_t corner_c = c + corner_x;
if (corner_c < 0 || (size_t)corner_c >= ncols)
continue;
float &d_min = m_signed_distance_field[corner_r * ncols + corner_c];
Slic3r::Point pt(m_bbox.min(0) + corner_c * m_resolution, m_bbox.min(1) + corner_r * m_resolution);
Slic3r::Point v_pt = pt - p1;
// dot(p2-p1, pt-p1)
int64_t t_pt = int64_t(v_seg(0)) * int64_t(v_pt(0)) + int64_t(v_seg(1)) * int64_t(v_pt(1));
if (t_pt < 0) {
// Closest to p1.
double dabs = sqrt(int64_t(v_pt(0)) * int64_t(v_pt(0)) + int64_t(v_pt(1)) * int64_t(v_pt(1)));
if (dabs < d_min) {
// Previous point.
const Slic3r::Point &p0 = contour.segment_prev(ipt);
Slic3r::Point v_seg_prev = p1 - p0;
int64_t t2_pt = int64_t(v_seg_prev(0)) * int64_t(v_pt(0)) + int64_t(v_seg_prev(1)) * int64_t(v_pt(1));
if (t2_pt > 0) {
// Inside the wedge between the previous and the next segment.
// Set the signum depending on whether the vertex is convex or reflex.
int64_t det = int64_t(v_seg_prev(0)) * int64_t(v_seg(1)) - int64_t(v_seg_prev(1)) * int64_t(v_seg(0));
assert(det != 0);
d_min = dabs;
// Fill in an unsigned vector towards the zero iso surface.
float *l = &L[(corner_r * ncols + corner_c) << 1];
l[0] = std::abs(v_pt(0));
l[1] = std::abs(v_pt(1));
#ifdef _DEBUG
double dabs2 = sqrt(l[0]*l[0]+l[1]*l[1]);
assert(std::abs(dabs-dabs2) < 1e-4 * std::max(dabs, dabs2));
#endif /* _DEBUG */
signs[corner_r * ncols + corner_c] = ((det < 0) ? 1 : 0) | 2;
}
}
}
else if (t_pt > l2_seg) {
// Closest to p2. Then p2 is the starting point of another segment, which shall be discovered in the same cell.
continue;
} else {
// Closest to the segment.
assert(t_pt >= 0 && t_pt <= l2_seg);
int64_t d_seg = int64_t(v_seg(1)) * int64_t(v_pt(0)) - int64_t(v_seg(0)) * int64_t(v_pt(1));
double d = double(d_seg) / sqrt(double(l2_seg));
double dabs = std::abs(d);
if (dabs < d_min) {
d_min = dabs;
// Fill in an unsigned vector towards the zero iso surface.
float *l = &L[(corner_r * ncols + corner_c) << 1];
float linv = float(d_seg) / float(l2_seg);
l[0] = std::abs(float(v_seg(1)) * linv);
l[1] = std::abs(float(v_seg(0)) * linv);
#ifdef _DEBUG
double dabs2 = sqrt(l[0]*l[0]+l[1]*l[1]);
assert(std::abs(dabs-dabs2) <= 1e-4 * std::max(dabs, dabs2));
#endif /* _DEBUG */
signs[corner_r * ncols + corner_c] = ((d_seg < 0) ? 1 : 0) | 2;
}
}
}
}
}
}
}
#ifdef EDGE_GRID_DEBUG_OUTPUT
{
std::vector<uint8_t> pixels(ncols * nrows * 3, 0);
for (coord_t r = 0; r < nrows; ++ r) {
for (coord_t c = 0; c < ncols; ++ c) {
uint8_t *pxl = pixels.data() + (((nrows - r - 1) * ncols) + c) * 3;
float d = m_signed_distance_field[r * ncols + c];
if (d != search_radius) {
float s = 255 * d / search_radius;
int is = std::max(0, std::min(255, int(floor(s + 0.5f))));
pxl[0] = 255;
pxl[1] = 255 - is;
pxl[2] = 255 - is;
}
else {
pxl[0] = 0;
pxl[1] = 255;
pxl[2] = 0;
}
}
}
png::write_rgb_to_file_scaled(debug_out_path("unsigned_df-%d.png", iRun), ncols, nrows, pixels, 10);
}
{
std::vector<uint8_t> pixels(ncols * nrows * 3, 0);
for (coord_t r = 0; r < nrows; ++ r) {
for (coord_t c = 0; c < ncols; ++ c) {
unsigned char *pxl = pixels.data() + (((nrows - r - 1) * ncols) + c) * 3;
float d = m_signed_distance_field[r * ncols + c];
if (d != search_radius) {
float s = 255 * d / search_radius;
int is = std::max(0, std::min(255, int(floor(s + 0.5f))));
if ((signs[r * ncols + c] & 1) == 0) {
// Positive
pxl[0] = 255;
pxl[1] = 255 - is;
pxl[2] = 255 - is;
}
else {
// Negative
pxl[0] = 255 - is;
pxl[1] = 255 - is;
pxl[2] = 255;
}
}
else {
pxl[0] = 0;
pxl[1] = 255;
pxl[2] = 0;
}
}
}
png::write_rgb_to_file_scaled(debug_out_path("signed_df-%d.png", iRun), ncols, nrows, pixels, 10);
}
#endif // EDGE_GRID_DEBUG_OUTPUT
// 2) Propagate the signum.
#define PROPAGATE_SIGNUM_SINGLE_STEP(DELTA) do { \
size_t addr = r * ncols + c; \
unsigned char &cur_val = signs[addr]; \
if (cur_val & 4) { \
unsigned char old_val = signs[addr + (DELTA)]; \
if ((old_val & 4) == 0) \
cur_val = old_val & 1; \
} \
} while (0);
// Top to bottom propagation.
for (size_t r = 0; r < nrows; ++ r) {
if (r > 0)
for (size_t c = 0; c < ncols; ++ c)
PROPAGATE_SIGNUM_SINGLE_STEP(- int(ncols));
for (size_t c = 1; c < ncols; ++ c)
PROPAGATE_SIGNUM_SINGLE_STEP(- 1);
for (int c = int(ncols) - 2; c >= 0; -- c)
PROPAGATE_SIGNUM_SINGLE_STEP(+ 1);
}
// Bottom to top propagation.
for (int r = int(nrows) - 2; r >= 0; -- r) {
for (size_t c = 0; c < ncols; ++ c)
PROPAGATE_SIGNUM_SINGLE_STEP(+ ncols);
for (size_t c = 1; c < ncols; ++ c)
PROPAGATE_SIGNUM_SINGLE_STEP(- 1);
for (int c = int(ncols) - 2; c >= 0; -- c)
PROPAGATE_SIGNUM_SINGLE_STEP(+ 1);
}
#undef PROPAGATE_SIGNUM_SINGLE_STEP
// 3) Propagate the distance by the Danielsson chamfer metric.
// Top to bottom propagation.
PropagateDanielssonSingleStep<1, 0> danielsson_hstep(L.data(), signs.data(), ncols, m_resolution);
PropagateDanielssonSingleStep<0, 1> danielsson_vstep(L.data(), signs.data(), ncols, m_resolution);
PropagateDanielssonSingleVStep3 danielsson_vstep3(L.data(), signs.data(), ncols, m_resolution);
// Top to bottom propagation.
for (size_t r = 0; r < nrows; ++ r) {
if (r > 0)
for (size_t c = 0; c < ncols; ++ c)
danielsson_vstep(r, c, -int(ncols));
// PROPAGATE_DANIELSSON_SINGLE_VSTEP3(-int(ncols), c != 0, c + 1 != ncols);
for (size_t c = 1; c < ncols; ++ c)
danielsson_hstep(r, c, -1);
for (int c = int(ncols) - 2; c >= 0; -- c)
danielsson_hstep(r, c, +1);
}
// Bottom to top propagation.
for (int r = int(nrows) - 2; r >= 0; -- r) {
for (size_t c = 0; c < ncols; ++ c)
danielsson_vstep(r, c, +ncols);
// PROPAGATE_DANIELSSON_SINGLE_VSTEP3(+int(ncols), c != 0, c + 1 != ncols);
for (size_t c = 1; c < ncols; ++ c)
danielsson_hstep(r, c, -1);
for (int c = int(ncols) - 2; c >= 0; -- c)
danielsson_hstep(r, c, +1);
}
// Update signed distance field from absolte vectors to the iso-surface.
for (size_t r = 0; r < nrows; ++ r) {
for (size_t c = 0; c < ncols; ++ c) {
size_t addr = r * ncols + c;
float *v = &L[addr<<1];
float d = sqrt(v[0]*v[0]+v[1]*v[1]);
if (signs[addr] & 1)
d = -d;
m_signed_distance_field[addr] = d;
}
}
#ifdef EDGE_GRID_DEBUG_OUTPUT
{
std::vector<uint8_t> pixels(ncols * nrows * 3, 0);
float search_radius = float(m_resolution * 5);
for (coord_t r = 0; r < nrows; ++r) {
for (coord_t c = 0; c < ncols; ++c) {
uint8_t *pxl = pixels.data() + (((nrows - r - 1) * ncols) + c) * 3;
uint8_t sign = signs[r * ncols + c];
switch (sign) {
case 0:
// Positive, outside of a narrow band.
pxl[0] = 0;
pxl[1] = 0;
pxl[2] = 255;
break;
case 1:
// Negative, outside of a narrow band.
pxl[0] = 255;
pxl[1] = 0;
pxl[2] = 0;
break;
case 2:
// Positive, outside of a narrow band.
pxl[0] = 100;
pxl[1] = 100;
pxl[2] = 255;
break;
case 3:
// Negative, outside of a narrow band.
pxl[0] = 255;
pxl[1] = 100;
pxl[2] = 100;
break;
case 4:
// This shall not happen. Undefined signum.
pxl[0] = 0;
pxl[1] = 255;
pxl[2] = 0;
break;
default:
// This shall not happen. Invalid signum value.
pxl[0] = 255;
pxl[1] = 255;
pxl[2] = 255;
break;
}
}
}
png::write_rgb_to_file_scaled(debug_out_path("signed_df-signs-%d.png", iRun), ncols, nrows, pixels, 10);
}
#endif // EDGE_GRID_DEBUG_OUTPUT
#ifdef EDGE_GRID_DEBUG_OUTPUT
{
std::vector<uint8_t> pixels(ncols * nrows * 3, 0);
float search_radius = float(m_resolution * 5);
for (coord_t r = 0; r < nrows; ++r) {
for (coord_t c = 0; c < ncols; ++c) {
uint8_t *pxl = pixels.data() + (((nrows - r - 1) * ncols) + c) * 3;
float d = m_signed_distance_field[r * ncols + c];
float s = 255.f * fabs(d) / search_radius;
int is = std::max(0, std::min(255, int(floor(s + 0.5f))));
if (d < 0.f) {
pxl[0] = 255;
pxl[1] = 255 - is;
pxl[2] = 255 - is;
}
else {
pxl[0] = 255 - is;
pxl[1] = 255 - is;
pxl[2] = 255;
}
}
}
png::write_rgb_to_file_scaled(debug_out_path("signed_df2-%d.png", iRun), ncols, nrows, pixels, 10);
}
#endif // EDGE_GRID_DEBUG_OUTPUT
}
float EdgeGrid::Grid::signed_distance_bilinear(const Point &pt) const
{
coord_t x = pt(0) - m_bbox.min(0);
coord_t y = pt(1) - m_bbox.min(1);
coord_t w = m_resolution * m_cols;
coord_t h = m_resolution * m_rows;
bool clamped = false;
coord_t xcl = x;
coord_t ycl = y;
if (x < 0) {
xcl = 0;
clamped = true;
} else if (x >= w) {
xcl = w - 1;
clamped = true;
}
if (y < 0) {
ycl = 0;
clamped = true;
} else if (y >= h) {
ycl = h - 1;