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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
|
// This code is in the public domain -- castano@gmail.com
#include "nvmesh.h" // pch
#include "AtlasBuilder.h"
#include "Util.h"
#include "nvmesh/halfedge/Mesh.h"
#include "nvmesh/halfedge/Face.h"
#include "nvmesh/halfedge/Vertex.h"
#include "nvmath/Matrix.inl"
#include "nvmath/Vector.inl"
//#include "nvcore/IntroSort.h"
#include "nvcore/Array.inl"
#include <algorithm> // std::sort
#include <float.h> // FLT_MAX
#include <limits.h> // UINT_MAX
using namespace nv;
namespace
{
// Dummy implementation of a priority queue using sort at insertion.
// - Insertion is o(n)
// - Smallest element goes at the end, so that popping it is o(1).
// - Resorting is n*log(n)
// @@ Number of elements in the queue is usually small, and we'd have to rebalance often. I'm not sure it's worth implementing a heap.
// @@ Searcing at removal would remove the need for sorting when priorities change.
struct PriorityQueue
{
PriorityQueue(uint size = UINT_MAX) : maxSize(size) {}
void push(float priority, uint face) {
uint i = 0;
const uint count = pairs.count();
for (; i < count; i++) {
if (pairs[i].priority > priority) break;
}
Pair p = { priority, face };
pairs.insertAt(i, p);
if (pairs.count() > maxSize) {
pairs.removeAt(0);
}
}
// push face out of order, to be sorted later.
void push(uint face) {
Pair p = { 0.0f, face };
pairs.append(p);
}
uint pop() {
uint f = pairs.back().face;
pairs.pop_back();
return f;
}
void sort() {
//nv::sort(pairs); // @@ My intro sort appears to be much slower than it should!
std::sort(pairs.buffer(), pairs.buffer() + pairs.count());
}
void clear() {
pairs.clear();
}
uint count() const { return pairs.count(); }
float firstPriority() const { return pairs.back().priority; }
const uint maxSize;
struct Pair {
bool operator <(const Pair & p) const { return priority > p.priority; } // !! Sort in inverse priority order!
float priority;
uint face;
};
Array<Pair> pairs;
};
static bool isNormalSeam(const HalfEdge::Edge * edge) {
return (edge->vertex->nor != edge->pair->next->vertex->nor || edge->next->vertex->nor != edge->pair->vertex->nor);
}
static bool isTextureSeam(const HalfEdge::Edge * edge) {
return (edge->vertex->tex != edge->pair->next->vertex->tex || edge->next->vertex->tex != edge->pair->vertex->tex);
}
} // namespace
struct nv::ChartBuildData
{
ChartBuildData(int id) : id(id) {
planeNormal = Vector3(0);
centroid = Vector3(0);
coneAxis = Vector3(0);
coneAngle = 0;
area = 0;
boundaryLength = 0;
normalSum = Vector3(0);
centroidSum = Vector3(0);
}
int id;
// Proxy info:
Vector3 planeNormal;
Vector3 centroid;
Vector3 coneAxis;
float coneAngle;
float area;
float boundaryLength;
Vector3 normalSum;
Vector3 centroidSum;
Array<uint> seeds; // @@ These could be a pointers to the HalfEdge faces directly.
Array<uint> faces;
PriorityQueue candidates;
};
AtlasBuilder::AtlasBuilder(const HalfEdge::Mesh * m) : mesh(m), facesLeft(m->faceCount())
{
const uint faceCount = m->faceCount();
faceChartArray.resize(faceCount, -1);
faceCandidateArray.resize(faceCount, -1);
// @@ Floyd for the whole mesh is too slow. We could compute floyd progressively per patch as the patch grows. We need a better solution to compute most central faces.
//computeShortestPaths();
// Precompute edge lengths and face areas.
uint edgeCount = m->edgeCount();
edgeLengths.resize(edgeCount);
for (uint i = 0; i < edgeCount; i++) {
uint id = m->edgeAt(i)->id;
nvDebugCheck(id / 2 == i);
edgeLengths[i] = m->edgeAt(i)->length();
}
faceAreas.resize(faceCount);
for (uint i = 0; i < faceCount; i++) {
faceAreas[i] = m->faceAt(i)->area();
}
}
AtlasBuilder::~AtlasBuilder()
{
const uint chartCount = chartArray.count();
for (uint i = 0; i < chartCount; i++)
{
delete chartArray[i];
}
}
void AtlasBuilder::markUnchartedFaces(const Array<uint> & unchartedFaces)
{
const uint unchartedFaceCount = unchartedFaces.count();
for (uint i = 0; i < unchartedFaceCount; i++){
uint f = unchartedFaces[i];
faceChartArray[f] = -2;
//faceCandidateArray[f] = -2; // @@ ?
removeCandidate(f);
}
nvDebugCheck(facesLeft >= unchartedFaceCount);
facesLeft -= unchartedFaceCount;
}
void AtlasBuilder::computeShortestPaths()
{
const uint faceCount = mesh->faceCount();
shortestPaths.resize(faceCount*faceCount, FLT_MAX);
// Fill edges:
for (uint i = 0; i < faceCount; i++)
{
shortestPaths[i*faceCount + i] = 0.0f;
const HalfEdge::Face * face_i = mesh->faceAt(i);
Vector3 centroid_i = face_i->centroid();
for (HalfEdge::Face::ConstEdgeIterator it(face_i->edges()); !it.isDone(); it.advance())
{
const HalfEdge::Edge * edge = it.current();
if (!edge->isBoundary())
{
const HalfEdge::Face * face_j = edge->pair->face;
uint j = face_j->id;
Vector3 centroid_j = face_j->centroid();
shortestPaths[i*faceCount + j] = shortestPaths[j*faceCount + i] = length(centroid_i - centroid_j);
}
}
}
// Use Floyd-Warshall algorithm to compute all paths:
for (uint k = 0; k < faceCount; k++)
{
for (uint i = 0; i < faceCount; i++)
{
for (uint j = 0; j < faceCount; j++)
{
shortestPaths[i*faceCount + j] = min(shortestPaths[i*faceCount + j], shortestPaths[i*faceCount + k]+shortestPaths[k*faceCount + j]);
}
}
}
}
void AtlasBuilder::placeSeeds(float threshold, uint maxSeedCount)
{
// Instead of using a predefiened number of seeds:
// - Add seeds one by one, growing chart until a certain treshold.
// - Undo charts and restart growing process.
// @@ How can we give preference to faces far from sharp features as in the LSCM paper?
// - those points can be found using a simple flood filling algorithm.
// - how do we weight the probabilities?
for (uint i = 0; i < maxSeedCount; i++)
{
if (facesLeft == 0) {
// No faces left, stop creating seeds.
break;
}
createRandomChart(threshold);
}
}
void AtlasBuilder::createRandomChart(float threshold)
{
ChartBuildData * chart = new ChartBuildData(chartArray.count());
chartArray.append(chart);
// Pick random face that is not used by any chart yet.
uint randomFaceIdx = rand.getRange(facesLeft - 1);
uint i = 0;
for (uint f = 0; f != randomFaceIdx; f++, i++)
{
while (faceChartArray[i] != -1) i++;
}
while (faceChartArray[i] != -1) i++;
chart->seeds.append(i);
addFaceToChart(chart, i, true);
// Grow the chart as much as possible within the given threshold.
growChart(chart, threshold * 0.5f, facesLeft);
//growCharts(threshold - threshold * 0.75f / chartCount(), facesLeft);
}
void AtlasBuilder::addFaceToChart(ChartBuildData * chart, uint f, bool recomputeProxy)
{
// Add face to chart.
chart->faces.append(f);
nvDebugCheck(faceChartArray[f] == -1);
faceChartArray[f] = chart->id;
facesLeft--;
// Update area and boundary length.
chart->area = evaluateChartArea(chart, f);
chart->boundaryLength = evaluateBoundaryLength(chart, f);
chart->normalSum = evaluateChartNormalSum(chart, f);
chart->centroidSum = evaluateChartCentroidSum(chart, f);
if (recomputeProxy) {
// Update proxy and candidate's priorities.
updateProxy(chart);
}
// Update candidates.
removeCandidate(f);
updateCandidates(chart, f);
updatePriorities(chart);
}
// @@ Get N best candidates in one pass.
const AtlasBuilder::Candidate & AtlasBuilder::getBestCandidate() const
{
uint best = 0;
float bestCandidateMetric = FLT_MAX;
const uint candidateCount = candidateArray.count();
nvCheck(candidateCount > 0);
for (uint i = 0; i < candidateCount; i++)
{
const Candidate & candidate = candidateArray[i];
if (candidate.metric < bestCandidateMetric) {
bestCandidateMetric = candidate.metric;
best = i;
}
}
return candidateArray[best];
}
// Returns true if any of the charts can grow more.
bool AtlasBuilder::growCharts(float threshold, uint faceCount)
{
#if 1 // Using one global list.
faceCount = min(faceCount, facesLeft);
for (uint i = 0; i < faceCount; i++)
{
const Candidate & candidate = getBestCandidate();
if (candidate.metric > threshold) {
return false; // Can't grow more.
}
addFaceToChart(candidate.chart, candidate.face);
}
return facesLeft != 0; // Can continue growing.
#else // Using one list per chart.
bool canGrowMore = false;
const uint chartCount = chartArray.count();
for (uint i = 0; i < chartCount; i++)
{
if (growChart(chartArray[i], threshold, faceCount))
{
canGrowMore = true;
}
}
return canGrowMore;
#endif
}
bool AtlasBuilder::growChart(ChartBuildData * chart, float threshold, uint faceCount)
{
// Try to add faceCount faces within threshold to chart.
for (uint i = 0; i < faceCount; )
{
if (chart->candidates.count() == 0 || chart->candidates.firstPriority() > threshold)
{
return false;
}
uint f = chart->candidates.pop();
if (faceChartArray[f] == -1)
{
addFaceToChart(chart, f);
i++;
}
}
if (chart->candidates.count() == 0 || chart->candidates.firstPriority() > threshold)
{
return false;
}
return true;
}
void AtlasBuilder::resetCharts()
{
const uint faceCount = mesh->faceCount();
for (uint i = 0; i < faceCount; i++)
{
faceChartArray[i] = -1;
faceCandidateArray[i] = -1;
}
facesLeft = faceCount;
candidateArray.clear();
const uint chartCount = chartArray.count();
for (uint i = 0; i < chartCount; i++)
{
ChartBuildData * chart = chartArray[i];
const uint seed = chart->seeds.back();
chart->area = 0.0f;
chart->boundaryLength = 0.0f;
chart->normalSum = Vector3(0);
chart->centroidSum = Vector3(0);
chart->faces.clear();
chart->candidates.clear();
addFaceToChart(chart, seed);
}
}
void AtlasBuilder::updateCandidates(ChartBuildData * chart, uint f)
{
const HalfEdge::Face * face = mesh->faceAt(f);
// Traverse neighboring faces, add the ones that do not belong to any chart yet.
for (HalfEdge::Face::ConstEdgeIterator it(face->edges()); !it.isDone(); it.advance())
{
const HalfEdge::Edge * edge = it.current()->pair;
if (!edge->isBoundary())
{
uint f = edge->face->id;
if (faceChartArray[f] == -1)
{
chart->candidates.push(f);
}
}
}
}
void AtlasBuilder::updateProxies()
{
const uint chartCount = chartArray.count();
for (uint i = 0; i < chartCount; i++)
{
updateProxy(chartArray[i]);
}
}
namespace {
float absoluteSum(Vector4::Arg v)
{
return fabs(v.x) + fabs(v.y) + fabs(v.z) + fabs(v.w);
}
//#pragma message(NV_FILE_LINE "FIXME: Using the c=cos(teta) substitution, the equation system becomes linear and we can avoid the newton solver.")
struct ConeFitting
{
ConeFitting(const HalfEdge::Mesh * m, float g, float tf, float tx) : mesh(m), gamma(g), tolf(tf), tolx(tx), F(0), D(0), H(0) {
}
void addTerm(Vector3 N, float A)
{
const float c = cosf(X.w);
const float s = sinf(X.w);
const float tmp = dot(X.xyz(), N) - c;
F += tmp * tmp;
D.x += 2 * X.x * tmp;
D.y += 2 * X.y * tmp;
D.z += 2 * X.z * tmp;
D.w += 2 * s * tmp;
H(0,0) = 2 * X.x * N.x + 2 * tmp;
H(0,1) = 2 * X.x * N.y;
H(0,2) = 2 * X.x * N.z;
H(0,3) = 2 * X.x * s;
H(1,0) = 2 * X.y * N.x;
H(1,1) = 2 * X.y * N.y + 2 * tmp;
H(1,2) = 2 * X.y * N.z;
H(1,3) = 2 * X.y * s;
H(2,0) = 2 * X.z * N.x;
H(2,1) = 2 * X.z * N.y;
H(2,2) = 2 * X.z * N.z + 2 * tmp;
H(2,3) = 2 * X.z * s;
H(3,0) = 2 * s * N.x;
H(3,1) = 2 * s * N.y;
H(3,2) = 2 * s * N.z;
H(3,3) = 2 * s * s + 2 * c * tmp;
}
Vector4 solve(ChartBuildData * chart, Vector4 start)
{
const uint faceCount = chart->faces.count();
X = start;
Vector4 dX;
do {
for (uint i = 0; i < faceCount; i++)
{
const HalfEdge::Face * face = mesh->faceAt(chart->faces[i]);
addTerm(face->normal(), face->area());
}
Vector4 dX;
//solveKramer(H, D, &dX);
solveLU(H, D, &dX);
// @@ Do a full newton step and reduce by half if F doesn't decrease.
X -= gamma * dX;
// Constrain normal to be normalized.
X = Vector4(normalize(X.xyz()), X.w);
} while(absoluteSum(D) > tolf || absoluteSum(dX) > tolx);
return X;
}
HalfEdge::Mesh const * const mesh;
const float gamma;
const float tolf;
const float tolx;
Vector4 X;
float F;
Vector4 D;
Matrix H;
};
// Unnormalized face normal assuming it's a triangle.
static Vector3 triangleNormal(const HalfEdge::Face * face)
{
Vector3 p0 = face->edge->vertex->pos;
Vector3 p1 = face->edge->next->vertex->pos;
Vector3 p2 = face->edge->next->next->vertex->pos;
Vector3 e0 = p2 - p0;
Vector3 e1 = p1 - p0;
return normalizeSafe(cross(e0, e1), Vector3(0), 0.0f);
}
static Vector3 triangleNormalAreaScaled(const HalfEdge::Face * face)
{
Vector3 p0 = face->edge->vertex->pos;
Vector3 p1 = face->edge->next->vertex->pos;
Vector3 p2 = face->edge->next->next->vertex->pos;
Vector3 e0 = p2 - p0;
Vector3 e1 = p1 - p0;
return cross(e0, e1);
}
// Average of the edge midpoints weighted by the edge length.
// I want a point inside the triangle, but closer to the cirumcenter.
static Vector3 triangleCenter(const HalfEdge::Face * face)
{
Vector3 p0 = face->edge->vertex->pos;
Vector3 p1 = face->edge->next->vertex->pos;
Vector3 p2 = face->edge->next->next->vertex->pos;
float l0 = length(p1 - p0);
float l1 = length(p2 - p1);
float l2 = length(p0 - p2);
Vector3 m0 = (p0 + p1) * l0 / (l0 + l1 + l2);
Vector3 m1 = (p1 + p2) * l1 / (l0 + l1 + l2);
Vector3 m2 = (p2 + p0) * l2 / (l0 + l1 + l2);
return m0 + m1 + m2;
}
} // namespace
void AtlasBuilder::updateProxy(ChartBuildData * chart)
{
//#pragma message(NV_FILE_LINE "TODO: Use best fit plane instead of average normal.")
chart->planeNormal = normalizeSafe(chart->normalSum, Vector3(0), 0.0f);
chart->centroid = chart->centroidSum / float(chart->faces.count());
//#pragma message(NV_FILE_LINE "TODO: Experiment with conic fitting.")
// F = (Nc*Nt - cos Oc)^2 = (x*Nt_x + y*Nt_y + z*Nt_z - cos w)^2
// dF/dx = 2 * x * (x*Nt_x + y*Nt_y + z*Nt_z - cos w)
// dF/dy = 2 * y * (x*Nt_x + y*Nt_y + z*Nt_z - cos w)
// dF/dz = 2 * z * (x*Nt_x + y*Nt_y + z*Nt_z - cos w)
// dF/dw = 2 * sin w * (x*Nt_x + y*Nt_y + z*Nt_z - cos w)
// JacobianMatrix({
// 2 * x * (x*Nt_x + y*Nt_y + z*Nt_z - Cos(w)),
// 2 * y * (x*Nt_x + y*Nt_y + z*Nt_z - Cos(w)),
// 2 * z * (x*Nt_x + y*Nt_y + z*Nt_z - Cos(w)),
// 2 * Sin(w) * (x*Nt_x + y*Nt_y + z*Nt_z - Cos(w))}, {x,y,z,w})
// H[0,0] = 2 * x * Nt_x + 2 * (x*Nt_x + y*Nt_y + z*Nt_z - cos(w));
// H[0,1] = 2 * x * Nt_y;
// H[0,2] = 2 * x * Nt_z;
// H[0,3] = 2 * x * sin(w);
// H[1,0] = 2 * y * Nt_x;
// H[1,1] = 2 * y * Nt_y + 2 * (x*Nt_x + y*Nt_y + z*Nt_z - cos(w));
// H[1,2] = 2 * y * Nt_z;
// H[1,3] = 2 * y * sin(w);
// H[2,0] = 2 * z * Nt_x;
// H[2,1] = 2 * z * Nt_y;
// H[2,2] = 2 * z * Nt_z + 2 * (x*Nt_x + y*Nt_y + z*Nt_z - cos(w));
// H[2,3] = 2 * z * sin(w);
// H[3,0] = 2 * sin(w) * Nt_x;
// H[3,1] = 2 * sin(w) * Nt_y;
// H[3,2] = 2 * sin(w) * Nt_z;
// H[3,3] = 2 * sin(w) * sin(w) + 2 * cos(w) * (x*Nt_x + y*Nt_y + z*Nt_z - cos(w));
// @@ Cone fitting might be quite slow.
/*ConeFitting coneFitting(mesh, 0.1f, 0.001f, 0.001f);
Vector4 start = Vector4(chart->coneAxis, chart->coneAngle);
Vector4 solution = coneFitting.solve(chart, start);
chart->coneAxis = solution.xyz();
chart->coneAngle = solution.w;*/
}
bool AtlasBuilder::relocateSeeds()
{
bool anySeedChanged = false;
const uint chartCount = chartArray.count();
for (uint i = 0; i < chartCount; i++)
{
if (relocateSeed(chartArray[i]))
{
anySeedChanged = true;
}
}
return anySeedChanged;
}
bool AtlasBuilder::relocateSeed(ChartBuildData * chart)
{
Vector3 centroid = computeChartCentroid(chart);
const uint N = 10; // @@ Hardcoded to 10?
PriorityQueue bestTriangles(N);
// Find the first N triangles that fit the proxy best.
const uint faceCount = chart->faces.count();
for (uint i = 0; i < faceCount; i++)
{
float priority = evaluateProxyFitMetric(chart, chart->faces[i]);
bestTriangles.push(priority, chart->faces[i]);
}
// Of those, choose the most central triangle.
uint mostCentral;
float maxDistance = -1;
const uint bestCount = bestTriangles.count();
for (uint i = 0; i < bestCount; i++)
{
const HalfEdge::Face * face = mesh->faceAt(bestTriangles.pairs[i].face);
Vector3 faceCentroid = triangleCenter(face);
float distance = length(centroid - faceCentroid);
/*#pragma message(NV_FILE_LINE "TODO: Implement evaluateDistanceToBoundary.")
float distance = evaluateDistanceToBoundary(chart, bestTriangles.pairs[i].face);*/
if (distance > maxDistance)
{
maxDistance = distance;
mostCentral = bestTriangles.pairs[i].face;
}
}
nvDebugCheck(maxDistance >= 0);
// In order to prevent k-means cyles we record all the previously chosen seeds.
uint index;
if (chart->seeds.find(mostCentral, &index))
{
// Move new seed to the end of the seed array.
uint last = chart->seeds.count() - 1;
swap(chart->seeds[index], chart->seeds[last]);
return false;
}
else
{
// Append new seed.
chart->seeds.append(mostCentral);
return true;
}
}
void AtlasBuilder::removeCandidate(uint f)
{
int c = faceCandidateArray[f];
if (c != -1) {
faceCandidateArray[f] = -1;
if (c == candidateArray.count() - 1) {
candidateArray.popBack();
}
else {
candidateArray.replaceWithLast(c);
faceCandidateArray[candidateArray[c].face] = c;
}
}
}
void AtlasBuilder::updateCandidate(ChartBuildData * chart, uint f, float metric)
{
if (faceCandidateArray[f] == -1) {
const uint index = candidateArray.count();
faceCandidateArray[f] = index;
candidateArray.resize(index + 1);
candidateArray[index].face = f;
candidateArray[index].chart = chart;
candidateArray[index].metric = metric;
}
else {
int c = faceCandidateArray[f];
nvDebugCheck(c != -1);
Candidate & candidate = candidateArray[c];
nvDebugCheck(candidate.face == f);
if (metric < candidate.metric || chart == candidate.chart) {
candidate.metric = metric;
candidate.chart = chart;
}
}
}
void AtlasBuilder::updatePriorities(ChartBuildData * chart)
{
// Re-evaluate candidate priorities.
uint candidateCount = chart->candidates.count();
for (uint i = 0; i < candidateCount; i++)
{
chart->candidates.pairs[i].priority = evaluatePriority(chart, chart->candidates.pairs[i].face);
if (faceChartArray[chart->candidates.pairs[i].face] == -1)
{
updateCandidate(chart, chart->candidates.pairs[i].face, chart->candidates.pairs[i].priority);
}
}
// Sort candidates.
chart->candidates.sort();
}
// Evaluate combined metric.
float AtlasBuilder::evaluatePriority(ChartBuildData * chart, uint face)
{
// Estimate boundary length and area:
float newBoundaryLength = evaluateBoundaryLength(chart, face);
float newChartArea = evaluateChartArea(chart, face);
float F = evaluateProxyFitMetric(chart, face);
float C = evaluateRoundnessMetric(chart, face, newBoundaryLength, newChartArea);
float P = evaluateStraightnessMetric(chart, face);
// Penalize faces that cross seams, reward faces that close seams or reach boundaries.
float N = evaluateNormalSeamMetric(chart, face);
float T = evaluateTextureSeamMetric(chart, face);
//float R = evaluateCompletenessMetric(chart, face);
//float D = evaluateDihedralAngleMetric(chart, face);
// @@ Add a metric based on local dihedral angle.
// @@ Tweaking the normal and texture seam metrics.
// - Cause more impedance. Never cross 90 degree edges.
// -
float cost = float(
settings.proxyFitMetricWeight * F +
settings.roundnessMetricWeight * C +
settings.straightnessMetricWeight * P +
settings.normalSeamMetricWeight * N +
settings.textureSeamMetricWeight * T);
/*cost = settings.proxyFitMetricWeight * powf(F, settings.proxyFitMetricExponent);
cost = max(cost, settings.roundnessMetricWeight * powf(C, settings.roundnessMetricExponent));
cost = max(cost, settings.straightnessMetricWeight * pow(P, settings.straightnessMetricExponent));
cost = max(cost, settings.normalSeamMetricWeight * N);
cost = max(cost, settings.textureSeamMetricWeight * T);*/
// Enforce limits strictly:
if (newChartArea > settings.maxChartArea) cost = FLT_MAX;
if (newBoundaryLength > settings.maxBoundaryLength) cost = FLT_MAX;
// Make sure normal seams are fully respected:
if (settings.normalSeamMetricWeight >= 1000 && N != 0) cost = FLT_MAX;
nvCheck(isFinite(cost));
return cost;
}
// Returns a value in [0-1].
float AtlasBuilder::evaluateProxyFitMetric(ChartBuildData * chart, uint f)
{
const HalfEdge::Face * face = mesh->faceAt(f);
Vector3 faceNormal = triangleNormal(face);
//return square(dot(chart->coneAxis, faceNormal) - cosf(chart->coneAngle));
// Use plane fitting metric for now:
//return square(1 - dot(faceNormal, chart->planeNormal)); // @@ normal deviations should be weighted by face area
return 1 - dot(faceNormal, chart->planeNormal); // @@ normal deviations should be weighted by face area
// Find distance to chart.
/*Vector3 faceCentroid = face->centroid();
float dist = 0;
int count = 0;
for (HalfEdge::Face::ConstEdgeIterator it(face->edges()); !it.isDone(); it.advance())
{
const HalfEdge::Edge * edge = it.current();
if (!edge->isBoundary()) {
const HalfEdge::Face * neighborFace = edge->pair()->face();
if (faceChartArray[neighborFace->id()] == chart->id) {
dist += length(neighborFace->centroid() - faceCentroid);
count++;
}
}
}
dist /= (count * count);
return (1 - dot(faceNormal, chart->planeNormal)) * dist;*/
//return (1 - dot(faceNormal, chart->planeNormal));
}
float AtlasBuilder::evaluateDistanceToBoundary(ChartBuildData * chart, uint face)
{
//#pragma message(NV_FILE_LINE "TODO: Evaluate distance to boundary metric.")
// @@ This is needed for the seed relocation code.
// @@ This could provide a better roundness metric.
return 0.0f;
}
float AtlasBuilder::evaluateDistanceToSeed(ChartBuildData * chart, uint f)
{
//const uint seed = chart->seeds.back();
//const uint faceCount = mesh->faceCount();
//return shortestPaths[seed * faceCount + f];
const HalfEdge::Face * seed = mesh->faceAt(chart->seeds.back());
const HalfEdge::Face * face = mesh->faceAt(f);
return length(triangleCenter(seed) - triangleCenter(face));
}
float AtlasBuilder::evaluateRoundnessMetric(ChartBuildData * chart, uint face, float newBoundaryLength, float newChartArea)
{
// @@ D-charts use distance to seed.
// C(c,t) = pi * D(S_c,t)^2 / A_c
//return PI * square(evaluateDistanceToSeed(chart, face)) / chart->area;
//return PI * square(evaluateDistanceToSeed(chart, face)) / chart->area;
//return 2 * PI * evaluateDistanceToSeed(chart, face) / chart->boundaryLength;
// Garland's Hierarchical Face Clustering paper uses ratio between boundary and area, which is easier to compute and might work as well:
// roundness = D^2/4*pi*A -> circle = 1, non circle greater than 1
//return square(newBoundaryLength) / (newChartArea * 4 * PI);
float roundness = square(chart->boundaryLength) / chart->area;
float newRoundness = square(newBoundaryLength) / newChartArea;
if (newRoundness > roundness) {
return square(newBoundaryLength) / (newChartArea * 4 * PI);
}
else {
// Offer no impedance to faces that improve roundness.
return 0;
}
//return square(newBoundaryLength) / (4 * PI * newChartArea);
//return clamp(1 - (4 * PI * newChartArea) / square(newBoundaryLength), 0.0f, 1.0f);
// Use the ratio between the new roundness vs. the previous roundness.
// - If we use the absolute metric, when the initial face is very long, then it's hard to make any progress.
//return (square(newBoundaryLength) * chart->area) / (square(chart->boundaryLength) * newChartArea);
//return (4 * PI * newChartArea) / square(newBoundaryLength) - (4 * PI * chart->area) / square(chart->boundaryLength);
//if (square(newBoundaryLength) * chart->area) / (square(chart->boundaryLength) * newChartArea);
}
float AtlasBuilder::evaluateStraightnessMetric(ChartBuildData * chart, uint f)
{
float l_out = 0.0f;
float l_in = 0.0f;
const HalfEdge::Face * face = mesh->faceAt(f);
for (HalfEdge::Face::ConstEdgeIterator it(face->edges()); !it.isDone(); it.advance())
{
const HalfEdge::Edge * edge = it.current();
//float l = edge->length();
float l = edgeLengths[edge->id/2];
if (edge->isBoundary())
{
l_out += l;
}
else
{
uint neighborFaceId = edge->pair->face->id;
if (faceChartArray[neighborFaceId] != chart->id) {
l_out += l;
}
else {
l_in += l;
}
}
}
nvDebugCheck(l_in != 0.0f); // Candidate face must be adjacent to chart. @@ This is not true if the input mesh has zero-length edges.
//return l_out / l_in;
float ratio = (l_out - l_in) / (l_out + l_in);
//if (ratio < 0) ratio *= 10; // Encourage closing gaps.
return min(ratio, 0.0f); // Only use the straightness metric to close gaps.
//return ratio;
}
float AtlasBuilder::evaluateNormalSeamMetric(ChartBuildData * chart, uint f)
{
float seamFactor = 0.0f;
float totalLength = 0.0f;
const HalfEdge::Face * face = mesh->faceAt(f);
for (HalfEdge::Face::ConstEdgeIterator it(face->edges()); !it.isDone(); it.advance())
{
const HalfEdge::Edge * edge = it.current();
if (edge->isBoundary()) {
continue;
}
const uint neighborFaceId = edge->pair->face->id;
if (faceChartArray[neighborFaceId] != chart->id) {
continue;
}
//float l = edge->length();
float l = edgeLengths[edge->id/2];
totalLength += l;
if (!edge->isSeam()) {
continue;
}
// Make sure it's a normal seam.
if (isNormalSeam(edge))
{
float d0 = clamp(dot(edge->vertex->nor, edge->pair->next->vertex->nor), 0.0f, 1.0f);
float d1 = clamp(dot(edge->next->vertex->nor, edge->pair->vertex->nor), 0.0f, 1.0f);
//float a0 = clamp(acosf(d0) / (PI/2), 0.0f, 1.0f);
//float a1 = clamp(acosf(d1) / (PI/2), 0.0f, 1.0f);
//l *= (a0 + a1) * 0.5f;
l *= 1 - (d0 + d1) * 0.5f;
seamFactor += l;
}
}
if (seamFactor == 0) return 0.0f;
return seamFactor / totalLength;
}
float AtlasBuilder::evaluateTextureSeamMetric(ChartBuildData * chart, uint f)
{
float seamLength = 0.0f;
//float newSeamLength = 0.0f;
//float oldSeamLength = 0.0f;
float totalLength = 0.0f;
const HalfEdge::Face * face = mesh->faceAt(f);
for (HalfEdge::Face::ConstEdgeIterator it(face->edges()); !it.isDone(); it.advance())
{
const HalfEdge::Edge * edge = it.current();
/*float l = edge->length();
totalLength += l;
if (edge->isBoundary() || !edge->isSeam()) {
continue;
}
// Make sure it's a texture seam.
if (isTextureSeam(edge))
{
uint neighborFaceId = edge->pair()->face()->id();
if (faceChartArray[neighborFaceId] != chart->id) {
newSeamLength += l;
}
else {
oldSeamLength += l;
}
}*/
if (edge->isBoundary()) {
continue;
}
const uint neighborFaceId = edge->pair->face->id;
if (faceChartArray[neighborFaceId] != chart->id) {
continue;
}
//float l = edge->length();
float l = edgeLengths[edge->id/2];
totalLength += l;
if (!edge->isSeam()) {
continue;
}
// Make sure it's a texture seam.
if (isTextureSeam(edge))
{
seamLength += l;
}
}
if (seamLength == 0.0f) {
return 0.0f; // Avoid division by zero.
}
return seamLength / totalLength;
}
float AtlasBuilder::evaluateSeamMetric(ChartBuildData * chart, uint f)
{
float newSeamLength = 0.0f;
float oldSeamLength = 0.0f;
float totalLength = 0.0f;
const HalfEdge::Face * face = mesh->faceAt(f);
for (HalfEdge::Face::ConstEdgeIterator it(face->edges()); !it.isDone(); it.advance())
{
const HalfEdge::Edge * edge = it.current();
//float l = edge->length();
float l = edgeLengths[edge->id/2];
if (edge->isBoundary())
{
newSeamLength += l;
}
else
{
if (edge->isSeam())
{
uint neighborFaceId = edge->pair->face->id;
if (faceChartArray[neighborFaceId] != chart->id) {
newSeamLength += l;
}
else {
oldSeamLength += l;
}
}
}
totalLength += l;
}
return (newSeamLength - oldSeamLength) / totalLength;
}
float AtlasBuilder::evaluateChartArea(ChartBuildData * chart, uint f)
{
const HalfEdge::Face * face = mesh->faceAt(f);
//return chart->area + face->area();
return chart->area + faceAreas[face->id];
}
float AtlasBuilder::evaluateBoundaryLength(ChartBuildData * chart, uint f)
{
float boundaryLength = chart->boundaryLength;
// Add new edges, subtract edges shared with the chart.
const HalfEdge::Face * face = mesh->faceAt(f);
for (HalfEdge::Face::ConstEdgeIterator it(face->edges()); !it.isDone(); it.advance())
{
const HalfEdge::Edge * edge = it.current();
//float edgeLength = edge->length();
float edgeLength = edgeLengths[edge->id/2];
if (edge->isBoundary())
{
boundaryLength += edgeLength;
}
else
{
uint neighborFaceId = edge->pair->face->id;
if (faceChartArray[neighborFaceId] != chart->id) {
boundaryLength += edgeLength;
}
else {
boundaryLength -= edgeLength;
}
}
}
//nvDebugCheck(boundaryLength >= 0);
return max(0.0f, boundaryLength); // @@ Hack!
}
Vector3 AtlasBuilder::evaluateChartNormalSum(ChartBuildData * chart, uint f)
{
const HalfEdge::Face * face = mesh->faceAt(f);
return chart->normalSum + triangleNormalAreaScaled(face);
}
Vector3 AtlasBuilder::evaluateChartCentroidSum(ChartBuildData * chart, uint f)
{
const HalfEdge::Face * face = mesh->faceAt(f);
return chart->centroidSum + face->centroid();
}
Vector3 AtlasBuilder::computeChartCentroid(const ChartBuildData * chart)
{
Vector3 centroid(0);
const uint faceCount = chart->faces.count();
for (uint i = 0; i < faceCount; i++)
{
const HalfEdge::Face * face = mesh->faceAt(chart->faces[i]);
centroid += triangleCenter(face);
}
return centroid / float(faceCount);
}
void AtlasBuilder::fillHoles(float threshold)
{
while (facesLeft > 0)
{
createRandomChart(threshold);
}
}
void AtlasBuilder::mergeChart(ChartBuildData * owner, ChartBuildData * chart, float sharedBoundaryLength)
{
const uint faceCount = chart->faces.count();
for (uint i = 0; i < faceCount; i++)
{
uint f = chart->faces[i];
nvDebugCheck(faceChartArray[f] == chart->id);
faceChartArray[f] = owner->id;
owner->faces.append(f);
}
// Update adjacencies?
owner->area += chart->area;
owner->boundaryLength += chart->boundaryLength - sharedBoundaryLength;
owner->normalSum += chart->normalSum;
owner->centroidSum += chart->centroidSum;
updateProxy(owner);
}
void AtlasBuilder::mergeCharts()
{
Array<float> sharedBoundaryLengths;
const uint chartCount = chartArray.count();
for (int c = chartCount-1; c >= 0; c--)
{
sharedBoundaryLengths.clear();
sharedBoundaryLengths.resize(chartCount, 0.0f);
ChartBuildData * chart = chartArray[c];
float externalBoundary = 0.0f;
const uint faceCount = chart->faces.count();
for (uint i = 0; i < faceCount; i++)
{
uint f = chart->faces[i];
const HalfEdge::Face * face = mesh->faceAt(f);
for (HalfEdge::Face::ConstEdgeIterator it(face->edges()); !it.isDone(); it.advance())
{
const HalfEdge::Edge * edge = it.current();
//float l = edge->length();
float l = edgeLengths[edge->id/2];
if (edge->isBoundary()) {
externalBoundary += l;
}
else {
uint neighborFace = edge->pair->face->id;
uint neighborChart = faceChartArray[neighborFace];
if (neighborChart != c) {
if ((edge->isSeam() && (isNormalSeam(edge) || isTextureSeam(edge))) || neighborChart == -2) {
externalBoundary += l;
}
else {
sharedBoundaryLengths[neighborChart] += l;
}
}
}
}
}
for (int cc = chartCount-1; cc >= 0; cc--)
{
if (cc == c)
continue;
ChartBuildData * chart2 = chartArray[cc];
if (chart2 == NULL)
continue;
if (sharedBoundaryLengths[cc] > 0.8 * max(0.0f, chart->boundaryLength - externalBoundary)) {
// Try to avoid degenerate configurations.
if (chart2->boundaryLength > sharedBoundaryLengths[cc])
{
if (dot(chart2->planeNormal, chart->planeNormal) > -0.25) {
mergeChart(chart2, chart, sharedBoundaryLengths[cc]);
delete chart;
chartArray[c] = NULL;
break;
}
}
}
if (sharedBoundaryLengths[cc] > 0.20 * max(0.0f, chart->boundaryLength - externalBoundary)) {
// Compare proxies.
if (dot(chart2->planeNormal, chart->planeNormal) > 0) {
mergeChart(chart2, chart, sharedBoundaryLengths[cc]);
delete chart;
chartArray[c] = NULL;
break;
}
}
}
}
// Remove deleted charts.
for (int c = 0; c < I32(chartArray.count()); /*do not increment if removed*/)
{
if (chartArray[c] == NULL) {
chartArray.removeAt(c);
// Update faceChartArray.
const uint faceCount = faceChartArray.count();
for (uint i = 0; i < faceCount; i++) {
nvDebugCheck (faceChartArray[i] != -1);
nvDebugCheck (faceChartArray[i] != c);
nvDebugCheck (faceChartArray[i] <= I32(chartArray.count()));
if (faceChartArray[i] > c) {
faceChartArray[i]--;
}
}
}
else {
chartArray[c]->id = c;
c++;
}
}
}
const Array<uint> & AtlasBuilder::chartFaces(uint i) const
{
return chartArray[i]->faces;
}
|