-
Notifications
You must be signed in to change notification settings - Fork 26
/
polyhedronisme.js
7962 lines (7622 loc) · 278 KB
/
polyhedronisme.js
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
// Polyhédronisme
//===================================================================================================
//
// A toy for constructing and manipulating polyhedra and other meshes
//
// Includes implementation of the conway polyhedral operators derived
// from code by mathematician and mathematical sculptor
// George W. Hart http://www.georgehart.com/
//
// Copyright 2019, Anselm Levskaya
// Released under the MIT License
// Math / Vector / Matrix Functions
//===================================================================================================
// import math functions to local namespace
const { random, round, floor, sqrt,
sin, cos, tan, asin, acos, atan,
abs, pow, log,
PI, LN10
} = Math;
const log10 = x=> log(x)/LN10;
//returns string w. nsigs digits ignoring magnitude
const sigfigs = function(N, nsigs){
const mantissa = N / pow(10, floor(log10(N)));
const truncated_mantissa = round(mantissa * pow(10, (nsigs-1)));
return `${truncated_mantissa}`;
};
// general recursive deep-copy function
var clone = function(obj) {
if ((obj == null) || (typeof obj !== 'object')) {
return obj;
}
const newInstance = new obj.constructor();
for (let key in obj) {
newInstance[key] = clone(obj[key]);
}
return newInstance;
};
// often useful
const randomchoice = function(array){
const n = floor(random()*array.length);
return array[n];
};
// 3d scalar multiplication
const mult = (c, vec) =>
[c*vec[0], c*vec[1], c*vec[2]];
// 3d element-wise multiply
const _mult = (vec1, vec2) =>
[vec1[0]*vec2[0], vec1[1]*vec2[1], vec1[2]*vec2[2]];
// 3d vector addition
const add = (vec1, vec2) =>
[vec1[0]+vec2[0], vec1[1]+vec2[1], vec1[2]+vec2[2]];
// 3d vector subtraction
const sub = (vec1, vec2) =>
[vec1[0]-vec2[0], vec1[1]-vec2[1], vec1[2]-vec2[2]];
// 3d dot product
const dot = (vec1, vec2) =>
(vec1[0]*vec2[0]) + (vec1[1]*vec2[1]) + (vec1[2]*vec2[2]);
// 3d cross product d1 x d2
const cross = (d1, d2) =>
[(d1[1]*d2[2]) - (d1[2]*d2[1]),
(d1[2]*d2[0]) - (d1[0]*d2[2]),
(d1[0]*d2[1]) - (d1[1]*d2[0]) ];
// vector norm
const mag = vec => sqrt(dot(vec, vec));
// vector magnitude squared
const mag2 = vec => dot(vec, vec);
// makes vector unit length
const unit = vec => mult(1 / sqrt(mag2(vec)), vec);
// midpoint between vec1, vec2
const midpoint = (vec1, vec2) => mult(1/2.0, add(vec1, vec2));
// parametric segment between vec1, vec2 w. parameter t ranging from 0 to 1
const tween = (vec1, vec2, t) =>
[((1-t)*vec1[0]) + (t*vec2[0]),
((1-t)*vec1[1]) + (t*vec2[1]),
((1-t)*vec1[2]) + (t*vec2[2])];
// uses above to go one-third of the way along vec1->vec2 line
const oneThird = (vec1, vec2) => tween(vec1, vec2, 1/3.0);
// reflect 3vec in unit sphere, spherical reciprocal
const reciprocal = vec => mult(1.0 / mag2(vec), vec);
// point where line v1...v2 tangent to an origin sphere
const tangentPoint= function(v1, v2) {
const d = sub(v2, v1);
return sub(v1, mult(dot(d, v1)/mag2(d), d));
};
// distance of line v1...v2 to origin
const edgeDist = (v1, v2) => sqrt(mag2(tangentPoint(v1, v2)));
// square of distance from point v3 to line segment v1...v2
// http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html
// calculates min distance from
// point v3 to finite line segment between v1 and v2
const linePointDist2 = function(v1, v2, v3) {
let result;
const d21 = sub(v2, v1);
const d13 = sub(v1, v3);
const d23 = sub(v2, v3);
const m2 = mag2(d21);
const t = -dot(d13, d21)/m2;
if (t <= 0) {
// closest to point beyond v1, clip to |v3-v1|^2
result = mag2(d13);
} else if (t >= 1) {
// closest to point beyond v2, clip to |v3-v2|^2
result = mag2(d23);
} else {
// closest in-between v1, v2
result = mag2(cross(d21, d13))/m2;
}
return result;
};
// find vector orthogonal to plane of 3 pts
// -- do the below algos assume this be normalized or not?
const orthogonal = function(v1,v2,v3) {
// adjacent edge vectors
const d1 = sub(v2, v1);
const d2 = sub(v3, v2);
// cross product
return cross(d1, d2);
};
// find first element common to 3 sets by brute force search
const intersect = function(set1, set2, set3) {
for (let s1 of set1) {
for (let s2 of set2) {
if (s1 === s2) {
for (let s3 of set3) {
if (s1 === s3) {
return s1;
}
}
}
}
}
return null; // empty intersection
};
// calculate centroid of array of vertices
const calcCentroid = function(vertices) {
// running sum of vertex coords
let centroidV = [0,0,0];
for (let v of vertices) {
centroidV = add(centroidV, v);
}
return mult(1 / vertices.length, centroidV );
};
// calculate average normal vector for array of vertices
const normal = function(vertices) {
// running sum of normal vectors
let normalV = [0,0,0];
let [v1, v2] = vertices.slice(-2);
for (let v3 of vertices) {
normalV = add(normalV, orthogonal(v1, v2, v3));
[v1, v2] = [v2, v3];
} // shift over one
return unit(normalV);
};
// calculates area planar face by summing over subtriangle areas
// this assumes planarity.
const planararea = function(vertices) {
let area = 0.0;
let vsum = [0.,0.,0.];
let [v1, v2] = vertices.slice(-2);
for (let v3 of vertices) {
vsum = add(vsum, cross(v1, v2));
[v1, v2] = [v2, v3];
}
area = abs(dot(normal(vertices), vsum) / 2.0);
return area;
};
// congruence signature for assigning same colors to congruent faces
const faceSignature = function(vertices, sensitivity) {
let x;
const cross_array = [];
let [v1, v2] = vertices.slice(-2);
for (let v3 of vertices) {
// accumulate inner angles
cross_array.push(mag( cross(sub(v1, v2), sub(v3, v2)) ));
[v1, v2] = [v2, v3];
}
// sort angles to create unique sequence
cross_array.sort((a,b)=>a-b);
// render sorted angles as quantized digit strings
// this is the congruence signature
let sig = "";
for (x of cross_array) { sig+=sigfigs(x, sensitivity); }
// hack to make reflected faces share the same signature
for (x of cross_array.reverse()) { sig+=sigfigs(x, sensitivity); }
return sig;
};
// projects 3d polyhedral face to 2d polygon
// for triangulation and face display
const project2dface = function(verts){
let tmpverts = clone(verts);
const v0 = verts[0];
tmpverts = _.map(tmpverts, x=>x-v0);
const n = normal(verts);
const c = unit(calcCentroid(verts)); //XXX: correct?
const p = cross(n,c);
return tmpverts.map((v) => [dot(n, v), dot(p, v)]);
};
// copies array of arrays by value (deep copy)
const copyVecArray = function(vecArray){
const newVecArray = new Array(vecArray.length);
for (let i = 0, end = vecArray.length; i < end; i++) {
newVecArray[i] = vecArray[i].slice(0);
}
return newVecArray;
};
// 3d matrix vector multiply
const mv3 = (mat,vec) =>
//Ghetto custom def of matrix-vector mult
//example matrix: [[a,b,c],[d,e,f],[g,h,i]]
[(mat[0][0]*vec[0])+(mat[0][1]*vec[1])+(mat[0][2]*vec[2]),
(mat[1][0]*vec[0])+(mat[1][1]*vec[1])+(mat[1][2]*vec[2]),
(mat[2][0]*vec[0])+(mat[2][1]*vec[1])+(mat[2][2]*vec[2])];
// 3d matrix matrix multiply
const mm3 = (A,B) =>
[[(A[0][0]*B[0][0])+(A[0][1]*B[1][0])+(A[0][2]*B[2][0]),
(A[0][0]*B[0][1])+(A[0][1]*B[1][1])+(A[0][2]*B[2][1]),
(A[0][0]*B[0][2])+(A[0][1]*B[1][2])+(A[0][2]*B[2][2])],
[(A[1][0]*B[0][0])+(A[1][1]*B[1][0])+(A[1][2]*B[2][0]),
(A[1][0]*B[0][1])+(A[1][1]*B[1][1])+(A[1][2]*B[2][1]),
(A[1][0]*B[0][2])+(A[1][1]*B[1][2])+(A[1][2]*B[2][2])],
[(A[2][0]*B[0][0])+(A[2][1]*B[1][0])+(A[2][2]*B[2][0]),
(A[2][0]*B[0][1])+(A[2][1]*B[1][1])+(A[2][2]*B[2][1]),
(A[2][0]*B[0][2])+(A[2][1]*B[1][2])+(A[2][2]*B[2][2])]];
const eye3 = [[1,0,0], [0,1,0], [0,0,1]];
// Rotation Matrix
// Totally ghetto, not at all in agreement with euler angles!
// use quaternions instead
const rotm = function(phi,theta,psi){
const xy_mat = [
[cos(phi), -1.0*sin(phi), 0.0],
[sin(phi), cos(phi), 0.0],
[0.0, 0.0, 1.0]];
const yz_mat = [
[cos(theta), 0, -1.0*sin(theta)],
[ 0, 1, 0],
[sin(theta), 0, cos(theta)]];
const xz_mat = [
[1.0, 0, 0],
[ 0, cos(psi), -1.0*sin(psi)],
[ 0, sin(psi), cos(psi)]];
return mm3(xz_mat, mm3(yz_mat,xy_mat));
};
// Rotation Matrix defined by rotation about (unit) axis [x,y,z] for angle radians
const vec_rotm = function(angle, x, y, z) {
let m;
angle /= 2;
const sinA = sin(angle);
const cosA = cos(angle);
const sinA2 = sinA*sinA;
const length = mag([x,y,z]);
if (length === 0) {
[x, y, z] = [0, 0, 1];
}
if (length !== 1) {
[x, y, z] = unit([x, y, z]);
}
if ((x === 1) && (y === 0) && (z === 0)) {
m = [[1, 0, 0],
[0, 1-(2*sinA2), 2*sinA*cosA],
[0, -2*sinA*cosA, 1-(2*sinA2)]];
} else if ((x === 0) && (y === 1) && (z === 0)) {
m = [[1-(2*sinA2), 0, -2*sinA*cosA],
[ 0, 1, 0],
[2*sinA*cosA, 0, 1-(2*sinA2)]];
} else if ((x === 0) && (y === 0) && (z === 1)) {
m = [[ 1-(2*sinA2), 2*sinA*cosA, 0],
[ -2*sinA*cosA, 1-(2*sinA2), 0],
[ 0, 0, 1]];
} else {
const x2 = x*x;
const y2 = y*y;
const z2 = z*z;
m =
[[1-(2*(y2+z2)*sinA2), 2*((x*y*sinA2)+(z*sinA*cosA)), 2*((x*z*sinA2)-(y*sinA*cosA))],
[2*((y*x*sinA2)-(z*sinA*cosA)), 1-(2*(z2+x2)*sinA2), 2*((y*z*sinA2)+(x*sinA*cosA))],
[2*((z*x*sinA2)+(y*sinA*cosA)), 2*((z*y*sinA2)-(x*sinA*cosA)), 1-(2*(x2+y2)*sinA2)]];
}
return m;
};
// Perspective Transform
// assumes world's been rotated appropriately such that Z is depth
// scales perspective such that inside depth regions min_real_depth <--> max_real_depth
// perspective lengths vary no more than: desired_ratio
// with target dimension of roughly length: desired_length
const perspT = function(vec3, max_real_depth, min_real_depth,
desired_ratio, desired_length) {
const z0 =
((max_real_depth * desired_ratio) - min_real_depth) / (1-desired_ratio);
const scalefactor =
(desired_length * desired_ratio) / (1-desired_ratio);
// projected [X, Y]
return [(scalefactor*vec3[0])/(vec3[2]+z0), (scalefactor*vec3[1])/(vec3[2]+z0)];
};
// Inverses perspective transform by projecting plane onto a unit sphere at origin
const invperspT =
function(x, y, dx, dy, max_real_depth, min_real_depth,
desired_ratio, desired_length) {
const z0 =
((max_real_depth * desired_ratio) - min_real_depth)/(1-desired_ratio);
const s = (desired_length * desired_ratio)/(1-desired_ratio);
const xp = x-dx;
const yp = y-dy;
const s2 = s*s;
const z02 = z0*z0;
const xp2 = xp*xp;
const yp2 = yp*yp;
const xsphere = ((2*s*xp*z0)
+ sqrt((4*s2*xp2*z02)
+ (4*xp2*(s2+xp2+yp2)*(1-z02))))/(2.0*(s2+xp2+yp2));
const ysphere = (((s*yp*z0)/(s2+xp2+yp2))
+ ((yp*sqrt((4*s2*z02)
+ (4*(s2+xp2+yp2)*(1-z02))))/(2.0*(s2+xp2+yp2))));
const zsphere = sqrt(1 - (xsphere*xsphere) - (ysphere*ysphere));
return [xsphere, ysphere, zsphere];
};
// Returns rotation matrix that takes vec1 to vec2
const getVec2VecRotM = function(vec1, vec2){
const axis = cross(vec1, vec2);
const angle = acos(dot(vec1, vec2));
return vec_rotm(-1*angle, axis[0], axis[1], axis[2]);
};
// Polyhédronisme
//===================================================================================================
//
// A toy for constructing and manipulating polyhedra.
//
// Copyright 2019, Anselm Levskaya
// Released under the MIT License
//
function __range__(left, right, inclusive) {
let range = [];
let ascending = left < right;
let end = !inclusive ? right : ascending ? right + 1 : right - 1;
for (let i = left; ascending ? i < end : i > end; ascending ? i++ : i--) {
range.push(i);
}
return range;
}
// Polyhedra Functions
//=================================================================================================
//
// Topology stored as set of faces. Each face is list of n vertex indices
// corresponding to one oriented, n-sided face. Vertices listed clockwise as seen from outside.
// Generate an array of edges [v1,v2] for the face.
const faceToEdges = function(face) {
const edges = [];
let [v1] = face.slice(-1);
for (let v2 of face) {
edges.push([v1, v2]);
v1 = v2;
}
return edges;
};
const vertColors = function(poly) {
const vertcolors=[];
for (let i = 0; i < poly.faces.length; i++) {
const face = poly.faces[i];
for (let v of face) {
vertcolors[v] = poly.face_classes[i];
}
}
return vertcolors;
};
// Polyhedra Coloring Functions
//=================================================================================================
const rwb_palette = ["#ff7777", "#dddddd", "#889999", "#fff0e5",
"#aa3333", "#ff0000", "#ffffff", "#aaaaaa"];
let PALETTE = rwb_palette; // GLOBAL
const palette = function(n) {
const k = n % PALETTE.length;
return hextofloats(PALETTE[k])
};
// converts [h,s,l] float args to [r,g,b] list
function hsl2rgb(h, s, l) {
let r, g, b;
if (s == 0) {
r = g = b = l; // achromatic
} else {
const hue2rgb = function(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
let q = l < 0.5 ? l * (1 + s) : l + s - l * s;
let p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [r, g, b];
}
// converts #xxxxxx / #xxx format into list of [r,g,b] floats
const hextofloats = function(hexstr){
let rgb;
if (hexstr[0] === "#") {
hexstr = hexstr.slice(1);
}
if (hexstr.length === 3) {
rgb = hexstr.split('').map(c=> parseInt(c+c, 16)/255);
} else {
rgb = hexstr.match(/.{2}/g).map(c=> parseInt(c, 16)/255);
}
return rgb;
};
// converts [r,g,b] floats to #xxxxxx form
const floatstohex = function(rgb){
let r_hex = Number(parseInt(255 * rgb[0], 10)).toString(16);
let g_hex = Number(parseInt(255 * rgb[1], 10)).toString(16);
let b_hex = Number(parseInt(255 * rgb[2], 10)).toString(16);
return "#" + r_hex + g_hex + b_hex;
}
// randomize color palette
const rndcolors = function(){
let newpalette=[];
for(let i=0; i<100; i++){
let h = random();
let s = 0.5*random() + 0.3;
let l = 0.5*random() + 0.45;
let rgb = hsl2rgb(h, s, l);
newpalette.push(floatstohex(rgb));
}
return newpalette;
}
// Color the faces of the polyhedra for display
const paintPolyhedron = function(poly) {
poly.face_classes = [];
const colormemory={};
// memoized color assignment to faces of similar areas
const colorassign = function(hash, colormemory) {
//const hash = ar;
if (hash in colormemory) {
return colormemory[hash];
} else {
const fclr = _.toArray(colormemory).length;
colormemory[hash] = fclr;
return fclr;
}
};
for (var f of poly.faces) {
var clr, face_verts;
if (COLOR_METHOD === "area") {
// color by face planar area assuming flatness
face_verts = f.map(v=>poly.vertices[v])
clr = colorassign(sigfigs(planararea(face_verts), COLOR_SENSITIVITY), colormemory);
} else if (COLOR_METHOD === "signature") {
// color by congruence signature
face_verts = f.map(v=>poly.vertices[v])
clr = colorassign(faceSignature(face_verts, COLOR_SENSITIVITY), colormemory);
} else {
// color by face-sidedness
clr = f.length - 3;
}
poly.face_classes.push(clr);
}
console.log(_.toArray(colormemory).length+" face classes");
return poly;
};
// z sorts faces of poly
// -------------------------------------------------------------------------
const sortfaces = function(poly) {
//smallestZ = (x) -> _.sortBy(x,(a,b)->a[2]-b[2])[0]
//closests = (smallestZ(poly.vertices[v] for v in f) for f in poly.faces)
let idx;
const centroids = poly.centers();
const normals = poly.normals();
const ray_origin = [0,0, ((persp_z_max * persp_ratio) - persp_z_min)/(1-persp_ratio)];
// sort by binary-space partition: are you on same side as view-origin or not?
// !!! there is something wrong with this. even triangulated surfaces have artifacts.
const planesort = (a,b) =>
//console.log dot(sub(ray_origin,a[0]),a[1]), dot(sub(b[0],a[0]),a[1])
-dot(sub(ray_origin,a[0]),a[1])*dot(sub(b[0],a[0]),a[1]);
// sort by centroid z-depth: not correct but more stable heuristic w. weird non-planar "polygons"
const zcentroidsort = (a, b) => a[0][2]-b[0][2];
const zsortIndex = _.zip(centroids, normals, __range__(0, poly.faces.length, false))
//.sort(planesort)
.sort(zcentroidsort)
.map(x=> x[2]);
// sort all face-associated properties
poly.faces = zsortIndex.map(idx=>poly.faces[idx]);
poly.face_classes = zsortIndex.map(idx=>poly.face_classes[idx]);
};
class polyhedron {
// constructor of initially null polyhedron
constructor(verts, faces, name) {
// array of faces. faces.length = # faces
this.faces = faces || new Array();
// array of vertex coords. vertices.length = # of vertices
this.vertices = verts || new Array();
this.name = name || "null polyhedron";
}
// return a non-redundant list of the polyhedron's edges
edges() {
let e, a, b;
const uniqEdges = {};
const faceEdges = this.faces.map(faceToEdges);
for (let edgeSet of faceEdges) {
for (e of edgeSet) {
if (e[0] < e[1]) {
[a, b] = e;
} else {
[b, a] = e;
}
uniqEdges[`${a}~${b}`] = e;
}
}
return _.values(uniqEdges);
}
// get array of face centers
centers() {
const centersArray = [];
for (let face of this.faces) {
let fcenter = [0, 0, 0];
// average vertex coords
for (let vidx of face) {
fcenter = add(fcenter, this.vertices[vidx]);
}
centersArray.push(mult(1.0 / face.length, fcenter));
}
// return face-ordered array of centroids
return centersArray;
}
// get array of face normals
normals() {
const normalsArray = [];
for (let face of this.faces) {
normalsArray.push(normal(face.map(vidx => this.vertices[vidx])));
}
return normalsArray;
}
// informative string
data() {
const nEdges = (this.faces.length + this.vertices.length) - 2; // E = V + F - 2
return `${this.faces.length} faces, ${nEdges} edges, ${this.vertices.length} vertices`;
}
moreData() {
return `min edge length ${this.minEdgeLength().toPrecision(2)}<br>` +
`min face radius ${this.minFaceRadius().toPrecision(2)}`;
}
minEdgeLength() {
let min2 = Number.MAX_VALUE;
// Compute minimum edge length
for (let e of this.edges()) {
// square of edge length
const d2 = mag2(sub(this.vertices[e[0]], this.vertices[e[1]]));
if (d2 < min2) {
min2 = d2;
}
}
// This is normalized if rescaling has happened.
return sqrt(min2);
}
minFaceRadius() {
let min2 = Number.MAX_VALUE;
const nFaces = this.faces.length;
const centers = this.centers();
for (let f = 0, end = nFaces; f < end; f++) {
const c = centers[f];
for (let e of faceToEdges(this.faces[f])) {
// Check distance from center to each edge.
const de2 = linePointDist2(this.vertices[e[0]], this.vertices[e[1]], c);
if (de2 < min2) {
min2 = de2;
}
}
}
return sqrt(min2);
}
// Export / Formatting Routines --------------------------------------------------
// produces vanilla OBJ files for import into 3d apps
toOBJ() {
let f;
let v;
let objstr="#Produced by polyHédronisme http://levskaya.github.com/polyhedronisme\n";
objstr+=`group ${this.name}\n`;
objstr+="#vertices\n";
for (v of this.vertices) {
objstr += `v ${v[0]} ${v[1]} ${v[2]}\n`;
}
objstr += "#normal vector defs \n";
for (f of this.faces) {
const norm = normal(f.map(v=>this.vertices[v]))
objstr += `vn ${norm[0]} ${norm[1]} ${norm[2]}\n`;
}
objstr += "#face defs \n";
for (let i = 0; i < this.faces.length; i++) {
f = this.faces[i];
objstr += "f ";
for (v of f) {
objstr += `${v+1}//${i+1} `;
}
objstr += "\n";
}
return objstr;
}
toX3D() {
let v;
// ShapeWays uses 1unit = 1meter, so reduce to 3cm scale
const SCALE_FACTOR = .03;
// opening cruft
let x3dstr=`\
<?xml version="1.0" encoding ="UTF-8"?>
<X3D profile="Interchange" version="3.0">
<head>
<component name="Rendering" level="3"/>
<meta name="generator" content="Polyhedronisme"/>
<meta name="version" content="0.1.0"/>
</head>
<Scene>
<Shape>
<IndexedFaceSet normalPerVertex="false" coordIndex="\
`;
// face indices
for (let f of this.faces) {
for (v of f) {
x3dstr+=`${v} `;
}
x3dstr+='-1\n';
}
x3dstr+='">\n';
// per-face Color
x3dstr+='<Color color="';
for (let cl of vertColors(this)) {//@face_class
const clr=palette(cl);
x3dstr+=`${clr[0]} ${clr[1]} ${clr[2]} `;
}
x3dstr+='"/>';
// re-scaled xyz coordinates
x3dstr+='<Coordinate point="';
for (v of this.vertices) {
x3dstr+=`${v[0]*SCALE_FACTOR} ${v[1]*SCALE_FACTOR} ${v[2]*SCALE_FACTOR} `;
}
x3dstr+='"/>\n';
// end cruft
x3dstr+=`\
</IndexedFaceSet>
</Shape>
</Scene>
</X3D>`;
return x3dstr;
}
toVRML() {
let v;
// ShapeWays uses 1unit = 1meter, so reduce to 3cm scale
const SCALE_FACTOR = .03;
// opening cruft
let x3dstr=`\
#VRML V2.0 utf8
#Generated by Polyhedronisme
NavigationInfo {
type [ "EXAMINE", "ANY" ]
}
Transform {
scale 1 1 1
translation 0 0 0
children
[
Shape
{
geometry IndexedFaceSet
{
creaseAngle .5
solid FALSE
coord Coordinate
{
point
[\
`;
// re-scaled xyz coordinates
for (v of this.vertices) {
x3dstr+=`${v[0]*SCALE_FACTOR} ${v[1]*SCALE_FACTOR} ${v[2]*SCALE_FACTOR},`;
}
x3dstr=x3dstr.slice(0, +-2 + 1 || undefined);
x3dstr+=`\
]
}
color Color
{
color
[\
`;
// per-face Color
for (let cl of this.face_classes) {
const clr=palette(cl);
x3dstr+=`${clr[0]} ${clr[1]} ${clr[2]} ,`;
}
x3dstr=x3dstr.slice(0, +-2 + 1 || undefined);
x3dstr+=`\
]
}
colorPerVertex FALSE
coordIndex
[\
`;
// face indices
for (let f of this.faces) {
for (v of f) {
x3dstr+=`${v}, `;
}
x3dstr+='-1,';
}
x3dstr=x3dstr.slice(0, +-2 + 1 || undefined);
x3dstr+=`\
]
}
appearance Appearance
{
material Material
{
ambientIntensity 0.2
diffuseColor 0.9 0.9 0.9
specularColor .1 .1 .1
shininess .5
}
}
}
]
}\
`;
return x3dstr;
}
}
//===================================================================================================
// Primitive Polyhedra Seeds
//===================================================================================================
const tetrahedron = function() {
const poly = new polyhedron();
poly.name = "T";
poly.faces = [ [0,1,2], [0,2,3], [0,3,1], [1,3,2] ];
poly.vertices = [ [1.0,1.0,1.0], [1.0,-1.0,-1.0], [-1.0,1.0,-1.0], [-1.0,-1.0,1.0] ];
return poly;
};
const octahedron = function() {
const poly = new polyhedron();
poly.name = "O";
poly.faces = [ [0,1,2], [0,2,3], [0,3,4], [0,4,1], [1,4,5], [1,5,2], [2,5,3], [3,5,4] ];
poly.vertices = [ [0,0,1.414], [1.414,0,0], [0,1.414,0], [-1.414,0,0], [0,-1.414,0], [0,0,-1.414] ];
return poly;
};
const cube = function() {
const poly = new polyhedron();
poly.name = "C";
poly.faces = [ [3,0,1,2], [3,4,5,0], [0,5,6,1], [1,6,7,2], [2,7,4,3], [5,4,7,6] ];
poly.vertices = [ [0.707,0.707,0.707], [-0.707,0.707,0.707], [-0.707,-0.707,0.707], [0.707,-0.707,0.707],
[0.707,-0.707,-0.707], [0.707,0.707,-0.707], [-0.707,0.707,-0.707], [-0.707,-0.707,-0.707] ];
return poly;
};
const icosahedron = function() {
const poly = new polyhedron();
poly.name = "I";
poly.faces = [ [0,1,2], [0,2,3], [0,3,4], [0,4,5],
[0,5,1], [1,5,7], [1,7,6], [1,6,2],
[2,6,8], [2,8,3], [3,8,9], [3,9,4],
[4,9,10], [4,10,5], [5,10,7], [6,7,11],
[6,11,8], [7,10,11], [8,11,9], [9,11,10] ];
poly.vertices = [ [0,0,1.176], [1.051,0,0.526],
[0.324,1.0,0.525], [-0.851,0.618,0.526],
[-0.851,-0.618,0.526], [0.325,-1.0,0.526],
[0.851,0.618,-0.526], [0.851,-0.618,-0.526],
[-0.325,1.0,-0.526], [-1.051,0,-0.526],
[-0.325,-1.0,-0.526], [0,0,-1.176] ];
return poly;
};
const dodecahedron = function() {
const poly = new polyhedron();
poly.name = "D";
poly.faces = [ [0,1,4,7,2], [0,2,6,9,3], [0,3,8,5,1],
[1,5,11,10,4], [2,7,13,12,6], [3,9,15,14,8],
[4,10,16,13,7], [5,8,14,17,11], [6,12,18,15,9],
[10,11,17,19,16], [12,13,16,19,18], [14,15,18,19,17] ];
poly.vertices = [ [0,0,1.07047], [0.713644,0,0.797878],
[-0.356822,0.618,0.797878], [-0.356822,-0.618,0.797878],
[0.797878,0.618034,0.356822], [0.797878,-0.618,0.356822],
[-0.934172,0.381966,0.356822], [0.136294,1.0,0.356822],
[0.136294,-1.0,0.356822], [-0.934172,-0.381966,0.356822],
[0.934172,0.381966,-0.356822], [0.934172,-0.381966,-0.356822],
[-0.797878,0.618,-0.356822], [-0.136294,1.0,-0.356822],
[-0.136294,-1.0,-0.356822], [-0.797878,-0.618034,-0.356822],
[0.356822,0.618,-0.797878], [0.356822,-0.618,-0.797878],
[-0.713644,0,-0.797878], [0,0,-1.07047] ];
return poly;
};
const prism = function(n) {
let i;
const theta = (2*PI)/n; // pie angle
const h = Math.sin(theta/2); // half-edge
let poly = new polyhedron();
poly.name = `P${n}`;
for (i = 0; i < n; i++) { // vertex #'s 0 to n-1 around one face
poly.vertices.push([-cos(i*theta), -sin(i*theta), -h]);
}
for (i = 0; i < n; i++) { // vertex #'s n to 2n-1 around other
poly.vertices.push([-cos(i*theta), -sin(i*theta), h]);
}
poly.faces.push(__range__(n-1, 0, true)); //top
poly.faces.push(__range__(n, 2*n, false)); //bottom
for (i = 0; i < n; i++) { //n square sides
poly.faces.push([i, (i+1)%n, ((i+1)%n)+n, i+n]);
}
poly = adjustXYZ(poly,1);
return poly;
};
const antiprism = function(n) {
let i;
const theta = (2*PI)/n; // pie angle
let h = sqrt(1-(4/((4+(2*cos(theta/2)))-(2*cos(theta)))));
let r = sqrt(1-(h*h));
const f = sqrt((h*h) + pow(r*cos(theta/2),2));
// correction so edge midpoints (not vertices) on unit sphere
r = -r/f;
h = -h/f;
let poly = new polyhedron();
poly.name = `A${n}`;
for (i = 0; i < n; i++) { // vertex #'s 0...n-1 around one face
poly.vertices.push([r * cos(i*theta), r * sin(i*theta), h]);
}
for (i = 0; i < n; i++) { // vertex #'s n...2n-1 around other
poly.vertices.push([r * cos((i+0.5)*theta), r * sin((i+0.5)*theta), -h]);
}
poly.faces.push(__range__(n-1, 0, true)); //top
poly.faces.push(__range__(n, (2*n)-1, true)); //bottom
for (i = 0; i <= n-1; i++) { //2n triangular sides
poly.faces.push([i, (i+1)%n, i+n]);
poly.faces.push([i, i+n, ((((n+i)-1)%n)+n)]);
}
poly = adjustXYZ(poly,1);
return poly;
};
const pyramid = function(n) {
let i;
const theta = (2*PI)/n; // pie angle
const height = 1;
let poly = new polyhedron();
poly.name = `Y${n}`;
for (i = 0; i < n; i++) { // vertex #'s 0...n-1 around one face
poly.vertices.push([-cos(i*theta), -sin(i*theta), -0.2]);
}
poly.vertices.push([0,0, height]); // apex
poly.faces.push(__range__(n-1, 0, true)); // base
for (i = 0; i < n; i++) { // n triangular sides
poly.faces.push([i, (i+1)%n, n]);
}
poly = canonicalXYZ(poly, 3);
return poly;
};
const cupola = function(n, alpha, height) {
let i;
if (n===undefined) { n = 3; }
if (alpha===undefined) { alpha = 0.0; }
let poly = new polyhedron();
poly.name = `U${n}`;
if (n < 2) {
return poly;
}
let s = 1.0;
// alternative face/height scaling
//let rb = s / 2 / sin(PI / 2 / n - alpha);
let rb = s / 2 / sin(PI / 2 / n);
let rt = s / 2 / sin(PI / n);
if (height===undefined) {
height = (rb - rt);
// set correct height for regularity for n=3,4,5
if (2 <= n && n <= 5) {
height = s * sqrt(1 - 1 / 4 / sin(PI/n) / sin(PI/n));
}
}
// init 3N vertices
for (i = 0; i < 3*n; i++) {
poly.vertices.push([0,0,0]);
}
// fill vertices
for (i = 0; i < n; i++) {
poly.vertices[2*i] = [rb * cos(PI*(2*i)/n + PI/2/n+alpha),
rb * sin(PI*(2*i)/n + PI/2/n+alpha),
0.0];
poly.vertices[2*i+1] = [rb * cos(PI*(2*i+1)/n + PI/2/n-alpha),
rb * sin(PI*(2*i+1)/n + PI/2/n-alpha),
0.0];
poly.vertices[2*n+i] = [rt * cos(2*PI*i/n),
rt * sin(2*PI*i/n),
height];
}
poly.faces.push(__range__(2*n-1, 0, true)); // base
poly.faces.push(__range__(2*n, 3*n-1, true)); // top
for (i = 0; i < n; i++) { // n triangular sides and n square sides
poly.faces.push([(2*i+1)%(2*n), (2*i+2)%(2*n), 2*n+(i+1)%n]);
poly.faces.push([2*i, (2*i+1)%(2*n), 2*n+(i+1)%n, 2*n+i]);
}
return poly;
}
const anticupola = function(n, alpha, height) {
let i;