-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathApparentRidges.hx
2762 lines (2607 loc) · 86 KB
/
ApparentRidges.hx
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
/***************************************************
* Apparent Ridges
*
* -- Render line drawings of 3D meshes.
*
* Main Algorithm based on RTSC (C++):
* https://rtsc.cs.princeton.edu
* Some mesh operations based on Trimesh2 (C++):
* https://gfx.cs.princeton.edu/proj/trimesh2/
* The original Apparent Ridges Paper:
* http://people.csail.mit.edu/tjudd/apparentLines.pdf
*
* This haxe implementation by:
* Lingdong Huang, 2020, License: GPL v2
* Made for STUDIO for Creative Inquiry at CMU
*
* haxe --version
* 4.1.3
* See Makefile for build instructions
***************************************************/
package apparentridges;
import haxe.ds.Vector;
/**
Collection of static utilities
**/
@:expose
class Util {
/**
Round float to integer
@param x the float to be rounded
@return closest integer
**/
public static inline function rndInt(x : Float) : Int{
return Std.int(Math.round(x));
}
/**
MIN() for integers
@param a first integer
@param b second integer
@return the lesser of the inputs
**/
public static inline function min(a:Int, b:Int) : Int{
return (a>b)?b:a;
}
/**
Square a float (x^2)
@param x the float
@return the square
**/
public static inline function sq(x : Float) : Float{
return x * x;
}
/**
i + 1 modulo 3.
"This way of computing it tends to be faster than using %" -- Trimesh2
**/
public static inline function nextMod3(i : Int) : Int{
return ((i) < 2 ? (i) + 1 : (i) - 2);
}
/**
i - 1 modulo 3.
"This way of computing it tends to be faster than using %" -- Trimesh2
**/
public static inline function prevMod3(i : Int) : Int{
return ((i) > 0 ? (i) - 1 : (i) + 2);
}
/**
"Area-weighted triangle face normal" -- RTSC
**/
public static inline function trinorm(v0 : Vec3, v1 : Vec3, v2 : Vec3) : Vec3{
return Vec3.cross((v1 - v0), (v2 - v0)) * 0.5;
}
/**
"LDL^T decomposition of a symmetric positive definite matrix (and some
other symmetric matrices, but fragile since we don't do pivoting).
Like Cholesky, but no square roots, which is important for small N.
Reads diagonal and upper triangle of matrix A.
On output, lower triangle of A holds LD, while rdiag holds D^-1.
Algorithm from Golub and van Loan." -- Trimesh2
**/
public static function ldltdc(A : Array<Array<Float>>, rdiag : Array<Float>) : Bool{
// Special case for small N
var N : Int = rdiag.length;
if (N < 1) {
return false;
} else if (N <= 3) {
var d0 : Float = A[0][0];
rdiag[0] = 1 / d0;
if (N == 1)
return (d0 != 0);
A[1][0] = A[0][1];
var l10 : Float = rdiag[0] * A[1][0];
var d1 : Float = A[1][1] - l10 * A[1][0];
rdiag[1] = 1 / d1;
if (N == 2)
return (d0 != 0 && d1 != 0);
var d2 : Float = A[2][2] - rdiag[0] * sq(A[2][0]) - rdiag[1] * sq(A[2][1]);
rdiag[2] = 1 / d2;
A[2][0] = A[0][2];
A[2][1] = A[1][2] - l10 * A[2][0];
return (d0 != 0 && d1 != 0 && d2 != 0);
}
var v : Array<Float> = []; //[N-1]
for (i in 0...N) {
for (k in 0...i)
v[k] = A[i][k] * rdiag[k];
for (j in i...N) {
var sum : Float = A[i][j];
for (k in 0...i)
sum -= v[k] * A[j][k];
if (i == j) {
if (sum == 0)
return false;
rdiag[i] = 1 / sum;
} else {
A[j][i] = sum;
}
}
}
return true;
}
/**
"Solve Ax=b after ldltdc. x is allowed to be the same as b." -- Trimesh
**/
public static function ldltsl(A : Array<Array<Float>>,
rdiag : Array<Float>,
b : Array<Float>,
x : Array<Float>){
var N : Int = rdiag.length;
for (i in 0...N) {
var sum : Float = b[i];
for (k in 0...i)
sum -= A[i][k] * x[k];
x[i] = sum * rdiag[i];
}
for (_i in 0...N) {
var i : Int = N-_i-1;
var sum : Float = 0;
for (k in (i+1)...N)
sum += A[k][i] * x[k];
x[i] -= sum * rdiag[i];
}
}
/**
"Compute largest eigenvalue and associated eigenvector of a
symmetric 2x2 matrix. Solves characteristic equation.
Inputs: three elements of matrix (upper-left, diag, lower-right)
Outputs: largest (in magnitude) eigenvector/value" -- Trimesh2
**/
public static function largestEig2x2(m1:Float,m12:Float,m2:Float) : Vec3{
var l1 : Float = 0.5 * (m1+m2);
// The result of the below sqrt is positive, so to get the largest
// eigenvalue we add it if we were positive already, else subtract
if (l1 > 0.0)
l1 += Math.sqrt(Util.sq(m12) + 0.25 * Util.sq(m2-m1));
else
l1 -= Math.sqrt(Util.sq(m12) + 0.25 * Util.sq(m2-m1));
// Find corresponding eigenvector
var e1 = new Vec3(m2 - l1, -m12, 0);
e1.normalize();
e1.z = l1;
return e1;
}
/**
Returns a 4x4 identiy matrix (row-major, flat)
@return the identity matrix
**/
public static inline function matIden() : Array<Float> {return [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];}
/**
Returns a 4x4 matrix for rotating around x axis (row-major, flat)
@param a the angle in radians
@return the rotation matrix
**/
public static inline function matRotx(a:Float): Array<Float> {return [1,0,0,0, 0,Math.cos(a),-Math.sin(a),0, 0,Math.sin(a),Math.cos(a),0, 0,0,0,1];}
/**
Returns a 4x4 matrix for rotating around y axis (row-major, flat)
@param a the angle in radians
@return the rotation matrix
**/
public static inline function matRoty(a:Float): Array<Float> {return [Math.cos(a),0,Math.sin(a),0, 0,1,0,0, -Math.sin(a),0,Math.cos(a),0, 0,0,0,1];}
/**
Returns a 4x4 matrix for rotating around z axis (row-major, flat)
@param a the angle in radians
@return the rotation matrix
**/
public static inline function matRotz(a:Float): Array<Float> {return [Math.cos(a),-Math.sin(a),0,0, Math.sin(a),Math.cos(a),0,0, 0,0,1,0, 0,0,0,1];}
/**
Returns a 4x4 translation matrix (row-major, flat)
@param x translation along x axis
@param y translation along x axis
@param z translation along x axis
@return the translation matrix
**/
public static inline function matTrsl(x:Float,y:Float,z:Float) : Array<Float> {return [1,0,0,x, 0,1,0,y, 0,0,1,z, 0,0,0,1];}
/**
Returns a 4x4 scaling matrix (row-major, flattend)
@param x scale along x axis
@param y scale along x axis
@param z scale along x axis
@return the scaling matrix
**/
public static inline function matScal(x:Float,y:Float,z:Float) : Array<Float> {return [x,0,0,0, 0,y,0,0, 0,0,z,0, 0,0,0,1];}
/**
Multiply two 4x4 matrices (row-major, flat)
@param A first matrix
@param B second matrix
@return the matrix product
**/
public static inline function matMult(A:Array<Float>,B:Array<Float>) : Array<Float> {
return [A[0]*B[0]+A[1]*B[4]+A[2]*B[8]+A[3]*B[12],A[0]*B[1]+A[1]*B[5]+A[2]*B[9]+A[3]*B[13],A[0]*B[2]+A[1]*B[6]+A[2]*B[10]+A[3]*B[14],
A[0]*B[3]+A[1]*B[7]+A[2]*B[11]+A[3]*B[15],A[4]*B[0]+A[5]*B[4]+A[6]*B[8]+A[7]*B[12],A[4]*B[1]+A[5]*B[5]+A[6]*B[9]+A[7]*B[13],
A[4]*B[2]+A[5]*B[6]+A[6]*B[10]+A[7]*B[14],A[4]*B[3]+A[5]*B[7]+A[6]*B[11]+A[7]*B[15],A[8]*B[0]+A[9]*B[4]+A[10]*B[8]+A[11]*B[12],
A[8]*B[1]+A[9]*B[5]+A[10]*B[9]+A[11]*B[13],A[8]*B[2]+A[9]*B[6]+A[10]*B[10]+A[11]*B[14],A[8]*B[3]+A[9]*B[7]+A[10]*B[11]+A[11]*B[15],
A[12]*B[0]+A[13]*B[4]+A[14]*B[8]+A[15]*B[12],A[12]*B[1]+A[13]*B[5]+A[14]*B[9]+A[15]*B[13],A[12]*B[2]+A[13]*B[6]+A[14]*B[10]+A[15]*B[14],
A[12]*B[3]+A[13]*B[7]+A[14]*B[11]+A[15]*B[15]];
}
/**
Transform a 3D vector using a 4x4 matrix (row-major, flat)
@param A the transformation matrix
@param v the vector
@return new vector after transformation
**/
public static inline function matTrfm(A:Array<Float>,v:Vec3) : Vec3 {
return new Vec3((A[0]*v[0]+A[1]*v[1]+A[2]*v[2]+A[3])/(A[12]*v[0]+A[13]*v[1]+A[14]*v[2]+A[15]),
(A[4]*v[0]+A[5]*v[1]+A[6]*v[2]+A[7])/(A[12]*v[0]+A[13]*v[1]+A[14]*v[2]+A[15]),(A[8]*v[0]+A[9]*v[1]+A[10]*v[2]+A[11])/(A[12]*v[0]+A[13]*v[1]+A[14]*v[2]+A[15])
);}
/**
Project a 3D point onto 2D plane with pinhole camera model situated at `(0,0,0)` pointing toward `+z`
@param f focal length
@param v the vector
@return a 2D point (with zeroed z component)
**/
public static inline function matProj(f:Float,v:Vec3) : Vec3 {return new Vec3(f*v[0]/v[2],f*v[1]/v[2],0);}
/**
Uniform random sampler on unit hemisphere (`+z`)
@return a random point that lies on the hemisphere
**/
public static inline function uniformHemisphereSampler () : Vec3{
var Xi1 : Float = Math.random();
var Xi2 : Float = Math.random();
var theta : Float = Math.acos(Xi1);
var phi : Float = 2*Math.PI*Xi2;
var xs : Float = Math.sin(theta)*Math.cos(phi);
var ys : Float = Math.sin(theta)*Math.sin(phi);
var zs : Float = Math.cos(theta);
var v : Vec3 = new Vec3(xs,ys,zs);
return v;
}
#if sys
/**
Save a string to a file on disk
@param filename path to the file
@param content content to be written
**/
public static function writeFile(filename : String, content : String){
sys.io.File.saveContent(filename,content);
}
#end
}
/**
An abstract 3D Vector type that maps to native fixed-length array in target language,
with all methods inlined
**/
@:expose
abstract Vec3 (haxe.ds.Vector<Float>) {
/** x component, also accessable via subscript `[0]` **/
public var x(get, set):Float;
/** y component, also accessable via subscript `[1]` **/
public var y(get, set):Float;
/** z component, also accessable via subscript `[2]` **/
public var z(get, set):Float;
/**
create new vector from `x` `y` `z` components
@param _x x component
@param _y y component
@param _z z component
**/
public inline function new(_x:Float,_y:Float,_z:Float){
this = new haxe.ds.Vector<Float>(3);
this[0] = _x;
this[1] = _y;
this[2] = _z;
}
private inline function get_x():Float { return this[0]; }
private inline function get_y():Float { return this[1]; }
private inline function get_z():Float { return this[2]; }
private inline function set_x(v:Float):Float { return this[0]=v; }
private inline function set_y(v:Float):Float { return this[1]=v; }
private inline function set_z(v:Float):Float { return this[2]=v; }
/**
Duplicate a vector
@return a new vector that equals to this vector
**/
public inline function copy() : Vec3{
return new Vec3(x,y,z);
}
/**
Set `x` `y` `z` components of this vector from another vector
@param v the vector to copy from
**/
public inline function assign(v : Vec3){
x = v.x; y = v.y; z = v.z;
}
/**
Compute the cross product of two vectors
@param v1 the first vector
@param v2 the second vector
@return the cross product
**/
public static inline function cross(v1:Vec3, v2:Vec3) : Vec3 {
return new Vec3(
v1.y*v2.z-v1.z*v2.y,
v1.z*v2.x-v1.x*v2.z,
v1.x*v2.y-v1.y*v2.x
);
}
/**
Compute the dot product of two vectors
@param v1 the first vector
@param v2 the second vector
@return the dot product
**/
public static inline function dot(v1:Vec3, v2:Vec3) : Float {
return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z;
}
/**
Compute the square of the (Euclidean) distance between two vectors
@param v1 the first vector
@param v2 the second vector
@return distance^2
**/
public static inline function dist2(v1:Vec3, v2:Vec3) : Float{
return Util.sq(v1.x-v2.x)+Util.sq(v1.y-v2.y)+Util.sq(v1.z-v2.z);
}
/**
Compute the (Euclidean) distance between two vectors
@param v1 the first vector
@param v2 the second vector
@return the distance
**/
public static inline function dist(v1:Vec3,v2:Vec3):Float{
return Math.sqrt(Vec3.dist2(v1,v2));
}
/**
Compute the length (magnitude, l2-norm) of the vector
@return the length
**/
public inline function len():Float {
return Math.sqrt(x*x+y*y+z*z);
}
/**
Compute the square of the length of the vector
@return length^2
**/
public inline function len2():Float{
return x*x+y*y+z*z;
}
/**
Normalize the vector to unit vector in-place
**/
public inline function normalize(){
var l : Float = len();
if (l > 0){
l = 1/l;
x *= l;
y *= l;
z *= l;
}else{
x = 0;
y = 0;
z = 1;
}
}
/**
Scale the vector in place
@param s the scaling factor
**/
public inline function scale(s:Float){
x *= s;
y *= s;
z *= s;
}
/**
Get vector `x`/`y`/`z` component via subscript operator `[0]` `[1]` `[2]`
@param i the index
**/
@:arrayAccess
public inline function get(i:Int):Float {
return this[i];
}
/**
Set vector `x`/`y`/`z` component via subscript operator `[0]` `[1]` `[2]`
@param i the index
@param v the value to write
**/
@:arrayAccess
public inline function set(i:Int,v:Float):Float {
this[i] = v;
return v;
}
/**
Overload `+` operator to add vectors
@param rhs the other vector
@return elementwise sum
**/
@:op(A+B)
public inline function add(rhs:Vec3) : Vec3 {
return new Vec3(x+rhs.x,y+rhs.y,z+rhs.z);
}
/**
Overload `-` operator to subtract vectors
@param rhs the other vector
@return elementwise difference
**/
@:op(A-B)
public inline function sub(rhs:Vec3) : Vec3 {
return new Vec3(x-rhs.x,y-rhs.y,z-rhs.z);
}
/**
Overload `*` operator to multiply vectors elementwise
@param rhs the other vector
@return hadamard product
**/
@:op(A*B)
public inline function mul(rhs:Vec3) : Vec3 {
return new Vec3(x*rhs.x,y*rhs.y,z*rhs.z);
}
/**
Overload `*` operator to multiply vector by a scalar
@param rhs the scalar
@return scaled vector
**/
@:op(A*B)
public inline function mulf(rhs:Float) : Vec3 {
return new Vec3(x*rhs,y*rhs,z*rhs);
}
}
/**
Triangular mesh face type, storing vertices as indices.
Maps to native fixed-length array in target language
**/
@:expose
abstract Face (haxe.ds.Vector<Int>) {
/**
New face from vertices (vertex indices in the mesh)
@param a index of first vertex in the mesh
@param b index of second vertex in the mesh
@param c index of third vertex in the mesh
**/
public inline function new(a:Int, b:Int, c:Int){
this = new haxe.ds.Vector<Int>(3);
this[0]=a;
this[1]=b;
this[2]=c;
}
/**
Get vertex in the face via subscript `[0]` `[1]` `[2]`
@param i the index
**/
@:arrayAccess
public inline function get(i:Int):Int {
return this[i];
}
/**
Set vertex in the face via subscript `[0]` `[1]` `[2]`
@param i the index
@param v the value
**/
@:arrayAccess
public inline function set(i:Int,v:Int):Int {
this[i] = v;
return v;
}
/**
Search for a vertex in the face
@param v the vertex to look for (vertex index in the mesh)
@return index of the vertex in the face, -1 if not found
**/
public inline function indexOf(v:Int):Int{
if (this[0]==v){return 0;}
if (this[1]==v){return 1;}
if (this[2]==v){return 2;}
return -1;
}
}
/**
Type for storing an apparent ridge,
containing coordinates of endpoints and cooresponding ridge strengths
**/
@:expose
class Ridge {
/** first endpoint **/
public var A : Vec3;
/** second endpoint **/
public var B : Vec3;
/** ridge strength at first endpoint **/
public var strengthA : Float;
/** ridge strength at second endpoint **/
public var strengthB : Float;
/**
new ridge from endpoints and strengths
@param a first endpoint coordinate
@param sa strength of first endpoint
@param b second endpoint coordiate
@param sb strength of second endpoint
**/
public inline function new(a:Vec3,sa:Float,b:Vec3,sb:Float){
A = a; strengthA = sa;
B = b; strengthB = sb;
}
}
/**
Bounding sphere type
**/
@:expose
class BSphere{
/** radius of the bounding sphere **/
public var r : Float;
/** center of the bounding sphere **/
public var o : Vec3;
/** new uninitialized bounding sphere **/
public inline function new(){}
}
/**
The main mesh type, stored as vertices and triangles.
Contains methods to compute normals, curvatures,
apparent ridges, etc.
**/
@:expose
class Mesh {
/** vertices as array of 3D points **/
public var vertices : Array<Vec3> = [];
/** faces as array of triangles **/
public var faces : Array<Face> = [];
/** vertex normals as array of vectors **/
public var normals : Array<Vec3> = [];
/** curvature on the first principle direction, per-vertex**/
public var curv1 : Array<Float> = [];
/** curvature on the second principle direction, pre-vertex**/
public var curv2 : Array<Float> = [];
/** first principle curvature direction, per-vertex**/
public var pdir1 : Array<Vec3> = [];
/** second principle curvature direction, per-vertex**/
public var pdir2 : Array<Vec3> = [];
/** point area of each vertex **/
public var pointAreas : Array<Float> = [];
/** corner area of each vertex **/
public var cornerAreas : Array<Vec3> = [];
/** neighboring faces for each vertex **/
public var adjacentFaces : Array<Array<Int>> = [];
/** cosine of angle between normal and view direction **/
public var ndotv : Array<Float> = [];
/**
`t1` and `q1` as defined in the paper,
packed into single Vec3 for each vertex
**/
public var t1q1 : Array<Vec3> = [];
/**
"`D_{t_1} q_1` - the derivative of max view-dependent curvature
in the principal max view-dependent curvature direction." -- RTSC
**/
public var Dt1q1 : Array<Float> = [];
/** bounding sphere of the mesh **/
public var bsphere : BSphere;
/** "Used to make thresholds dimensionless" -- RTSC **/
public var featureSize : Float;
/** bounding volume hierarchy **/
public var bvh : BVHTree;
/**
New empty mesh
**/
public function new(){
}
/**
Call necessary pre-computations of mesh properties for computing
apparent ridges, in this order:
normals, point-areas, adjacent-faces, curvatures, bounding sphere,
feature size, bounding volume hierarchy.
Alternatively, you can call the `computeXxxxx()` methods directly for
a more customized set of things to compute, but since some of them
depend on another so be careful of the order.
@param doBVH whether to compute the bounding volume hiarchy, only
necessary for hiding occluded ridges
@param verb verbose: log progress
**/
public function precompute(doBVH:Bool=true,verb:Bool=false){
if(verb)trace("computing normals...");
computeNormals();
if(verb)trace("computing point areas...");
computePointAreas();
if(verb)trace("computing adjacent faces...");
computeAdjacentFaces();
if(verb)trace("computing curvatures...");
computeCurvatures();
if(verb)trace("computing bounding sphere...");
computeBSphere();
if(verb)trace("computing feature size...");
computeFeatureSize();
if(verb)trace("computing bounding volume hierarchy...");
if (doBVH){computeBVH();}else{computeBVHTrivial();}
if(verb)trace("pre-computation finished.");
}
/**
"Compute per-vertex normals
Uses average of per-face normals, weighted according to:
Max, N.
'Weights for Computing Vertex Normals from Facet Normals,'
Journal of Graphics Tools, Vol. 4, No. 2, 1999."
-- Trimesh2
**/
public function computeNormals(){
normals = [for (i in 0...vertices.length) new Vec3(0,0,0)];
for (f in faces){
var p0 : Vec3 = vertices[f[0]];
var p1 : Vec3 = vertices[f[1]];
var p2 : Vec3 = vertices[f[2]];
var a : Vec3 = p0-p1;
var b : Vec3 = p1-p2;
var fn : Vec3 = Vec3.cross(a,b);
normals[f[0]] += fn;
normals[f[1]] += fn;
normals[f[2]] += fn;
}
for (n in normals){
n.normalize();
}
}
/**
"Compute an approximate bounding sphere"
-- Trimesh2
**/
public function computeBSphere(){
bsphere = new BSphere();
function farthestVertexAlong(dir : Vec3){
var nv : Int = vertices.length;
var far : Int = 0;
var far_dot = Vec3.dot(vertices[0],dir);
for (i in 1...nv){
var my_dot : Float = Vec3.dot(vertices[i],dir);
if (my_dot > far_dot){
far = i;
far_dot = my_dot;
}
}
return far;
}
var best_min : Vec3 = new Vec3(0,0,0);
var best_max : Vec3 = new Vec3(0,0,0);
var dirs : Array<Vec3> = [
new Vec3(1,0,0),
new Vec3(0,1,0),
new Vec3(0,0,1),
new Vec3(1,1,1),
new Vec3(1,-1,1),
new Vec3(1,-1,-1),
new Vec3(1,1,1),
];
for (d in dirs){
var p1 : Vec3 = vertices[farthestVertexAlong(d*(-1.0))];
var p2 : Vec3 = vertices[farthestVertexAlong(d)];
if (Vec3.dist2(p1,p2)>Vec3.dist2(best_min,best_max)){
best_min = p1;
best_max = p2;
}
}
bsphere.o = (best_min + best_max) * 0.5;
bsphere.r = Vec3.dist(best_min, best_max) * 0.5;
var r2 = Util.sq(bsphere.r);
// Expand bsphere to contain all points
for (i in 0...vertices.length){
var d2 : Float = Vec3.dist2(vertices[i],bsphere.o);
if (d2 <= r2){
continue;
}
var d : Float = Math.sqrt(d2);
bsphere.r = 0.5 * (bsphere.r + d);
r2 = Util.sq(bsphere.r);
bsphere.o-=vertices[i];
bsphere.o*=bsphere.r*(1.0/d);
bsphere.o+=vertices[i];
}
}
/**
"Compute a 'feature size' for the mesh: computed as 1% of
the reciprocal of the 10-th percentile curvature" -- RTSC
**/
public function computeFeatureSize(){
var nv : Int = curv1.length;
var nsamp = Util.min(nv, 500);
var samples : Array<Float> = [];
var s : Int = 79;//bbs
var p : Int = 103;
var q : Int = 211;
var m : Int = p*q;
for (i in 0...nsamp){
var ind : Int = Std.int(nv*(s/m));
s = (s*s) % m;
samples.push(Math.abs(curv1[ind]));
samples.push(Math.abs(curv2[ind]));
}
var frac : Float = 0.1;
var mult : Float = 0.01;
var max_feat_size = 0.05 * bsphere.r;
var which : Int = Std.int(frac * samples.length);
samples.sort(function(a : Float, b : Float) : Int {
if(a < b) return -1;
else if(a > b) return 1;
else return 0;
}); // todo: std::nth_element
featureSize = Math.min(mult/samples[which],max_feat_size);
}
/**
Find the faces touching each vertex
**/
public function computeAdjacentFaces(){
adjacentFaces = [for (i in 0...vertices.length) new Array<Int>()];
for (i in 0...faces.length){
for (j in 0...3){
adjacentFaces[faces[i][j]].push(i);
}
}
}
/**
Get the three edges from a face
@param face the face
@return 3 vectors representing direction and length of each edge
**/
public function getFaceEdges(f:Face) : haxe.ds.Vector<Vec3>{
var e : haxe.ds.Vector<Vec3> = new haxe.ds.Vector<Vec3>(3);
e[0] = vertices[f[2]]-vertices[f[1]];
e[1] = vertices[f[0]]-vertices[f[2]];
e[2] = vertices[f[1]]-vertices[f[0]];
return e;
}
/**
"Compute the area 'belonging' to each vertex or each corner
of a triangle (defined as Voronoi area restricted to the 1-ring of
a vertex, or to the triangle)." -- Trimesh2
**/
public function computePointAreas(){
var nf : Int = faces.length;
var nv : Int = vertices.length;
pointAreas = [for (i in 0...nv) 0];
cornerAreas = [for (i in 0...nf) new Vec3(0,0,0)];
for (i in 0...nf){
var e : haxe.ds.Vector<Vec3> = getFaceEdges(faces[i]);
// Compute corner weights
var area : Float = 0.5 * Vec3.cross(e[0],e[1]).len();
var l2 : Array<Float> = [e[0].len2(), e[1].len2(), e[2].len2()];
// Barycentric weights of circumcenter
var bcw : Array<Float> = [
l2[0] * (l2[1] + l2[2] - l2[0]),
l2[1] * (l2[2] + l2[0] - l2[1]),
l2[2] * (l2[0] + l2[1] - l2[2])
];
if (bcw[0] <= 0) {
cornerAreas[i][1] = -0.25 * l2[2] * area / Vec3.dot(e[0],e[2]);
cornerAreas[i][2] = -0.25 * l2[1] * area / Vec3.dot(e[0],e[1]);
cornerAreas[i][0] = area - cornerAreas[i][1] - cornerAreas[i][2];
} else if (bcw[1] <= 0.0) {
cornerAreas[i][2] = -0.25 * l2[0] * area / Vec3.dot(e[1],e[0]);
cornerAreas[i][0] = -0.25 * l2[2] * area / Vec3.dot(e[1],e[2]);
cornerAreas[i][1] = area - cornerAreas[i][2] - cornerAreas[i][0];
} else if (bcw[2] <= 0.0) {
cornerAreas[i][0] = -0.25 * l2[1] * area / Vec3.dot(e[2],e[1]);
cornerAreas[i][1] = -0.25 * l2[0] * area / Vec3.dot(e[2],e[0]);
cornerAreas[i][2] = area - cornerAreas[i][0] - cornerAreas[i][1];
} else {
var scale : Float = 0.5 * area / (bcw[0] + bcw[1] + bcw[2]);
for (j in 0...3)
cornerAreas[i][j] = scale * (bcw[Util.nextMod3(j)] +
bcw[Util.prevMod3(j)]);
}
pointAreas[faces[i][0]] += cornerAreas[i][0];
pointAreas[faces[i][1]] += cornerAreas[i][1];
pointAreas[faces[i][2]] += cornerAreas[i][2];
}
}
/**
"Rotate a coordinate system to be perpendicular to the given normal"
-- Trimesh2
**/
private static function rotCoordSys(old_u : Vec3, old_v : Vec3, new_norm : Vec3,
new_u : Vec3, new_v : Vec3){
new_u.assign(old_u);
new_v.assign(old_v);
var old_norm : Vec3 = Vec3.cross(old_u,old_v);
var ndot : Float = Vec3.dot(old_norm,new_norm);
if ((ndot <= -1)) {
new_u.scale(-1);
new_v.scale(-1);
return;
}
// Perpendicular to old_norm and in the plane of old_norm and new_norm
var perp_old : Vec3 = new_norm - old_norm*ndot;
// Perpendicular to new_norm and in the plane of old_norm and new_norm
// vec perp_new = ndot * new_norm - old_norm;
// perp_old - perp_new, with normalization constants folded in
var dperp : Vec3 = (old_norm + new_norm) * (1 / (1 + ndot));
// Subtracts component along perp_old, and adds the same amount along
// perp_new. Leaves unchanged the component perpendicular to the
// plane containing old_norm and new_norm.
new_u -= dperp * Vec3.dot(new_u,perp_old);
new_v -= dperp * Vec3.dot(new_v,perp_old);
}
/**
"Reproject a curvature tensor from the basis spanned by old_u and old_v
(which are assumed to be unit-length and perpendicular) to the
new_u, new_v basis." -- Trimesh2
**/
private static function projCurv(old_u : Vec3, old_v : Vec3,
old_ku : Float, old_kuv : Float, old_kv : Float,
new_u : Vec3, new_v : Vec3) : Vec3{
var r_new_u : Vec3 = new Vec3(0,0,0);
var r_new_v : Vec3 = new Vec3(0,0,0);
rotCoordSys(new_u,new_v,Vec3.cross(old_u,old_v),r_new_u,r_new_v);
var u1 : Float = Vec3.dot(r_new_u,old_u);
var v1 : Float = Vec3.dot(r_new_u,old_v);
var u2 : Float = Vec3.dot(r_new_v,old_u);
var v2 : Float = Vec3.dot(r_new_v,old_v);
var new_ku : Float = old_ku * u1*u1 + old_kuv * (2 * u1*v1) + old_kv * v1*v1;
var new_kuv : Float = old_ku * u1*u2 + old_kuv * (u1*v2 + u2*v1) + old_kv * v1*v2;
var new_kv : Float = old_ku * u2*u2 + old_kuv * (2 * u2*v2) + old_kv * v2*v2;
return new Vec3(new_ku,new_kuv,new_kv);
}
/**
"Given a curvature tensor, find principal directions and curvatures"
-- Trimesh2
**/
private static function diagonalizeCurv(old_u : Vec3, old_v : Vec3,
ku : Float, kuv : Float, kv : Float,
new_norm : Vec3,
pd1 : Vec3, pd2 : Vec3, k1k2 : Vec3){
var r_old_u : Vec3 = new Vec3(0,0,0);
var r_old_v : Vec3 = new Vec3(0,0,0);
rotCoordSys(old_u, old_v, new_norm, r_old_u, r_old_v);
var c : Float = 1; var s : Float = 0; var tt : Float = 0;
if (kuv != 0.0) {
// Jacobi rotation to diagonalize
var h : Float = 0.5 * (kv - ku) / kuv;
tt = (h < 0.0) ?
1.0 / (h - Math.sqrt(1.0 + h*h)) :
1.0 / (h + Math.sqrt(1.0 + h*h));
c = 1.0 / Math.sqrt(1.0 + tt*tt);
s = tt * c;
}
var k1 : Float = ku - tt * kuv;
var k2 : Float = kv + tt * kuv;
if (Math.abs(k1) >= Math.abs(k2)) {
k1k2.x = k1;
k1k2.y = k2;
pd1.assign(r_old_u*c - r_old_v*s);
} else {
k1k2.x = k2;
k1k2.y = k1;
pd1.assign(r_old_u*s + r_old_v*c);
}
pd2.assign(Vec3.cross(new_norm,pd1));
}
/**
"Compute principal curvatures and directions" -- Trimesh2
**/
public function computeCurvatures(){
var nv : Int = vertices.length;
var nf : Int = faces.length;
curv1 = [for (i in 0...nv) 0];
curv2 = [for (i in 0...nv) 0];
pdir1 = [for (i in 0...nv) new Vec3(0,0,0)];
pdir2 = [for (i in 0...nv) new Vec3(0,0,0)];
var curv12 : Array<Float> = [for (i in 0...nv) 0];
// Set up an initial coordinate system per vertex
for (i in 0...nf){
pdir1[faces[i][0]] = vertices[faces[i][1]] -
vertices[faces[i][0]];
pdir1[faces[i][1]] = vertices[faces[i][2]] -
vertices[faces[i][1]];
pdir1[faces[i][2]] = vertices[faces[i][0]] -
vertices[faces[i][2]];
}
for (i in 0...nv){
pdir1[i] = Vec3.cross(pdir1[i],normals[i]);
pdir1[i].normalize();
pdir2[i] = Vec3.cross(normals[i],pdir1[i]);
}
// Compute curvature per-face
for (i in 0...nf){
var f : Face = faces[i];
var e : haxe.ds.Vector<Vec3> = getFaceEdges(f);
// N-T-B coordinate system per face
var t : Vec3 = e[0].copy();
t.normalize();
var n : Vec3 = Vec3.cross(e[0],e[1]);
var b : Vec3 = Vec3.cross(n,t);
b.normalize();
// Estimate curvature based on variation of normals
// along edges
var m : Array<Float> = [0,0,0];
var w : Array<Array<Float>> = [[0,0,0],[0,0,0],[0,0,0]];
for (j in 0...3){
var u : Float = Vec3.dot(e[j],t);
var v : Float = Vec3.dot(e[j],b);
w[0][0] += u*u;
w[0][1] += u*v;
w[2][2] += v*v;
// The below are computed once at the end of the loop
// w[1][1] += v*v + u*u;
// w[1][2] += u*v;
var dn : Vec3 = normals[f[Util.prevMod3(j)]] -
normals[f[Util.nextMod3(j)]];
var dnu : Float = Vec3.dot(dn,t);
var dnv : Float = Vec3.dot(dn,b);
m[0] += dnu*u;
m[1] += dnu*v + dnv*u;
m[2] += dnv*v;
}
w[1][1] = w[0][0] + w[2][2];
w[1][2] = w[0][1];
// Least squares solution
var diag : Array<Float> = [0,0,0];
if (!Util.ldltdc(w, diag)) {
continue;
}
Util.ldltsl(w,diag,m,m);
// Push it back out to the vertices
for (j in 0...3){
var vj : Int = f[j];
var ccc : Vec3 = projCurv(t,b,m[0],m[1],m[2],pdir1[vj],pdir2[vj]);
var c1 : Float= ccc.x;
var c12: Float= ccc.y;
var c2 : Float= ccc.z;
var wt : Float = cornerAreas[i][j]/pointAreas[vj];
curv1[vj] += wt * c1;
curv12[vj] += wt * c12;
curv2[vj] += wt * c2;
}
}
for (i in 0...nv){
var c1c2 : Vec3 = new Vec3(0,0,0);
diagonalizeCurv(
pdir1[i],pdir2[i],
curv1[i],curv12[i],curv2[i],
normals[i],pdir1[i],pdir2[i],
c1c2
);
curv1[i]=c1c2.x;
curv2[i]=c1c2.y;
}
}
/**
"Compute principal view-dependent curvatures and directions at vertex i.
ndotv = cosine of angle between normal and view direction
(u,v) = coordinates of w (projected view) in principal coordinates
Pass in u^2, u*v, and v^2, since those are readily available.
Fills in q1 and t1 (using the paper's notation).