forked from jpanetta/ElasticRods
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRodLinkage.cc
3044 lines (2684 loc) · 137 KB
/
RodLinkage.cc
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 "RodLinkage.hh"
#include "LinkageTerminalEdgeSensitivity.hh"
#include <queue>
#include <map>
#include <algorithm>
#include <iterator>
#include <MeshFEM/MeshIO.hh>
#include <MeshFEM/GlobalBenchmark.hh>
#include <MeshFEM/MSHFieldWriter.hh>
#include <MeshFEM/utils.hh>
#include <MeshFEM/filters/merge_duplicate_vertices.hh>
#include "VectorOperations.hh"
#if MESHFEM_WITH_TBB
#include <tbb/tbb.h>
#include <tbb/parallel_for.h>
#include <tbb/enumerable_thread_specific.h>
#endif
#include <MeshFEM/unused.hh>
template<typename Real_>
void RodLinkage_T<Real_>::read(const std::string &path, size_t subdivision, bool initConsistentAngle) {
std::vector<MeshIO::IOVertex > vertices;
std::vector<MeshIO::IOElement> elements;
MeshIO::load(path, vertices, elements);
set(vertices, elements, subdivision, initConsistentAngle);
}
template<typename Real_>
void RodLinkage_T<Real_>::set(std::vector<MeshIO::IOVertex > vertices, // copy edited inside
std::vector<MeshIO::IOElement> edges, // copy edited inside
size_t subdivision,
bool initConsistentAngle) {
{
const size_t old_nv = vertices.size();
merge_duplicate_vertices(vertices, edges, vertices, edges, 1e-10);
const size_t nv = vertices.size();
if (nv != old_nv) std::cerr << "WARNING: merged " << old_nv - nv << " duplicated vertices" << std::endl;
}
const size_t nv = vertices.size(),
ne = edges.size();
m_segments.clear();
m_joints.clear();
m_segments.reserve(edges.size());
m_joints.reserve(vertices.size());
std::vector<size_t> valence(nv);
// Note: only the first valence[vi] entries of incidentEdges are used; the
// rest are left uninitialized
std::vector<std::array<size_t, 4>> incidentEdges(nv);
// Determine vertex-edge connectivity;
for (size_t i = 0; i < ne; ++i) {
const auto &e = edges[i];
if (e.size() != 2) throw std::runtime_error("Invalid element; all elements must be lines");
incidentEdges[e[0]].at(valence.at(e[0])++) = i;
incidentEdges[e[1]].at(valence.at(e[1])++) = i;
}
// Generate a rod segment for each edge.
for (const auto &e : edges) {
m_segments.emplace_back(vertices[e[0]].point,
vertices[e[1]].point,
subdivision);
}
// Generate joints at the valence 2, 3, and 4 vertices.
size_t firstJointVtx = NONE; // Index of a vertex corresponding to a joint (used to initiate BFS below)
std::vector<size_t> jointForVertex(nv, size_t(NONE));
for (size_t vi = 0; vi < nv; ++vi) {
const size_t jointValence = valence[vi];
if (jointValence == 1) continue; // free end; no joint
if (jointValence > 4) throw std::runtime_error("Invalid vertex valence " + std::to_string(valence[vi]) + "; must be 1, 2, 3, or 4");
// Valence 2, 3, or 4:
if (firstJointVtx == NONE) firstJointVtx = vi;
// Group the incident edges into pairs that connect to form
// mostly-straight rods
// Do this by considering the *outward-pointing* edge vectors:
std::array<Vec3, 4> edgeVecs;
std::array<Real_, 4> edgeVecLens;
std::array<bool, 4> isStartPt;
for (size_t k = 0; k < jointValence; ++k) {
const auto &e = edges.at(incidentEdges[vi][k]);
edgeVecs[k] = vertices[e[1]].point - vertices[e[0]].point;
edgeVecLens[k] = edgeVecs[k].norm();
edgeVecs[k] /= edgeVecLens[k];
isStartPt[k] = (e[0] == vi);
if (isStartPt[k]) continue;
assert(e[1] == vi);
edgeVecs[k] *= -1.0;
}
// Partition the segments into those forming "Rod A" and those forming "Rod B"
std::array<size_t, 2> segmentsA{{NONE, NONE}}, segmentsB{{NONE, NONE}};
size_t numA = 0, numB = 0;
std::array<bool, 2> isStartA{{false, false}}, isStartB{{false, false}};
if (jointValence == 2) {
// There are no continuation edges if the valence is 2; one segment belongs to "Rod A" and the other to "Rod B"
// No terminal edge averaging needs to be done.
numA = numB = 1;
segmentsA[0] = 0, segmentsB[0] = 1;
}
if (jointValence == 3) {
// Determine which two of the 3 incident edges best connect to form Rod A
// (Try to pick the two that connect the straightest, but verify that this
// preserves a quad topology; if not, the straigtest valid connection must be made.)
Real_ minCosTheta = safe_numeric_limits<Real_>::max();
for (size_t j = 0; j < jointValence; ++j) {
for (size_t k = j + 1; k < jointValence; ++k) {
Real_ cosTheta = edgeVecs[j].dot(edgeVecs[k]);
if (cosTheta < minCosTheta) {
// Check if connecting edges (j, k) creates a triangle
// instead of a quad. This happens if the joints
// connected by edges j and k have neighborhoods that
// share more than "vi" in commmon.
auto get_neighbor = [&edges,&incidentEdges](size_t v, size_t local_eidx) {
const auto &e = edges[incidentEdges[v][local_eidx]];
if (e[0] == v) return e[1];
if (e[1] == v) return e[0];
throw std::runtime_error("Edge is not incident v!");
};
const size_t vj = get_neighbor(vi, j),
vk = get_neighbor(vi, k);
std::vector<size_t> nj, nk;
for (size_t i = 0; i < valence[vj]; ++i) { nj.push_back(get_neighbor(vj, i)); }
for (size_t i = 0; i < valence[vk]; ++i) { nk.push_back(get_neighbor(vk, i)); }
std::sort(nj.begin(), nj.end());
std::sort(nk.begin(), nk.end());
std::vector<size_t> nboth;
std::set_intersection(nj.begin(), nj.end(), nk.begin(), nk.end(), std::back_inserter(nboth));
if (nboth.size() > 1) continue; // connecting (j, k) forms a triangle; forbid it.
minCosTheta = cosTheta;
segmentsA[0] = j; segmentsA[1] = k;
}
}
}
if (segmentsA[0] == NONE) throw std::runtime_error("Failed to link up valence 3 vertex (without creating triangles)");
numA = 2; numB = 1;
segmentsB[0] = 3 - (segmentsA[0] + segmentsA[1]); // all indices add up to 3; complement by subtraction
}
if (jointValence == 4) {
// Order the edges clockwise around the joint normal and assign them alternating rod labels A, B, A, B.
// First choose a joint normal by crossing the two vectors that are closest to perpendicular
Vec3 n = Vec3::Zero();
for (size_t k = 1; k < jointValence; ++k) {
Vec3 a2 = edgeVecs[k].cross(edgeVecs[0]);
if (a2.squaredNorm() > n.squaredNorm()) n = a2;
}
n.normalize();
// Next, compute the angles between edge 0 and every other edge.
std::array<Real_, 3> angles;
Vec3 v0 = edgeVecs[0] - n * n.dot(edgeVecs[0]);
for (size_t k = 1; k < jointValence; ++k) {
Vec3 vk = edgeVecs[k] - n * n.dot(edgeVecs[k]);
Real_ theta = angle(n, v0, vk); // angle in [-pi, pi]
if (theta < 0) theta += 2.0 * M_PI; // compute angle in [0, 2 pi]
angles[k - 1] = theta;
}
// Sort vectors 1, 2, 3 clockwise (ascending angle wrt vector 0), assign alternating labels
std::vector<size_t> p = sortPermutation(angles); // sorted list: [angles[p[0]], angles[p[1]], angles[p[2]]]
segmentsA = {{ 0, 1 + p[1] }};
segmentsB = {{ 1 + p[0], 1 + p[2] }};
numA = numB = 2;
}
for (size_t k = 0; k < numA; ++k) isStartA[k] = isStartPt[segmentsA[k]];
for (size_t k = 0; k < numB; ++k) isStartB[k] = isStartPt[segmentsB[k]];
// Determine this joint's edge vectors for rod A and rod B. If there's only one
// segment for a rod A or B at this joint, then the terminal edge of this segment gives this
// vector (up to sign). If there are two connecting segments, we must construct an averaged vector.
// In all cases, we construct the edge that points out of segment 0 and into segment 1.
// This vector is scaled to be the smallest of the two participating edges (to prevent inversions of the adjacent rod edges).
// Note: this averaging/scaling operation will change the rest
// length of the neighboring edges, so rod segments' rest lengths
// will need to be recomputed.
Vec3 edgeA = -edgeVecs[segmentsA[0]], edgeB = -edgeVecs[segmentsB[0]]; // get vector pointing out of segment 0
Real_ segmentFracLen = 1.0 / (subdivision - 1); // only (subdivision - 1) segment lengths fit between the endpoints; rod extends half a segment past each endpoint.
Real_ lenA = edgeVecLens[segmentsA[0]] * segmentFracLen,
lenB = edgeVecLens[segmentsB[0]] * segmentFracLen;
if (numA == 2) {
lenA = std::min<Real_>(lenA, edgeVecLens[segmentsA[1]] * segmentFracLen);
edgeA += edgeVecs[segmentsA[1]];
}
if (numB == 2) {
lenB = std::min<Real_>(lenB, edgeVecLens[segmentsB[1]] * segmentFracLen);
edgeB += edgeVecs[segmentsB[1]];
}
edgeA *= lenA / edgeA.norm();
edgeB *= lenB / edgeB.norm();
// Convert to global segment indices
for (size_t k = 0; k < numA; ++k) segmentsA[k] = incidentEdges[vi][segmentsA[k]];
for (size_t k = 0; k < numB; ++k) segmentsB[k] = incidentEdges[vi][segmentsB[k]];
const size_t ji = m_joints.size();
jointForVertex[vi] = ji;
m_joints.emplace_back(this, vertices[vi].point, edgeA, edgeB, segmentsA, segmentsB, isStartA, isStartB);
// Link the incident segments to this joint.
for (size_t k = 0; k < jointValence; ++k) {
auto &s = m_segments.at(incidentEdges[vi][k]);
if (isStartPt[k]) s.startJoint = ji;
else s.endJoint = ji;
}
}
if (firstJointVtx == NONE)
throw std::runtime_error("There must be at least one joint in the network");
// Propagate consistent joint normals throughout the graph using BFS
// (to prevent 180 degree twists); warn if the graph is disconnected.
{
std::queue<size_t> bfsQueue;
std::vector<bool> visited(nv, false);
visited[firstJointVtx] = true;
bfsQueue.push(firstJointVtx);
size_t numVisited = 1;
while (!bfsQueue.empty()) {
size_t u = bfsQueue.front();
size_t ju = jointForVertex[u];
assert(ju != NONE);
bfsQueue.pop();
for (size_t k = 0; k < valence[u]; ++k) {
const auto &e = edges.at(incidentEdges[u][k]);
assert((e[0] == u) != (e[1] == u));
const size_t v = (e[0] == u) ? e[1] : e[0];
if (visited.at(v)) continue;
visited[v] = true;
++numVisited;
size_t jv = jointForVertex[v];
if (jv == NONE) continue; // terminate search at valence 1 vertices
m_joints.at(jv).makeNormalConsistent(m_joints.at(ju));
bfsQueue.push(v);
}
}
if (numVisited != nv) throw std::runtime_error("Disconnected edge graph");
}
// Propagate consistent joint opening angle definitions throughout the graph:
// +----------------------+
// | B\.-./A A\ / |
// | \ / \ / |
// | X vs ( X |
// | / \ / \ |
// | / \ B/ \ |
// +----------------------+
// This is equivalent to ensuring the "A" rods of one joint connect with the
// "A" rods of its neighbors. This angle consistency is needed so that all
// angles change in the same direction during deployment/closing (permitting
// actuation by an average target angle constraint).
// We pick the definition that makes the majority of angles acute.
{
// Try to make all joints consistent with the first.
std::queue<size_t> bfsQueue;
std::vector<size_t> prev(numJoints(), size_t(NONE)); // visited array, also allowing path recovery for debugging
prev[0] = 0;
bfsQueue.push(0);
while (!bfsQueue.empty()) {
size_t u = bfsQueue.front();
bfsQueue.pop();
const auto &ju = m_joints.at(u);
for (size_t AB_u = 0; AB_u < 2; ++AB_u) { // Separately visit neighbors connected along "A" (AB_u = 0) and "B" (AB_u = 1)
ju.visitNeighbors(
[&](size_t v, size_t /* si */, size_t AB_v) {
bool consistent = AB_u == AB_v;
if (prev[v] != NONE) {
// joint "v" has already been visited/set. If it
// is not already consistent, our strategy has failed.
if (!consistent && initConsistentAngle) {
// Output debugging information about the two inconsistent BFS paths.
auto reportPath = [&](size_t v) {
while (v != 0) {
std::cout << v;
size_t p = prev.at(v);
const auto &jv = m_joints.at(v);
jv.visitNeighbors([p,&jv](size_t ji, size_t si, size_t AB) { if (ji == p) std::cout << "--" << si << "(" << char(jv.segmentABOffset(si) + 'A') << ", " << char(AB + 'A') << ")--"; });
v = p;
}
std::cout << 0 << std::endl;
};
std::cout << "Trying to set " << v << " from path:" << std::endl;
reportPath(u);
std::cout << "Inconsistent with earlier path:" << std::endl;
reportPath(v);
throw std::runtime_error("Propagating consistent angle definitions failed");
}
return;
}
prev[v] = u;
bfsQueue.push(v);
if (!consistent) m_joints.at(v).swapAngleDefinition();
}, AB_u);
}
}
// Choose joint definitions so that the majority are acute.
size_t numAcute = 0;
for (const auto &ju : m_joints) {
if (ju.alpha() < 0) throw std::runtime_error("Negative joint angle");
if (ju.alpha() < M_PI / 2) ++numAcute;
}
if (numAcute < (numJoints() - numAcute))
for (auto &ju : m_joints) ju.swapAngleDefinition();
}
////////////////////////////////////////////////////////////////////////////
// Rest length/point spacing initialization
////////////////////////////////////////////////////////////////////////////
// Initial guess for the length of each segment: straight line distance
VecX segmentRestLenGuess(ne);
for (size_t i = 0; i < ne; ++i) {
const auto &e = edges[i];
segmentRestLenGuess[i] = (vertices[e[1]].point - vertices[e[0]].point).norm();
}
// Build the segment len->edge len map and use it to construct
// the rest length guess for every edge in the network
m_constructSegmentRestLenToEdgeRestLenMapTranspose(segmentRestLenGuess);
m_perSegmentRestLen = segmentRestLenGuess;
m_setRestLengthsFromPSRL();
// Initialize the DoF offset table (no constraints yet).
m_buildDoFOffsets();
// Also set a reasonable initialization for the deformed configuration
auto params = getDoFs();
setDoFs(params, true /* set spatially coherent thetas */);
// The terminal edges of each segment have been twisted to conform to
// the joints, but the internal edges are in their default orientation.
// We update the edges' material axes (thetas) by minimizing the twist
// energy with respect to the thetas.
for (auto &s : m_segments)
s.setMinimalTwistThetas();
// Update the "source thetas" used to maintain temporal coherence
updateSourceFrame();
// Use the linkage's cached material to initialize each rod's material.
setMaterial(m_material);
m_initMinRestLen = minRestLength();
m_clearCache();
}
template<typename Real_>
void RodLinkage_T<Real_>::m_setRestLengthsFromPSRL() {
if (m_segmentRestLenToEdgeRestLenMapTranspose.m == 0) throw std::runtime_error("Must run m_constructSegmentRestLenToEdgeRestLenMapTranspose first");
VecX restLens = m_segmentRestLenToEdgeRestLenMapTranspose.apply(m_perSegmentRestLen, /* transpose */ true);
// {
// std::ofstream rlens_file("rlens.txt");
// rlens_file.precision(16);
// rlens_file << restLens << std::endl;
// }
// Apply these rest lengths to the linkage.
size_t offset = 0;
for (auto &s : m_segments) {
const size_t ne = s.rod.numEdges();
// Visit each internal/free edge:
for (size_t ei = s.hasStartJoint(); ei < (s.hasEndJoint() ? ne - 1 : ne); ++ei)
s.rod.restLengthForEdge(ei) = restLens[offset++];
}
// {
// std::ofstream rlens_file("pre_joint_edge_rlens.txt");
// rlens_file.precision(16);
// for (auto &s : m_segments) {
// for (auto rl : s.rod.restLengths())
// rlens_file << rl << std::endl;
// }
// }
// std::ofstream jdebug_file("joint_len_debug.txt");
for (auto &j : m_joints) {
// jdebug_file << "Setting rlens " << restLens.template segment<2>(offset).transpose() << std::endl;
// jdebug_file << "segmentsA: " << j.segmentsA()[0] << " " << j.segmentsA()[1] << ", segmentsB:" << j.segmentsB()[0] << " " << j.segmentsB()[1] << "\t";
// jdebug_file << "isStartA: " << j.isStartA() [0] << " " << j.isStartA() [1] << ", isStartB: " << j.isStartB() [0] << " " << j.isStartB() [1] << std::endl;
j.setRestLengths(restLens.template segment<2>(offset));
offset += 2;
}
// {
// std::ofstream rlens_file("edge_rlens.txt");
// rlens_file.precision(16);
// for (auto &s : m_segments) {
// for (auto rl : s.rod.restLengths())
// rlens_file << rl << std::endl;
// }
// }
assert(offset = size_t(restLens.size()));
}
template<typename Real_>
void RodLinkage_T<Real_>::m_buildDoFOffsets() {
m_dofOffsetForSegment.resize(m_segments.size());
m_dofOffsetForJoint.resize(m_joints.size());
size_t offset = 0;
for (size_t i = 0; i < numSegments(); ++i) {
m_dofOffsetForSegment[i] = offset;
offset += m_segments[i].numDoF();
}
for (size_t i = 0; i < numJoints(); ++i) {
m_dofOffsetForJoint[i] = offset;
offset += m_joints[i].numDoF();
}
m_restLenDoFOffsetForSegment.resize(m_segments.size());
for (size_t i = 0; i < numSegments(); ++i) {
m_restLenDoFOffsetForSegment[i] = offset;
offset += m_segments[i].numFreeEdges();
}
m_restLenDoFOffsetForJoint.resize(m_joints.size());
for (size_t i = 0; i < numJoints(); ++i) {
m_restLenDoFOffsetForJoint[i] = offset;
offset += 2;
}
}
// Construct the *transpose* of the map from a vector holding the (rest) lengths
// of each segment to a vector holding a (rest) length for every rod length in the
// entire network. The vector output by this map is ordered as follows: all
// lengths for segments' interior and free edges, followed by two lengths for each joint.
// (We use build the transpose instead of the map itself to efficiently support
// the iteration needed to assemble the Hessian chain rule term)
// This is a fixed linear map for the lifetime of the linkage, though
// it depends on the initial distribution of segment lengths:
// to prevent edge "flips" when a long edge meets a short edge at a joint, we
// use the minimum of the two lengths to define the joint edge length. To
// prevent the map from being non-differentiable, we decide at linkage
// construction time which the "short" edge is. (Another solution would be to
// use a soft minimum, but this would require computing an additional Hessian
// term). We finally space the remaining length evenly across the unconstrained
// edges.
template<typename Real_>
void RodLinkage_T<Real_>::m_constructSegmentRestLenToEdgeRestLenMapTranspose(const VecX_T<Real_> &segmentRestLenGuess) {
assert(size_t(segmentRestLenGuess.size()) == numSegments());
// Get the initial ideal rest length for the edges of each segment; this is
// used to decide which segments control which terminal edges.
VecX idealEdgeLenForSegment(numSegments());
std::vector<size_t> numEdgesForSegment(numSegments());
for (size_t si = 0; si < numSegments(); ++si) {
numEdgesForSegment[si] = segment(si).rod.numEdges();
idealEdgeLenForSegment[si] = segmentRestLenGuess[si] / (numEdgesForSegment[si] - 1.0);
}
// Decide who controls each joint edge: the shorter ideal rest length
// wins. Ties are broken arbitrarily.
std::vector<std::array<size_t, 2>> controllersForJoint(numJoints());
for (size_t ji = 0; ji < numJoints(); ++ji) {
const auto &j = joint(ji);
auto &c = controllersForJoint[ji];
const auto &sA = j.segmentsA(); const auto &sB = j.segmentsB();
c[0] = sA[0];
c[1] = sB[0];
if ((sA[1] != NONE) && (idealEdgeLenForSegment[sA[1]] < idealEdgeLenForSegment[c[0]])) c[0] = sA[1];
if ((sB[1] != NONE) && (idealEdgeLenForSegment[sB[1]] < idealEdgeLenForSegment[c[1]])) c[1] = sB[1];
}
// Determine the number of nonzeros in the map.
// Each free edge in a segment segment is potentially influenced by segment
// lengths in the stencil:
// +-----+-----+-----+
// ^
// (The segment always influences its own edges, but neighbors controlling the incident
// joints influence the edges too).
size_t totalFreeEdges = 0;
size_t nz = 0;
// Count the entries in the columns corresponding to segments' internal/free ends
for (size_t si = 0; si < numSegments(); ++si) {
const auto &s = segment(si);
const size_t numFreeEdges = numEdgesForSegment[si] - s.hasStartJoint() - s.hasEndJoint();
totalFreeEdges += numFreeEdges;
nz += numFreeEdges; // The segment influences all of its own free edges.
// A controlling neighbor also influences all of the free edges:
auto processJoint = [&](size_t ji) {
if (ji == NONE) return;
const auto &j = joint(ji);
size_t controller = controllersForJoint[ji][j.segmentABOffset(si)];
assert(controller != NONE);
if (controller != si) nz += numFreeEdges;
};
processJoint(s.startJoint);
processJoint(s.endJoint);
}
// The two columns for each joint have only a single entry (one controlling segment)
nz += numJoints() * 2;
const SuiteSparse_long m = numSegments(), n = totalFreeEdges + 2 * numJoints();
CSCMat result(m, n);
result.nz = nz;
// Now we fill out the transpose of the map one column (edge) at a time:
// # [ ]
// segments [ ]
// # edges
auto &Ai = result.Ai;
auto &Ax = result.Ax;
auto &Ap = result.Ap;
Ai.reserve(nz);
Ax.reserve(nz);
Ap.reserve(n + 1);
Ap.push_back(0); // col 0 begin
// Segments are split into (ne - 1) intervals spanning between
// the incident joint positions (graph nodes); half an interval
// extends past the joints at each end.
// Joints control the lengths of the intervals surrounding them,
// specifying the length of half a subdivision interval on the incident
// segments. The remaining length of each segment is then
// distributed evenly across the "free" intervals.
// First, build the columns for the free edges of each segment:
for (size_t si = 0; si < numSegments(); ++si) {
const auto &s = segment(si);
// Determine the influencers for each internal/free edge length on this segment.
struct Influence {
size_t idx = NONE;
Real_ val = 0;
bool operator<(const Influence &b) const { return idx < b.idx; }
};
std::array<Influence, 3> infl;
const size_t ne = numEdgesForSegment[si];
const Real_ numFreeIntervals = (ne - 1) - 0.5 * (s.hasEndJoint() + s.hasStartJoint());
infl[0].idx = si;
infl[0].val = 1.0 / numFreeIntervals; // length is distributed evenly across the free intervals
// The incident joint edges subtract half their length from the amount
// distributed to the free intervals.
auto processJoint = [&](size_t lji) {
size_t ji = s.joint(lji);
if (ji == NONE) return;
const auto &j = joint(ji);
size_t c = controllersForJoint[ji][j.segmentABOffset(si)];
assert(c != NONE);
if (c == si) { infl[0].val -= (0.5 * (1.0 / (ne - 1))) / numFreeIntervals; return; }
infl[lji + 1].idx = c;
infl[lji + 1].val = -(0.5 * (1.0 / (numEdgesForSegment[c] - 1))) / numFreeIntervals;
};
processJoint(0);
processJoint(1);
std::sort(infl.begin(), infl.end());
// Visit each internal/free edge:
for (size_t ei = s.hasStartJoint(); ei < (s.hasEndJoint() ? ne - 1 : ne); ++ei) {
// Add entries for each present influencer.
for (size_t i = 0; i < 3; ++i) {
if (infl[i].idx == NONE) continue;
Ai.push_back(infl[i].idx);
Ax.push_back(infl[i].val);
}
Ap.push_back(Ai.size()); // col end
}
}
// Build the columns for the joint edges
for (size_t ji = 0; ji < numJoints(); ++ji) {
for (size_t ab = 0; ab < 2; ++ab) {
const size_t c = controllersForJoint[ji][ab];
Ai.push_back(c);
Ax.push_back(1.0 / (numEdgesForSegment[c] - 1));
Ap.push_back(Ai.size()); // col end
}
}
assert(Ax.size() == size_t(nz ));
assert(Ai.size() == size_t(nz ));
assert(Ap.size() == size_t(n + 1));
m_segmentRestLenToEdgeRestLenMapTranspose = std::move(result);
}
template<typename Real_>
void RodLinkage_T<Real_>::setMaterial(const RodMaterial &material) {
m_material = material;
for (auto &s : m_segments) {
auto &rod = s.rod;
rod.setMaterial(material);
// Avoid double-counting stiffness/mass for edges shared at the joints.
if (s.startJoint != NONE) rod.density(0) = 0.5;
if (s. endJoint != NONE) rod.density(rod.numEdges() - 1) = 0.5;
}
}
template<typename Real_>
void RodLinkage_T<Real_>::setStretchingStiffness(Real_ val) {
for (auto &s : m_segments) {
auto &rod = s.rod;
const size_t ne = rod.numEdges();
for (size_t j = 0; j < ne; ++j)
rod.stretchingStiffness(j) = val;
}
}
template<typename Real_>
size_t RodLinkage_T<Real_>::numDoF() const {
size_t result = 0;
for (const auto &s : m_segments) result += s.numDoF();
for (const auto &j : m_joints) result += j.numDoF();
return result;
}
// Full parameters consist of all segment parameters followed by all joint parameters.
template<typename Real_>
VecX_T<Real_> RodLinkage_T<Real_>::getDoFs() const {
const size_t n = numDoF();
VecX params(n);
for (size_t i = 0; i < numSegments(); ++i) { auto slice = params.segment(m_dofOffsetForSegment[i], m_segments[i].numDoF()); m_segments[i].getParameters(slice); }
for (size_t i = 0; i < numJoints() ; ++i) { auto slice = params.segment(m_dofOffsetForJoint [i], m_joints [i].numDoF()); m_joints [i].getParameters(slice); }
return params;
}
// Full parameters consist of all segment parameters followed by all joint parameters.
// "spatialCoherence" affects how terminal edge thetas are determined from the
// joint parameters; see joint.applyConfiguration.
template<typename Real_>
void RodLinkage_T<Real_>::setDoFs(const Eigen::Ref<const VecX> ¶ms, bool spatialCoherence) {
BENCHMARK_START_TIMER_SECTION("RodLinkage setDoFs");
const size_t n = numDoF();
if (size_t(params.size()) != n) throw std::runtime_error("Invalid number of parameters");
const size_t ns = m_segments.size();
m_networkPoints.resize(ns);
m_networkThetas.resize(ns);
// First, unpack the segment parameters into the points/thetas arrays
auto processSegment = [&](size_t si) {
auto slice = params.segment(m_dofOffsetForSegment[si], m_segments[si].numDoF());
m_segments[si].unpackParameters(slice, m_networkPoints[si], m_networkThetas[si]);
};
#if MESHFEM_WITH_TBB
tbb::parallel_for(tbb::blocked_range<size_t>(0, ns), [&](const tbb::blocked_range<size_t> &b) { for (size_t si = b.begin(); si < b.end(); ++si) processSegment(si); });
#else
for (size_t si = 0; si < ns; ++si) processSegment(si);
#endif
// Second, set all joint parameters and then
// use them to configure the segments' terminal edges.
const size_t nj = m_joints.size();
auto processJoint = [&](size_t ji) {
m_joints[ji].setParameters(params.segment(m_dofOffsetForJoint[ji], m_joints[ji].numDoF()));
m_joints[ji].applyConfiguration(m_segments, m_networkPoints, m_networkThetas, spatialCoherence);
};
#if MESHFEM_WITH_TBB
tbb::parallel_for(tbb::blocked_range<size_t>(0, nj), [&](const tbb::blocked_range<size_t> &b) { for (size_t ji = b.begin(); ji < b.end(); ++ji) processJoint(ji); });
#else
for (size_t ji = 0; ji < nj; ++ji) processJoint(ji);
#endif
// Finally, set the deformed state of each rod in the network
#if MESHFEM_WITH_TBB
tbb::parallel_for(tbb::blocked_range<size_t>(0, ns), [&](const tbb::blocked_range<size_t> &b) { for (size_t i = b.begin(); i < b.end(); ++i) m_segments[i].rod.setDeformedConfiguration(m_networkPoints[i], m_networkThetas[i]); });
#else
for (size_t i = 0; i < ns; ++i) m_segments[i].rod.setDeformedConfiguration(m_networkPoints[i], m_networkThetas[i]);
#endif
m_sensitivityCache.clear();
BENCHMARK_STOP_TIMER_SECTION("RodLinkage setDoFs");
}
////////////////////////////////////////////////////////////////////////////////
// Extended degrees of freedom: deformed configuration + rest lengths.
////////////////////////////////////////////////////////////////////////////////
template<typename Real_>
size_t RodLinkage_T<Real_>::numRestLengths() const {
size_t result = 0;
// A rest length for every free (non-joint) edge of each segment.
for (const auto &s : m_segments) result += s.numFreeEdges();
// Two rest lengths for each joint (one for segment A, one for B)
result += 2 * numJoints();
return result;
}
template<typename Real_>
VecX_T<Real_> RodLinkage_T<Real_>::getRestLengths() const {
VecX result(numRestLengths());
// A rest length for every free (non-joint) edge of each segment.
size_t offset = 0;
for (const auto &s : m_segments) {
auto rlens = s.rod.restLengths();
const size_t nfe = s.numFreeEdges();
result.segment(offset, nfe) = Eigen::Map<VecX>(rlens.data(), rlens.size()).segment(s.hasStartJoint(), nfe);
offset += nfe;
}
for (const auto &j : m_joints) {
result.segment(offset, 2) = j.getRestLengths();
offset += 2;
}
return result;
}
template<typename Real_>
VecX_T<Real_> RodLinkage_T<Real_>::getExtendedDoFs() const {
VecX result(numExtendedDoF());
result.segment(0, numDoF()) = getDoFs();
result.segment(numDoF(), numRestLengths()) = getRestLengths();
return result;
}
template<typename Real_>
void RodLinkage_T<Real_>::setExtendedDoFs(const VecX_T<Real_> ¶ms, bool spatialCoherence) {
if (size_t(params.size()) != numExtendedDoF()) throw std::runtime_error("Extended DoF size mismatch");
size_t offset = numDoF();
setDoFs(params.segment(0, offset), spatialCoherence);
// A rest length for every free (non-joint) edge of each segment.
for (auto &s : m_segments) {
auto rlens = s.rod.restLengths();
const size_t nfe = s.numFreeEdges();
Eigen::Map<VecX>(rlens.data(), rlens.size()).segment(s.hasStartJoint(), nfe) = params.segment(offset, nfe);
s.rod.setRestLengths(rlens);
offset += nfe;
}
for (auto &j : m_joints) {
j.setRestLengths(params.segment(offset, 2));
offset += 2;
}
}
////////////////////////////////////////////////////////////////////////////////
// Joint operations
////////////////////////////////////////////////////////////////////////////////
template<typename Real_>
RodLinkage_T<Real_>::Joint::Joint(RodLinkage_T *l, const Pt3 &p, const Vec3 &eA, const Vec3 &eB,
const std::array<size_t, 2> segmentsA, const std::array<size_t, 2> segmentsB,
const std::array<bool , 2> isStartA, const std::array<bool , 2> isStartB)
: m_linkage(l), m_pos(p),
m_segmentsA(segmentsA), m_segmentsB(segmentsB),
m_isStartA(isStartA), m_isStartB(isStartB)
{
if ((segmentsA[0] == RodLinkage::NONE) || (segmentsB[0] == RodLinkage::NONE))
throw std::runtime_error("First segment must exist for each rod incident this joint");
m_len_A = eA.norm();
m_len_B = eB.norm();
Vec3 tA = eA / m_len_A,
tB = eB / m_len_B;
// Pick the sign of edge vector B so that angle "alpha" between edge vectors A and B is
// acute, not obtuse.
m_sign_B = std::copysign(1.0, stripAutoDiff(tA.dot(tB)));
tB *= m_sign_B;
m_source_normal = tA.cross(tB);
Real_ sin_alpha = m_source_normal.norm();
m_source_normal /= sin_alpha;
// Compute angle bisector "t"; the joint's orientation will be described by frame (t | n x t | n)
m_source_t = tA + tB;
assert(m_source_t.norm() > 1e-8); // B's sign was chosen to make alpha acute...
m_source_t.normalize();
m_alpha = asin(sin_alpha); // always in [0, pi/2]
m_omega.setZero();
m_update();
}
template<typename Real_>
template<class Derived>
void RodLinkage_T<Real_>::Joint::setParameters(const Eigen::DenseBase<Derived> &vars) {
if (size_t(vars.size()) < numDoF()) throw std::runtime_error("DoF indices out of bounds");
// 9 parameters: position, omega, alpha, len a, len b
m_pos = vars.template segment<3>(0);
m_omega = vars.template segment<3>(3);
m_alpha = vars[6];
m_len_A = vars[7];
m_len_B = vars[8];
m_update();
}
template<typename Real_>
template<class Derived>
void RodLinkage_T<Real_>::Joint::getParameters(Eigen::DenseBase<Derived> &vars) const {
if (size_t(vars.size()) < numDoF()) throw std::runtime_error("DoF indices out of bounds");
// 9 parameters: position, omega, alpha, len a, len b
vars.template segment<3>(0) = m_pos;
vars.template segment<3>(3) = m_omega;
vars[6] = m_alpha;
vars[7] = m_len_A;
vars[8] = m_len_B;
}
// Update the network's full collection of rod points and twist angles with the
// values determined by this joint's configuration (editing only the values
// related to the incident terminal rod edges).
// The "rodSegments" are needed to compute material frame angles from the
// material axis vector.
// "spatialCoherence" determines whether the 2Pi offset ambiguity in theta is
// resolved by minimizing twisting energy (true) or minimizing the change made (temporal coherence; false)
template<typename Real_>
void RodLinkage_T<Real_>::Joint::applyConfiguration(const std::vector<RodSegment> &rodSegments,
std::vector<std::vector<Pt3>> &networkPoints,
std::vector<std::vector<Real_>> &networkThetas,
bool spatialCoherence) const {
// Vector "e" always points outward from the joint into/along the rod.
auto configureEdge = [&](Vec3 e, bool isStart, const ElasticRod_T<Real_> &rod, std::vector<Pt3> &pts, std::vector<Real_> &thetas) {
const size_t nv = pts.size();
const size_t ne = thetas.size();
assert(nv == rod.numVertices());
assert(ne == rod.numEdges());
// Orient "e" so that it agrees with the rod orientation (points into start/out of end)
// (e is now the scaled tangent vector of the new edge).
if (!isStart) e *= -1.0;
pts[isStart ? 0 : nv - 2] = m_pos - 0.5 * e;
pts[isStart ? 1 : nv - 1] = m_pos + 0.5 * e;
// Material axis d2 is given by the normal vector.
const size_t edgeIdx = isStart ? 0 : ne - 1;
thetas[edgeIdx] = rod.thetaForMaterialFrameD2(m_normal, e, edgeIdx, spatialCoherence);
};
// Configure segment 0 of each rod: edge vectors m_e_[AB] point OUT of
// segment 0, while configureEdge expects an inward-pointing vector
configureEdge(-m_e_A, m_isStartA[0], rodSegments[m_segmentsA[0]].rod, networkPoints[m_segmentsA[0]], networkThetas[m_segmentsA[0]]);
configureEdge(-m_e_B, m_isStartB[0], rodSegments[m_segmentsB[0]].rod, networkPoints[m_segmentsB[0]], networkThetas[m_segmentsB[0]]);
// Configure segment 1, if it exists.
if (m_segmentsA[1] != NONE) configureEdge(m_e_A, m_isStartA[1], rodSegments[m_segmentsA[1]].rod, networkPoints[m_segmentsA[1]], networkThetas[m_segmentsA[1]]);
if (m_segmentsB[1] != NONE) configureEdge(m_e_B, m_isStartB[1], rodSegments[m_segmentsB[1]].rod, networkPoints[m_segmentsB[1]], networkThetas[m_segmentsB[1]]);
}
// Update cache; to be called whenever the edge vectors change.
template<typename Real_>
void RodLinkage_T<Real_>::Joint::m_update() {
Mat3 source_config; // non-orthogonal frame formed by the two edge tangent and the normal
source_config.col(0) = source_t_A();
source_config.col(1) = source_t_B();
source_config.col(2) = m_source_normal;
Mat3 curr_config = ropt::rotated_matrix(m_omega, source_config);
m_e_A = curr_config.col(0) * m_len_A;
m_e_B = curr_config.col(1) * m_len_B;
m_normal = curr_config.col(2);
}
// +-----------------------+
// | B A A -B |
// | \.-./ \ / |
// | \ / \ / |
// | X ==> ( X |
// | / \ / \ |
// | / \ / \ |
// | B |
// +-----------------------+
// Change the definition of alpha, replacing it with its complement.
// This also exchanges the labels of A and B (changing B's sign to avoid flipping the normal)
// and rotates the bisector by pi/2.
template<typename Real_>
void RodLinkage_T<Real_>::Joint::swapAngleDefinition() {
std::swap(m_segmentsA, m_segmentsB);
std::swap(m_isStartA, m_isStartB);
std::swap(m_len_A, m_len_B);
m_source_t = m_sign_B * m_source_normal.cross(m_source_t);
m_sign_B *= -1;
m_alpha = M_PI - m_alpha;
m_update(); // swap cached m_e_A and m_e_B
}
////////////////////////////////////////////////////////////////////////////////
// Rod segment operations
////////////////////////////////////////////////////////////////////////////////
// Construct the initial rest points for a rod; note that the endpoints will be
// repositioned if the rod connects at a joint.
template<typename Real_>
std::vector<Pt3_T<Real_>> constructInitialRestPoints(const Pt3_T<Real_> &startPt, const Pt3_T<Real_> &endPt, size_t nsubdiv) {
if (nsubdiv < 5)
throw std::runtime_error("Rods in a linkage must have at least 5 edges (to prevent conflicting start/end joint constraints and fully separate joint influences in Hessian)");
// Half an edge will extend past each endpoint, so only (nsubdiv - 1) edges
// fit between the endpoints.
std::vector<Pt3_T<Real_>> rodPts;
for (size_t i = 0; i <= nsubdiv; ++i) {
Real_ alpha = (i - 0.5) / (nsubdiv - 1);
rodPts.push_back((1 - alpha) * startPt + alpha * endPt);
}
return rodPts;
}
template<typename Real_>
RodLinkage_T<Real_>::RodSegment::RodSegment(const Pt3 &startPt, const Pt3 &endPt, size_t nsubdiv)
: rod(constructInitialRestPoints(startPt, endPt, nsubdiv)) { }
template<typename Real_>
template<class Derived>
void RodLinkage_T<Real_>::RodSegment::unpackParameters(const Eigen::DenseBase<Derived> &vars,
std::vector<Pt3 > &points,
std::vector<Real_> &thetas) const {
if (numDoF() > size_t(vars.size())) throw std::runtime_error("DoF indices out of bounds");
const size_t nv = rod.numVertices(), ne = rod.numEdges();
points.resize(nv);
thetas.resize(ne);
size_t offset = 0;
// Set the centerline position degrees of freedom
for (size_t i = 0; i < nv; ++i) {
// The first/last edge don't contribute degrees of freedom if they're part of a joint.
if ((i < 2) && (startJoint != NONE)) continue;
if ((i >= nv - 2) && (endJoint != NONE)) continue;
points[i] = vars.template segment<3>(offset);
offset += 3;
}
// Unpack the material axis degrees of freedom
for (size_t j = 0; j < ne; ++j) {
if ((j == 0) && (startJoint != NONE)) continue;
if ((j == ne - 1) && (endJoint != NONE)) continue;
thetas[j] = vars[offset++];
}
}
template<typename Real_>
template<class Derived>
void RodLinkage_T<Real_>::RodSegment::setParameters(const Eigen::DenseBase<Derived> &vars) {
auto points = rod.deformedPoints();
auto thetas = rod.thetas();
unpackParameters(vars, points, thetas);
rod.setDeformedConfiguration(points, thetas);
}
template<typename Real_>
template<class Derived>
void RodLinkage_T<Real_>::RodSegment::getParameters(Eigen::DenseBase<Derived> &vars) const {
if (numDoF() > size_t(vars.size())) throw std::runtime_error("DoF indices out of bounds");
const auto &pts = rod.deformedPoints();
const auto &thetas = rod.thetas();
const size_t nv = rod.numVertices(), ne = rod.numEdges();
size_t offset = 0;
// get the centerline position degrees of freedom
for (size_t i = 0; i < nv; ++i) {
// The first/last edge don't contribute degrees of freedom if they're part of a joint.
if ((i < 2) && (startJoint != NONE)) continue;
if ((i >= nv - 2) && (endJoint != NONE)) continue;
vars.template segment<3>(offset) = pts[i];
offset += 3;
}
// Unpack the material axis degrees of freedom
for (size_t j = 0; j < ne; ++j) {
if ((j == 0) && (startJoint != NONE)) continue;
if ((j == ne - 1) && (endJoint != NONE)) continue;
vars[offset++] = thetas[j];
}
}
template<typename Real_>
void RodLinkage_T<Real_>::RodSegment::setMinimalTwistThetas(bool verbose) {
// Minimize twisting energy wrt theta.
// The twisting energy is quadratic wrt theta, so we simply solve for the
// step bringing the gradient to zero using the equation:
// H dtheta = -g,
// where g and H are the gradient and Hessian of the twisting energy with
// respect to material axis angles.
if ((startJoint == NONE) && (endJoint == NONE))
throw std::runtime_error("Rod with two free ends--system will be rank deficient");
const size_t ne = rod.numEdges();
auto pts = rod.deformedPoints();
auto ths = rod.thetas();
// First, remove any unnecessary twist stored in the rod by rotating the second endpoint
// by an integer multiple of 2PI (leaving d2 unchanged).
Real_ rodRefTwist = 0;
const auto &dc = rod.deformedConfiguration();
for (size_t j = 1; j < ne; ++j)
rodRefTwist += dc.referenceTwist[j];
const size_t lastEdge = ne - 1;
Real_ desiredTheta = ths[0] - rodRefTwist;