-
Notifications
You must be signed in to change notification settings - Fork 30
/
ak-link_chains.cpp
1993 lines (1762 loc) · 69.2 KB
/
ak-link_chains.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 "pipeline.hpp"
#include <glm/gtx/norm.hpp>
#include <glm/gtx/hash.hpp>
#include <iostream>
#include <map>
#include <set>
#include <functional>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include <cstring>
//fill in any -1U segments in closest with nearby indices (or return false if closest is entirely -1U):
bool fill_unassigned(std::vector< uint32_t > &closest, std::vector< float > const &weights, bool is_loop);
//helper to re-label closest points so they have a possible flattening on the bed, given the supplied costs for relabelling:
void flatten(std::vector< uint32_t > &closest, std::vector< float > const &costs, bool is_loop);
void ak::link_chains(
Parameters const ¶meters,
Model const &slice, //in: slice on which the chains reside
std::vector< float > const &slice_times, //in: time field (times @ vertices), for slice
std::vector< std::vector< uint32_t > > const &active_chains, //in: current active chains (slice vertex #'s)
std::vector< std::vector< Stitch > > const &active_stitches, //in: current active stitches
std::vector< std::vector< uint32_t > > const &next_chains, //in: current next chains (slice vertex #'s)
std::vector< bool > const &next_used_boundary, //in: did next chain use boundary? (forces no discard)
//need this or slice_times (above) std::vector< std::vector< bool > > const &discard_segments,
std::vector< std::vector< Stitch > > *next_stitches_, //out: next active stitches
std::vector< Link > *links_ //out: active_chains[from_chain][from_vertex] -> linked_next_chains[to_chain][to_vertex] links
) {
assert(slice_times.size() == slice.vertices.size());
for (auto const &chain : active_chains) {
assert(chain.size() >= 2);
assert(chain[0] != chain.back() || chain.size() >= 3);
for (auto v : chain) {
assert(v < slice.vertices.size());
}
}
assert(active_stitches.size() == active_chains.size());
for (auto const &stitches : active_stitches) {
for (auto const &s : stitches) {
assert(s.t >= 0.0f);
assert(s.t < 1.0f);
if (&s > &stitches[0]) {
assert(s.t > (&s-1)->t);
}
}
}
for (auto const &chain : next_chains) {
assert(chain.size() >= 2);
assert(chain[0] != chain.back() || chain.size() >= 3);
for (auto v : chain) {
assert(v < slice.vertices.size());
}
}
assert(next_used_boundary.size() == next_chains.size());
assert(next_stitches_);
auto &next_stitches = *next_stitches_;
next_stitches.clear();
assert(links_);
auto &links = *links_;
links.clear();
//figure out the time to trim after:
float active_max_time = -std::numeric_limits< float >::infinity();
for (auto const &chain : active_chains) {
for (auto v : chain) {
active_max_time = std::max(active_max_time, slice_times[v]);
}
}
//first, write down length to each vertex (makes it easy to move to/from parameter space):
auto make_lengths = [&slice](std::vector< std::vector< uint32_t > > const &chains) {
std::vector< std::vector< float > > all_lengths;
all_lengths.reserve(chains.size());
for (auto const &chain : chains) {
all_lengths.emplace_back();
std::vector< float > &lengths = all_lengths.back();
lengths.reserve(chain.size());
float total_length = 0.0f;
lengths.emplace_back(total_length);
for (uint32_t vi = 1; vi < chain.size(); ++vi) {
glm::vec3 const &a = slice.vertices[chain[vi-1]];
glm::vec3 const &b = slice.vertices[chain[vi]];
total_length += glm::length(b-a);
lengths.emplace_back(total_length);
}
assert(lengths.size() == chain.size());
}
return all_lengths;
};
std::vector< std::vector< float > > active_lengths = make_lengths(active_chains);
std::vector< std::vector< float > > next_lengths = make_lengths(next_chains);
//figure out ranges (in parameter space) that are to be discarded:
std::vector< std::vector< std::pair< float, bool > > > next_discard_after;
next_discard_after.reserve(next_chains.size());
for (auto const &chain : next_chains) {
uint32_t ci = &chain - &next_chains[0];
std::vector< float > const &lengths = next_lengths[ci];
assert(lengths.size() == chain.size());
next_discard_after.emplace_back();
auto &discard_after = next_discard_after.back();
discard_after.emplace_back(0.0f, (slice_times[chain[0]] > active_max_time));
for (uint32_t vi = 0; vi + 1 < chain.size(); ++vi) {
float ta = slice_times[chain[vi]];
float tb = slice_times[chain[vi+1]];
float la = lengths[vi];
float lb = lengths[vi+1];
//note: for the purposes of assigning ranges, treat time t == active_max_time as t - epsilon.
if ((ta <= active_max_time && tb > active_max_time)
|| (ta > active_max_time && tb <= active_max_time) ) {
float m = (active_max_time - ta) / (tb - ta);
float l = m * (lb - la) + la;
discard_after.emplace_back(l / lengths.back(), (tb > active_max_time));
} else {
assert((ta > active_max_time) == (tb > active_max_time));
//do nothing!
}
}
bool is_loop = (chain[0] == chain.back());
//remove any non-discard segments shorter than 1.5 stitches:
if (discard_after.size() > 1) {
float const MinLength = 1.5f * parameters.stitch_width_mm / parameters.model_units_mm;
float first_len = discard_after[1].first - 0.0f;
float last_len = 1.0f - discard_after.back().first;
if (is_loop) {
first_len = last_len = first_len + last_len;
}
for (uint32_t s = 0; s < discard_after.size(); ++s) {
if (discard_after[s].second != false) continue;
float len;
if (s == 0) len = first_len;
else if (s + 1 == discard_after.size()) len = last_len;
else len = discard_after[s+1].first - discard_after[s].first;
if (len * lengths.back() < MinLength) {
discard_after[s].second = true;
}
}
if (is_loop) {
assert(discard_after[0].second == discard_after.back().second);
}
for (uint32_t s = 0; s + 1 < discard_after.size(); /* later */) {
if (discard_after[s].second == discard_after[s+1].second) {
discard_after.erase(discard_after.begin() + (s+1));
} else {
++s;
}
}
}
//remove any discard segments shorter than 0.5 stitches:
if (discard_after.size() > 1) {
float const MinLength = 0.5f * parameters.stitch_width_mm / parameters.model_units_mm;
float first_len = discard_after[1].first - 0.0f;
float last_len = 1.0f - discard_after.back().first;
if (is_loop) {
first_len = last_len = first_len + last_len;
}
for (uint32_t s = 0; s < discard_after.size(); ++s) {
if (discard_after[s].second != true) continue;
float len;
if (s == 0) len = first_len;
else if (s + 1 == discard_after.size()) len = last_len;
else len = discard_after[s+1].first - discard_after[s].first;
if (len * lengths.back() < MinLength) {
discard_after[s].second = false;
}
}
if (is_loop) {
assert(discard_after[0].second == discard_after.back().second);
}
for (uint32_t s = 0; s + 1 < discard_after.size(); /* later */) {
if (discard_after[s].second == discard_after[s+1].second) {
discard_after.erase(discard_after.begin() + (s+1));
} else {
++s;
}
}
}
}
{ //for any next chains that touch a boundary, mark as 'accept':
uint32_t marked = 0;
for (uint32_t ni = 0; ni < next_chains.size(); ++ni) {
if (next_used_boundary[ni] == false) continue;
if (next_discard_after[ni].size() != 1 || next_discard_after[ni][0] != std::make_pair(0.0f, false)) {
next_discard_after[ni].assign(1, std::make_pair(0.0f, false));
++marked;
}
}
if (marked) {
std::cout << "NOTE: marked " << marked << " next chains as all-accept because they touch boundaries." << std::endl;
}
}
{ //if all segments are marked 'discard', then mark everything 'accept':
bool only_discard = true;
for (auto const &discard_after : next_discard_after) {
for (auto const &d : discard_after) {
if (!d.second) {
only_discard = false;
break;
}
}
if (only_discard == false) break;
}
if (only_discard) {
std::cout << "Marking everything accept because it was all marked discard." << std::endl;
for (auto &discard_after : next_discard_after) {
assert(discard_after.size() == 1);
assert(discard_after[0] == std::make_pair(0.0f, true));
discard_after[0].second = false;
}
} else {
std::cout << "Have a mix of discard and accept." << std::endl;
}
}
//------------------------------------------------------------------------------------
//find segments of active and next chains that are mutual nearest neighbors:
std::vector< std::vector< uint32_t > > active_closest;
std::vector< std::vector< uint32_t > > next_closest;
{ //find closest pairs:
std::vector< std::vector< uint32_t > > adj(slice.vertices.size());
{ //adjacency matrix -- always handy:
std::unordered_set< glm::uvec2 > edges;
for (auto const &tri : slice.triangles) {
auto do_edge = [&edges](uint32_t a, uint32_t b) {
if (b > a) std::swap(a,b);
edges.insert(glm::uvec2(a,b));
};
do_edge(tri.x, tri.y);
do_edge(tri.y, tri.z);
do_edge(tri.z, tri.x);
}
for (auto const &e : edges) {
adj[e.x].emplace_back(e.y);
adj[e.y].emplace_back(e.x);
}
}
auto closest_source_chain = [&slice,&adj](
std::vector< std::vector< uint32_t > > const &sources,
std::vector< std::vector< uint32_t > > const &targets) {
std::vector< float > dis(slice.vertices.size(), std::numeric_limits< float >::infinity());
std::vector< uint32_t > from(slice.vertices.size(), -1U);
std::vector< std::pair< float, uint32_t > > todo;
auto queue = [&dis, &todo, &from](uint32_t n, float d, uint32_t f) {
assert(d < dis[n]);
dis[n] = d;
from[n] = f;
todo.emplace_back(std::make_pair(-d, n));
std::push_heap(todo.begin(), todo.end());
};
for (auto const &chain : sources) {
uint32_t ci = &chain - &sources[0];
for (auto const &v : chain) {
if (v == -1U) continue;
if (0.0f < dis[v]) queue(v, 0.0f, ci); //some verts appear twice
}
}
while (!todo.empty()) {
std::pop_heap(todo.begin(), todo.end());
uint32_t at = todo.back().second;
float d = -todo.back().first;
todo.pop_back();
if (d > dis[at]) continue;
assert(d == dis[at]);
for (auto n : adj[at]) {
float nd = d + glm::length(slice.vertices[n] - slice.vertices[at]);
if (nd < dis[n]) queue(n, nd, from[at]);
}
}
std::vector< std::vector< uint32_t > > closest;
closest.reserve(targets.size());
for (auto const &chain : targets) {
closest.emplace_back();
closest.back().reserve(targets.size());
for (auto v : chain) {
if (v == -1U) {
closest.back().emplace_back(-1U);
} else {
closest.back().emplace_back(from[v]);
}
}
}
return closest;
};
active_closest = closest_source_chain(next_chains, active_chains);
next_closest = closest_source_chain(active_chains, next_chains);
//HACK: treat these as 'segment' values instead of 'vertex' (but really every segment just gets first vertex's value):
for (auto &c : active_closest) {
if (!c.empty()) c.pop_back();
}
for (auto &c : next_closest) {
if (!c.empty()) c.pop_back();
}
#if 0
//DEBUG:
for (auto const &ac : active_closest) {
std::cout << "active_closest[" << (&ac - &active_closest[0]) << "]:";
for (auto c : ac) {
std::cout << " " << int32_t(c);
}
std::cout << "\n";
}
std::cout.flush();
for (auto const &nc : next_closest) {
std::cout << "next_closest[" << (&nc - &next_closest[0]) << "]:";
for (auto c : nc) {
std::cout << " " << int32_t(c);
}
std::cout << "\n";
}
std::cout.flush();
#endif
}
//HELPER: discard any matches which aren't mutual
auto discard_nonmutual = [&](){
std::vector< std::set< uint32_t > > active_refs; active_refs.reserve(active_closest.size());
for (auto const &ac : active_closest) {
active_refs.emplace_back(ac.begin(), ac.end());
}
std::vector< std::set< uint32_t > > next_refs; next_refs.reserve(next_closest.size());
for (auto const &nc : next_closest) {
next_refs.emplace_back(nc.begin(), nc.end());
}
uint32_t discarded = 0;
for (auto &ac : active_closest) {
uint32_t ai = &ac - &active_closest[0];
for (auto &c : ac) {
if (c != -1U && !next_refs[c].count(ai)) {
c = -1U;
++discarded;
}
}
}
for (auto &nc : next_closest) {
uint32_t ni = &nc - &next_closest[0];
for (auto &c : nc) {
if (c != -1U && !active_refs[c].count(ni)) {
c = -1U;
++discarded;
}
}
}
if (discarded) std::cout << "Discarded " << discarded << " non-mutual segment matches." << std::endl;
return discarded > 0;
};
//start by removing any non-mutual links:
discard_nonmutual();
//fill discarded areas with adjacent information, and process further to make sure the result can be flattened:
while(true) {
for (auto &closest : active_closest) {
uint32_t ai = &closest - &active_closest[0];
auto const &lengths = active_lengths[ai];
assert(lengths.size() == closest.size() + 1);
bool is_loop = active_chains[ai].empty() || active_chains[ai][0] == active_chains[ai].back();
std::vector< float > weights; weights.reserve(closest.size());
for (uint32_t i = 1; i < lengths.size(); ++i) {
weights.emplace_back(lengths[i] - lengths[i-1]);
}
fill_unassigned(closest, weights, is_loop);
flatten(closest, weights, is_loop);
}
for (auto &closest : next_closest) {
uint32_t ni = &closest - &next_closest[0];
auto const &lengths = next_lengths[ni];
assert(lengths.size() == closest.size() + 1);
bool is_loop = next_chains[ni].empty() || next_chains[ni][0] == next_chains[ni].back();
std::vector< float > weights; weights.reserve(closest.size());
for (uint32_t i = 1; i < lengths.size(); ++i) {
weights.emplace_back(lengths[i] - lengths[i-1]);
}
fill_unassigned(closest, weights, is_loop);
flatten(closest, weights, is_loop);
}
if (discard_nonmutual()) {
std::cout << "NOTE: doing another pass through fill/flatten because additional non-mutual links were discarded." << std::endl;
} else {
break;
}
}
//-----------------------------------------------------------------
//now the *_closest lists are all in good, flatten-able shape.
struct BeginEnd {
BeginEnd(float begin_, float end_) : begin(begin_), end(end_) { }
float begin;
float end;
};
struct BeginEndStitches : public BeginEnd {
BeginEndStitches(float begin_, float end_, uint32_t next_) : BeginEnd(begin_, end_), next(next_) { }
std::vector< uint32_t > stitches;
uint32_t next; //convenience field for split balancing
};
struct BeginEndStitches2 : public BeginEnd {
BeginEndStitches2(float begin_, float end_, uint32_t active_) : BeginEnd(begin_, end_), active(active_) { }
uint32_t stitches = 0; //std::vector< uint32_t > stitches;
uint32_t active; //convenience field for merge balancing
};
//sort active and next into matching parametric ranges:
struct Match {
std::vector< BeginEndStitches > active; //at most two (after post-processing)
std::vector< BeginEndStitches2 > next; //at most two (after post-processing)
};
std::map< std::pair< uint32_t, uint32_t >, Match > matches;
//build parametric segments into matches:
for (auto &closest : active_closest) {
uint32_t ai = &closest - &active_closest[0];
auto const &lengths = active_lengths[ai];
assert(lengths.size() == closest.size() + 1);
for (uint32_t begin = 0; begin < closest.size(); /* later */) {
uint32_t end = begin + 1;
while (end < closest.size() && closest[end] == closest[begin]) ++end;
assert(end < lengths.size());
//std::cout << "[" << begin << ", " << end << ") becomes "; //DEBUG
matches[std::make_pair(ai, closest[begin])].active.emplace_back(lengths[begin] / lengths.back(), lengths[end] / lengths.back(), closest[begin]);
auto m = matches[std::make_pair(ai, closest[begin])].active;
//std::cout << "[" << m.back().begin << ", " << m.back().end << ')'; //DEBUG
//std::cout << " = [" << lengths[begin] << ", " << lengths[end] << ") / " << lengths.back() << std::endl; //DEBUG
begin = end;
}
}
for (auto &closest : next_closest) {
uint32_t ni = &closest - &next_closest[0];
assert(ni < next_lengths.size());
auto const &lengths = next_lengths[ni];
assert(lengths.size() == closest.size() + 1);
for (uint32_t begin = 0; begin < closest.size(); /* later */) {
uint32_t end = begin + 1;
while (end < closest.size() && closest[end] == closest[begin]) ++end;
assert(end < lengths.size());
matches[std::make_pair(closest[begin], ni)].next.emplace_back(lengths[begin] / lengths.back(), lengths[end] / lengths.back(), closest[begin]);
begin = end;
}
}
{ //do stitch assignments:
//sort ranges from matches back to actives:
std::vector< std::vector< BeginEndStitches * > > active_segments(active_chains.size());
for (auto &anm : matches) {
if (anm.first.first == -1U) {
assert(anm.second.active.empty());
continue;
}
for (auto &bse : anm.second.active) {
assert(bse.next == anm.first.second); //'next' should be set correctly!
active_segments[anm.first.first].emplace_back(&bse);
//std::cout << "match[" << int32_t(anm.first.first) << "," << int32_t(anm.first.second) << "] gives segment [" << bse.begin << ',' << bse.end << ')' << std::endl; //DEBUG
}
}
//assign stitches to segments:
for (uint32_t ai = 0; ai < active_chains.size(); ++ai) {
auto &segments = active_segments[ai];
assert(!segments.empty());
std::sort(segments.begin(), segments.end(), [](BeginEndStitches const *a, BeginEndStitches const *b) {
return a->begin < b->begin;
});
//DEBUG:
//std::cout << "active[" << ai << "] segments:";
//for (auto seg : segments) {
// std::cout << ' ' << '[' << seg->begin << ',' << seg->end << ')';
//}
//std::cout << std::endl;
//segments should partition [0.0, 1.0):
assert(!segments.empty());
assert(segments[0]->begin == 0.0f);
assert(segments.back()->end == 1.0f);
for (uint32_t i = 1; i < segments.size(); ++i) {
assert(segments[i-1]->end == segments[i]->begin);
}
//copy stitches to segments:
auto const &stitches = active_stitches[ai];
auto si = stitches.begin();
for (auto seg : segments) {
if (si == stitches.end()) break;
assert(si->t >= seg->begin); //segments should cover everything.
while (si != stitches.end() && (si->t < seg->end)) {
seg->stitches.emplace_back(si - stitches.begin());
++si;
}
}
assert(si == stitches.end()); //segments should cover everything.
}
}
//merge segments because it's probably more convenient for balancing:
uint32_t active_merges = 0;
for (auto &anm : matches) {
if (anm.second.active.size() <= 1) continue;
assert(anm.first.first != -1U);
uint32_t ai = anm.first.first;
bool is_loop = (active_chains[ai].empty() || active_chains[ai][0] == active_chains[ai].back());
if (!is_loop) continue;
std::sort(anm.second.active.begin(), anm.second.active.end(), [](BeginEndStitches const &a, BeginEndStitches const &b){
return a.begin < b.begin;
});
if (anm.second.active[0].begin == 0.0f && anm.second.active.back().end == 1.0f) {
++active_merges;
anm.second.active.back().end = anm.second.active[0].end;
anm.second.active.back().stitches.insert(anm.second.active.back().stitches.end(), anm.second.active[0].stitches.begin(), anm.second.active[0].stitches.end());
anm.second.active.erase(anm.second.active.begin());
}
assert(anm.second.active.size() <= 2); //<-- should be guaranteed by flatten
}
if (active_merges) std::cout << "Merged " << active_merges << " active segments." << std::endl;
uint32_t next_merges = 0;
for (auto &anm : matches) {
if (anm.second.next.size() <= 1) continue;
assert(anm.first.second != -1U);
uint32_t ni = anm.first.second;
bool is_loop = (next_chains[ni].empty() || next_chains[ni][0] == next_chains[ni].back());
if (!is_loop) continue;
std::sort(anm.second.next.begin(), anm.second.next.end(), [](BeginEnd const &a, BeginEnd const &b){
return a.begin < b.begin;
});
if (anm.second.next[0].begin == 0.0f && anm.second.next.back().end == 1.0f) {
++next_merges;
anm.second.next.back().end = anm.second.next[0].end;
anm.second.next.erase(anm.second.next.begin());
}
assert(anm.second.next.size() <= 2); //<-- should be guaranteed by flatten
}
if (next_merges) std::cout << "Merged " << next_merges << " next segments." << std::endl;
{ //balance stitch assignments for splits:
//sort ranges from matches back to actives: (doing again because of merging)
std::vector< std::vector< BeginEndStitches * > > active_segments(active_chains.size());
for (auto &anm : matches) {
if (anm.first.first == -1U) {
assert(anm.second.active.empty());
continue;
}
for (auto &bse : anm.second.active) {
assert(bse.next == anm.first.second); //'next' should be set correctly!
active_segments[anm.first.first].emplace_back(&bse);
}
}
for (uint32_t ai = 0; ai < active_chains.size(); ++ai) {
auto &segments = active_segments[ai];
assert(!segments.empty());
std::sort(segments.begin(), segments.end(), [](BeginEndStitches const *a, BeginEndStitches const *b) {
return a->begin < b->begin;
});
//Note: because of merging, last segment may wrap around weirdly;
// -- this is okay!
bool is_loop = (active_chains[ai].empty() || active_chains[ai][0] == active_chains[ai].back());
assert(
(segments[0]->begin == 0.0f && segments.back()->end == 1.0f)
|| (is_loop && (segments[0]->begin == segments.back()->end))
);
//segments should still partition [0,1):
for (uint32_t i = 1; i < segments.size(); ++i) {
assert(segments[i-1]->end == segments[i]->begin);
}
//find counts (on the way to finding a singleton segment):
std::unordered_map< uint32_t, uint32_t > next_counts;
for (auto seg : segments) {
next_counts.insert(std::make_pair(seg->next, 0)).first->second += 1;
}
uint32_t singles = 0;
uint32_t doubles = 0;
uint32_t multis = 0;
for (auto const &nc : next_counts) {
if (nc.second == 1) ++singles;
else if (nc.second == 2) ++doubles;
else ++multis;
}
assert(multis == 0);
if (singles == 1 && doubles == 0 && multis == 0) {
//just one segment, nothing to re-assign.
continue;
} else if (singles == 2 && doubles == 0 && multis == 0) {
//just two segments, *also* always balanced
continue;
} else if (!(singles == 2 && multis == 0)) {
throw std::runtime_error("Unhandled split situation with " + std::to_string(singles) + " singles, " + std::to_string(doubles) + " doubles, and " + std::to_string(multis) + " multis.");
}
assert(singles == 2 && multis == 0);
//rotate until a single is in the first position:
for (uint32_t s = 0; s < segments.size(); ++s) {
if (next_counts[segments[s]->next] == 1) {
std::rotate(segments.begin(), segments.begin() + s, segments.end());
break;
}
}
assert(next_counts[segments[0]->next] == 1);
//DEBUG: show counts (and adjustments)
std::string old_back;
std::string old_front;
auto pad = [](std::string s) -> std::string {
while (s.size() < 3) s = ' ' + s;
return s;
};
old_back += pad(std::to_string(segments[0]->stitches.size()));
old_front += pad("");
for (uint32_t i = 1; i < segments.size()/2; ++i) {
uint32_t io = uint32_t(segments.size())-i;
assert(segments[i]->next == segments[io]->next);
old_back += pad(std::to_string(segments[i]->stitches.size()));
old_front += pad(std::to_string(segments[io]->stitches.size()));
}
old_back += pad("");
old_front += pad(std::to_string(segments[segments.size()/2]->stitches.size()));
//end DEBUG
//expecting things to look like this now (doubles, in order, then another single, then the doubles, reversed):
// a b c d c b
assert(segments.size() % 2 == 0);
assert(segments.size() >= 4);
assert(next_counts[segments[segments.size()/2]->next] == 1);
for (uint32_t i = 1; i < segments.size()/2; ++i) {
assert(segments[i]->next == segments[segments.size()-i]->next);
}
//now push extra stitches from the center outward:
uint32_t m = (uint32_t(segments.size())/2)/2; //so a b c b -> m = 1 ; a b c d e d c b -> m = 2;
assert(0 < m && m < uint32_t(segments.size())/2);
{ //push from the middle segment outward (alternating sides):
uint32_t mo = uint32_t(segments.size())-m;
assert(segments.size()/2 < mo && mo < segments.size());
uint32_t mo_p = mo-1; assert(mo_p < segments.size());
uint32_t mo_n = (mo+1 < segments.size() ? mo+1 : 0); assert(mo_n < segments.size());
//layout:
// m-1 m m+1
// mo_n mo mo_p
assert(segments[mo]->next == segments[m]->next);
while (segments[m]->stitches.size() > segments[mo]->stitches.size()) {
segments[m+1]->stitches.insert(segments[m+1]->stitches.begin(), segments[m]->stitches.back());
segments[m]->stitches.pop_back();
if (segments[m]->stitches.size() > segments[mo]->stitches.size()) {
segments[m-1]->stitches.push_back(segments[m]->stitches[0]);
segments[m]->stitches.erase(segments[m]->stitches.begin());
}
}
while (segments[mo]->stitches.size() > segments[m]->stitches.size()) {
segments[mo_p]->stitches.push_back(segments[mo]->stitches[0]);
segments[mo]->stitches.erase(segments[mo]->stitches.begin());
if (segments[mo]->stitches.size() > segments[m]->stitches.size()) {
segments[mo_n]->stitches.insert(segments[mo_n]->stitches.begin(), segments[mo]->stitches.back());
segments[mo]->stitches.pop_back();
}
}
}
//push from left-side segments leftward:
for (uint32_t l = m-1; l > 0; --l) {
uint32_t lo = uint32_t(segments.size())-l;
uint32_t lo_n = (lo+1 < segments.size() ? lo+1 : 0); assert(lo_n < segments.size());
assert(segments[lo]->next == segments[l]->next);
while (segments[l]->stitches.size() > segments[lo]->stitches.size()) {
segments[l-1]->stitches.push_back(segments[l]->stitches[0]);
segments[l]->stitches.erase(segments[l]->stitches.begin());
}
while (segments[lo]->stitches.size() > segments[l]->stitches.size()) {
segments[lo_n]->stitches.insert(segments[lo_n]->stitches.begin(), segments[lo]->stitches.back());
segments[lo]->stitches.pop_back();
}
}
//push from right-side segments leftward:
for (uint32_t r = m+1; r < segments.size()/2; ++r) {
uint32_t ro = uint32_t(segments.size())-r;
uint32_t ro_p = ro-1; assert(ro_p < segments.size());
assert(segments[ro]->next == segments[r]->next);
while (segments[r]->stitches.size() > segments[ro]->stitches.size()) {
segments[r+1]->stitches.insert(segments[r+1]->stitches.begin(), segments[r]->stitches.back());
segments[r]->stitches.pop_back();
}
while (segments[ro]->stitches.size() > segments[r]->stitches.size()) {
segments[ro_p]->stitches.push_back(segments[ro]->stitches[0]);
segments[ro]->stitches.erase(segments[ro]->stitches.begin());
}
}
//check for balance:
for (uint32_t i = 1; i < segments.size()/2; ++i) {
uint32_t io = uint32_t(segments.size())-i;
assert(segments[i]->stitches.size() == segments[io]->stitches.size());
}
//DEBUG: show counts (and adjustments?)
std::string new_back;
std::string new_front;
new_back += pad(std::to_string(segments[0]->stitches.size()));
new_front += pad("");
for (uint32_t i = 1; i < segments.size()/2; ++i) {
uint32_t io = uint32_t(segments.size())-i;
assert(segments[i]->next == segments[io]->next);
new_back += pad(std::to_string(segments[i]->stitches.size()));
new_front += pad(std::to_string(segments[io]->stitches.size()));
}
new_back += pad("");
new_front += pad(std::to_string(segments[segments.size()/2]->stitches.size()));
//end DEBUG
if (old_back != new_back || old_front != new_front) {
std::cout << "Balanced a merge:\n";
std::cout << "old: " << old_back << "\n";
std::cout << " " << old_front << "\n";
std::cout << "new: " << new_back << "\n";
std::cout << " " << new_front << "\n";
std::cout.flush();
//} else {
//if (old_back == new_back && old_front == new_front) {
//std::cout << "NOTE: merge was already balanced." << std::endl;
}
}
}
//Look for merges/splits:
std::vector< uint32_t > active_matches(active_chains.size(), 0);
std::vector< uint32_t > next_matches(next_chains.size(), 0);
uint32_t empty_matches = 0;
for (auto const &anm : matches) {
if (anm.first.first != -1U) active_matches[anm.first.first] += 1;
if (anm.first.second != -1U) next_matches[anm.first.second] += 1;
if (anm.first.first == -1U || anm.first.second == -1U) ++empty_matches;
}
if (empty_matches) std::cout << "NOTE: have " << empty_matches << " segments that match with nothing." << std::endl;
{ //If there are any merges or splits, all participating next cycles are marked 'accept':
std::set< uint32_t > to_mark;
for (auto const &anm : matches) {
if (anm.first.first == -1U || anm.first.second == -1U) continue;
bool is_split_or_merge = (active_matches[anm.first.first] > 1 || next_matches[anm.first.second] > 1);
if (is_split_or_merge) {
to_mark.insert(anm.first.second);
}
}
uint32_t were_marked = 0;
for (auto ni : to_mark) {
for (auto const &td : next_discard_after[ni]) {
if (td.second) ++were_marked;
}
next_discard_after[ni].assign(1, std::make_pair(0.0f, false));
}
if (!to_mark.empty() && were_marked != 0) {
std::cerr << "Marked " << were_marked << " segments on " << to_mark.size() << " next cycles as 'accept' based on participating in a merge/split." << std::endl;
}
}
//allocate next stitches:
next_stitches.assign(next_chains.size(), std::vector< ak::Stitch >());
//allocate stitch counts based on segment lengths + source stitches:
//(and limit based on active stitch counts)
//then make next stitches
for (auto &anm : matches) {
Match &match = anm.second;
if (match.active.empty()) {
std::cout << "Ignoring match with empty active chain." << std::endl;
continue;
} else if (match.next.empty()) {
if (active_matches[anm.first.first] == 1) {
std::cout << "WARNING: active chain matches nothing at all; will not be linked and will thus be discarded." << std::endl;
} else {
std::cout << "Ignoring match with empty next chain." << std::endl;
}
continue;
}
assert(!match.active.empty());
assert(!match.next.empty());
bool is_split_or_merge = (active_matches[anm.first.first] > 1 || next_matches[anm.first.second] > 1);
//if is_split_or_merge will only link 1-1
//compute min/max totals from assigned stitches:
uint32_t active_ones = 0;
uint32_t active_anys = 0;
{
std::vector< ak::Stitch > const &stitches = active_stitches[anm.first.first];
for (auto const &be : match.active) {
for (auto si : be.stitches) {
assert(si < stitches.size());
if (stitches[si].flag == Stitch::FlagLinkOne) ++active_ones;
else if (stitches[si].flag == Stitch::FlagLinkAny) ++active_anys;
else assert(stitches[si].flag == Stitch::FlagLinkOne || stitches[si].flag == Stitch::FlagLinkAny);
}
}
}
//compute number of ones based on discard segments:
//Ideally we'd like this to be true (saves on discarded stitches):
// discarded segments contain at least one stitch marked 'LinkOne'
// while kept segments contain at least two stitches marked 'LinkOne'
//What we're doing below actually puts two stitches in discarded segments as well.
uint32_t next_ones = 0;
bool next_is_loop = (next_chains[anm.first.second][0] == next_chains[anm.first.second].back());
auto const &discard_after = next_discard_after[anm.first.second];
{ //compute next_ones:
if (next_is_loop) {
assert(discard_after[0].second == discard_after.back().second);
}
//every discard/non-discard edge needs at least one stitch next to it on each side:
for (auto const &be : match.next) {
for (auto tdi = discard_after.begin(); tdi != discard_after.end(); ++tdi) {
if (next_is_loop && tdi == discard_after.begin()) continue;
if (be.begin <= tdi->first && tdi->first < be.end) ++next_ones;
if (be.begin < tdi->first && tdi->first <= be.end) ++next_ones;
}
}
if (next_ones > 2 * active_anys + active_ones) {
std::cerr << "ERROR: more discard/non-discard ends are required (" << next_ones << ") than are permitted by the current active flags (" << active_anys << "*2 + " << active_ones << "); code to fix this (by removing shortest same-discard segment) not yet implemented." << std::endl;
assert(next_ones <= 2 * active_anys + active_ones);
}
}
//compute desired stitch count based on segment lengths:
assert(anm.first.second < next_lengths.size());
std::vector< float > const &lengths = next_lengths[anm.first.second];
float total_length = 0.0f;
//std::cout << "Matching to"; //DEBUG
for (auto const &be : match.next) {
// std::cout << " [" << be.begin << ", " << be.end << ")"; std::cout.flush(); //DEBUG
if (be.begin <= be.end) {
total_length += be.end - be.begin;
} else {
assert(be.begin < be.end + 1.0f);
total_length += (be.end + 1.0f) - be.begin;
}
}
//std::cout << std::endl; //DEBUG
total_length *= lengths.back();
float stitch_width = parameters.stitch_width_mm / parameters.model_units_mm;
uint32_t stitches = std::max(1, int32_t(std::round(total_length / stitch_width)));
{ //adjust for possible links:
//least is to link 1-1 for every next_ones and then link everything else 2-1:
uint32_t lower = next_ones //next ones to link to one stitch
+ (std::max(0, int32_t(active_ones + active_anys) - int32_t(next_ones)) + 1) / 2 //other stitches link 2-1
;
uint32_t upper = active_ones + 2 * active_anys; //most is to increase from all anys
assert(lower <= upper);
if (is_split_or_merge) {
assert(lower <= active_ones + active_anys && active_ones + active_anys <= upper);
std::cout << "NOTE: setting stitches from " << stitches << " to ";
stitches = active_ones + active_anys;
std::cout << stitches << " to make split/merge 1-1." << std::endl;
//stitches = active_ones + active_anys;
}
if (stitches < lower || stitches > upper) {
std::cout << "NOTE: stitches (" << stitches << ") will be clamped to possible range [" << lower << ", " << upper << "], which might cause some shape distortion." << std::endl;
stitches = std::max(lower, std::min(upper, stitches));
}
std::cout << "Will make " << stitches << " stitches, given active with " << active_ones << " ones, " << active_anys << " anys; next with " << next_ones << " ones." << std::endl; //DEBUG
}
std::vector< ak::Stitch > new_stitches;
if (stitches > 0) {
//spread stitches among "allocation ranges" (same discard status)
struct Alloc {
Alloc(float begin_, float end_, bool first_one_, bool last_one_, uint32_t bi_) : begin(begin_), end(end_), first_one(first_one_), last_one(last_one_), bi(bi_) { assert(begin < end); }
float begin, end;
bool first_one, last_one;
uint32_t bi; //<-- BeginEnd range this came from
uint32_t stitches = 0;
float length = std::numeric_limits< float >::quiet_NaN();
};
std::vector< Alloc > alloc;
//NOTE: care is taken so that when stitches are added to the match.next.stitches[] arrays during creation, they will be in CCW order:
for (auto const &be : match.next) {
uint32_t bi = &be - &match.next[0];
auto split_back = [&]() {
//split allocation range on discards:
for (auto tdi = discard_after.begin(); tdi != discard_after.end(); ++tdi) {
if (next_is_loop && tdi == discard_after.begin()) continue;
if (tdi->first < alloc.back().begin) {
} else if (tdi->first == alloc.back().begin) {
alloc.back().first_one = true;
} else if (tdi->first < alloc.back().end) {
float end = alloc.back().end;
alloc.back().last_one = true;
alloc.back().end = tdi->first;
alloc.emplace_back(tdi->first, end, true, false, alloc.back().bi);
} else if (tdi->first == alloc.back().end) {
alloc.back().last_one = true;
} else { assert(tdi->first > alloc.back().end);
}
}
};
if (be.begin <= be.end) {
alloc.emplace_back(be.begin, be.end, false, false, bi);
split_back();
} else {
alloc.emplace_back(be.begin, 1.0f, false, false, bi);
split_back();
alloc.emplace_back(0.0f, be.end, false, false, bi);
split_back();
}
}
uint32_t total_ones = 0;
for (auto &a : alloc) {
a.stitches = (a.first_one ? 1 : 0) + (a.last_one ? 1 : 0);
total_ones += a.stitches;
a.length = (a.end - a.begin) * lengths.back();
assert(a.length >= 0.0f);
}
assert(total_ones == next_ones); //better have the same number of ones as we accounted for previously
//add remaining stitches to alloc ranges based on which range has the least-dense stitches:
for (uint32_t s = total_ones; s < stitches; ++s) {
uint32_t best = -1U;
float best_density = 0.0f;
for (auto const &a : alloc) {
float d = a.length / float(a.stitches + 1);
if (d > best_density) {
best = &a - &alloc[0];
best_density = d;
}
}
assert(best < alloc.size());
alloc[best].stitches += 1;
}
//actually create stitches from allocation ranges:
for (auto const &a : alloc) {
if (a.stitches == 0) continue;