-
Notifications
You must be signed in to change notification settings - Fork 0
/
tiny-graphics.js
1209 lines (1061 loc) · 52.5 KB
/
tiny-graphics.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
// tiny-graphics.js - A file that shows how to organize a complete graphics program.
// It wraps common WebGL commands, math, and web page interactions. (by Garett Ridge)
//
// @class Vec
// Vectors of floating point numbers. This puts vector math into JavaScript.
// See these examples for usage of each function:
// equals: "Vec.of( 1,0,0 ).equals( Vec.of( 1,0,0 ) )" returns true.
// plus: "Vec.of( 1,0,0 ).plus ( Vec.of( 1,0,0 ) )" returns the Vec [ 2,0,0 ].
// minus: "Vec.of( 1,0,0 ).minus ( Vec.of( 1,0,0 ) )" returns the Vec [ 0,0,0 ].
// mult-pairs: "Vec.of( 1,2,3 ).mult_pairs( Vec.of( 3,2,0 ) )" returns the Vec [ 3,4,0 ].
// scale: "Vec.of( 1,2,3 ).scale( 2 )" overwrites the Vec with [ 2,4,6 ].
// times: "Vec.of( 1,2,3 ).times( 2 )" returns the Vec [ 2,4,6 ].
// randomized: Returns this Vec plus a random vector of a given maximum length.
// mix: "Vec.of( 0,2,4 ).mix( Vec.of( 10,10,10 ), .5 )" returns the Vec [ 5,6,7 ].
// norm: "Vec.of( 1,2,3 ).norm()" returns the square root of 15.
// normalized: "Vec.of( 4,4,4 ).normalized()" returns the Vec [ sqrt(3), sqrt(3), sqrt(3) ]
// normalize: "Vec.of( 4,4,4 ).normalize()" overwrites the Vec with [ sqrt(3), sqrt(3), sqrt(3) ].
// dot: "Vec.of( 1,2,3 ).dot( Vec.of( 1,2,3 ) )" returns 15.
// cast: "Vec.cast( [-1,-1,0], [1,-1,0], [-1,1,0] )" converts a list of Array literals into a list of Vecs.
// to3: "Vec.of( 1,2,3,4 ).to3()" returns the Vec [ 1,2,3 ]. Use only on 4x1 Vecs to truncate them.
// to4: "Vec.of( 1,2,3 ).to4( true or false )" returns the homogeneous Vec [ 1,2,3, 1 or 0 ]. Use only on 3x1.
// cross: "Vec.of( 1,0,0 ).cross( Vec.of( 0,1,0 ) )" returns the Vec [ 0,0,1 ]. Use only on 3x1 Vecs.
// to_string: "Vec.of( 1,2,3 ).to_string()" returns "[vec 1, 2, 3]"
// Notes: Vecs should only be created with of() due to wierdness with the TypedArray spec.
// Also, assign them with .copy() to avoid referring two variables to the same Vec object.
class Vec extends Float32Array {
copy() {
return Vec.from(this)
}
equals(b) {
return this.every((x, i) => x == b[i])
}
plus(b) {
return this.map((x, i) => x + b[i])
}
minus(b) {
return this.map((x, i) => x - b[i])
}
mult_pairs(b) {
return this.map((x, i) => x * b[i])
}
scale(s) {
this.forEach((x, i, a) => a[i] *= s)
}
times(s) {
return this.map(x => s * x)
}
randomized(s) {
return this.map(x => x + s * (Math.random() - .5))
}
mix(b, s) {
return this.map((x, i) => (1 - s) * x + s * b[i])
}
norm() {
return Math.sqrt(this.dot(this))
}
normalized() {
return this.times(1 / this.norm())
}
normalize() {
this.scale(1 / this.norm())
}
// Optimized arithmetic unrolls loops for vectors of length <= 4.
dot(b) {
if (this.length == 3) return this[0] * b[0] + this[1] * b[1] + this[2] * b[2];
if (this.length == 4) return this[0] * b[0] + this[1] * b[1] + this[2] * b[2] + this[3] * b[3];
if (this.length > 4) return this.reduce((acc, x, i) => {
return acc + x * b[i];
}, 0);
// Assume a minimum length of 2.
return this[0] * b[0] + this[1] * b[1];
}
// For avoiding repeatedly typing Vec.of in lists.
static cast(...args) {
return args.map(x => Vec.from(x));
}
to3() {
return Vec.of(this[0], this[1], this[2]);
}
to4(isPoint) {
return Vec.of(this[0], this[1], this[2], +isPoint);
}
cross(b) {
return Vec.of(this[1] * b[2] - this[2] * b[1], this[2] * b[0] - this[0] * b[2], this[0] * b[1] - this[1] * b[0]);
}
to_string() {
return "[vec " + this.join(", ") + "]"
}
// mine
inverse() {
return this.map(x => 1/x);
}
project_onto(v) {
var v_norm2 = v.dot(v);
return v_norm2 ? v.times(this.dot(v)/v_norm2) : this.times(0);
}
pow(s) {
return this.map(x => x ** s)
}
}
const arrSum = arr => arr.reduce((a,b) => a + b, 0);
class Quaternion extends Vec {
get w() { return this[0]; }
get v() { return Vec.of(this[1], this[2], this[3]); }
static unit() {
return Quaternion.from(1);
}
times(q) {
if (!isNaN(q))
return super.times(q);
var p = this,
rw = p.w*q.w - p.v.dot(q.v),
rv = p.v.times(q.w).plus(
q.v.times(p.w)).plus(
p.v.cross(q.v));
return Quaternion.from(rw, rv);
}
static from(w, v) {
if (v == undefined)
v = Vec.of(0, 0, 0);
return Quaternion.of(w, v[0], v[1], v[2]);
}
static from_rot(R) {
var trace = R[0][0] + R[1][1] + R[2][2],
mag_theta = Math.acos((trace - 1)/2),
u = Vec.of(R[2][1] - R[1][2], R[0][2] - R[2][0], R[1][0] - R[0][1]),
theta = Math.asin(u.norm()/2);
return Quaternion.from(Math.cos(theta/2), u.times(Math.sin(theta/2)));
}
static unit() {
return Quaternion.of(1, 0, 0, 0);
}
inverse() {
return Quaternion.of(this[0], -this[1], -this[2], -this[3]);
}
}
// @class Mat
// M by N matrices of floats. Enables matrix and vector math. Usage:
// "Mat( rows )" returns a Mat with those rows, where rows is an array of float arrays.
// "M.set_identity( m, n )" assigns the m by n identity matrix to Mat M.
// "M.sub_block( start, end )" where start and end are each a [ row, column ] pair returns a sub-rectangle cut out from M.
// "M.copy()" creates a deep copy of M and returns it so you can modify it without affecting the original.
// "M.equals(b)" as well as plus and minus work the same as for Vec but the two operands are Mats instead; b must be a Mat.
// "M.transposed()" returns a new matrix where all rows of M became columns and vice versa.
// "M.times(b)" (where the post-multiplied b can be a scalar, a Vec, or another Mat) returns a new Mat or Vec holding the product.
// "M.pre_multiply(b)" overwrites the matrix M with the product of b * M where b must be another Mat.
// "M.post_multiply(b)" overwrites the matrix M with the product of M * b where b can be a Mat, Vec, or scalar.
// "Mat.flatten_2D_to_1D( M )" flattens input (a Mat or any array of Vecs or float arrays) into a row-major 1D array of raw floats.
// "M.to_string()" where M contains the 4x4 identity returns "[[1, 0, 0, 0] [0, 1, 0, 0] [0, 0, 1, 0] [0, 0, 0, 1]]".
class Mat extends Array {
constructor(...args) {
super(0);
this.push(...args)
}
set_identity(m, n) {
this.length = 0;
for (let i = 0; i < m; i++) {
this.push(Array(n).fill(0));
if (i < n) this[i][i] = 1;
}
}
sub_block(start, end) {
return Mat.from(this.slice(start[0], end[0]).map(r => r.slice(start[1], end[1])));
}
copy() {
return this.map(r => Vec.of(...r))
}
equals(b) {
return this.every((r, i) => r.every((x, j) => x == b[i][j]))
}
plus(b) {
return this.map((r, i) => r.map((x, j) => x + b[i][j]))
}
minus(b) {
return this.map((r, i) => r.map((x, j) => x - b[i][j]))
}
transposed() {
return this.map((r, i) => r.map((x, j) => this[j][i]))
}
times(b) {
const len = b.length;
if (typeof len === "undefined") return this.map(r => r.map(x => b * x)); // Mat * scalar case.
const len2 = b[0].length;
if (typeof len2 === "undefined") {
let result = new Vec(this.length); // Mat * Vec case.
for (let r = 0; r < len; r++) result[r] = b.dot(this[r]);
return result;
}
let result = Mat.from(new Array(this.length));
for (let r = 0; r < this.length; r++) // Mat * Mat case.
{
result[r] = new Array(len2);
for (let c = 0, sum = 0; c < len2; c++) {
result[r][c] = 0;
for (let r2 = 0; r2 < len; r2++)
result[r][c] += this[r][r2] * b[r2][c];
}
}
return result;
}
pre_multiply(b) {
const new_value = b.times(this);
this.length = 0;
this.push(...new_value);
return this;
}
post_multiply(b) {
const new_value = this.times(b);
this.length = 0;
this.push(...new_value);
return this;
}
static flatten_2D_to_1D(M) {
let index = 0,
floats = new Float32Array(M.length && M.length * M[0].length);
for (let i = 0; i < M.length; i++)
for (let j = 0; j < M[i].length; j++) floats[index++] = M[i][j];
return floats;
}
to_string() {
return "[" + this.map((r, i) => "[" + r.join(", ") + "]").join(" ") + "]"
}
}
class Mat3 extends Mat {
static identity() {
return Mat.of([1, 0, 0], [0, 1, 0], [0, 0, 1]);
};
static det(m) {
const m00 = m[0][0],
m01 = m[0][1],
m02 = m[0][2],
m10 = m[1][0],
m11 = m[1][1],
m12 = m[1][2],
m20 = m[2][0],
m21 = m[2][1],
m22 = m[2][2];
return m00 * (m11 * m22 - m12 * m21) -
m01 * (m10 * m22 - m12 * m20) +
m02 * (m10 * m21 - m11 * m20);
}
static sym_product(ra, rb) {
let xa = ra[0], ya = ra[1], za = ra[2],
xb = rb[0], yb = rb[1], zb = rb[2];
const m00 = ya*yb + za*zb,
m01 = 1/2 * (za*yb + ya*xb),
m02 = 1/2 * (xa*zb + za*xb),
m11 = xa*xb + za*zb,
m12 = 1/2 * (ya*zb + za*yb),
m22 = xa*xb + ya*yb;
return Mat3.of(
[m00, m01, m02],
[m01, m11, m12],
[m02, m12, m22]
);
}
}
// Generate special 4x4 matrices that are useful for graphics.
class Mat4 extends Mat {
static identity() {
return Mat.of([1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]);
};
// Requires a scalar (angle) and a 3x1 Vec (axis)
static rotation(angle, axis)
{
let [x, y, z] = axis.normalized(), [c, s] = [Math.cos(angle), Math.sin(angle)], omc = 1.0 - c;
return Mat.of(
[x * x * omc + c, x * y * omc - z * s, x * z * omc + y * s, 0],
[x * y * omc + z * s, y * y * omc + c, y * z * omc - x * s, 0],
[x * z * omc - y * s, y * z * omc + x * s, z * z * omc + c, 0],
[0, 0, 0, 1]);
}
// Requires a 3x1 Vec.
static scale(s) {
if (typeof s === "number")
s = [s, s, s];
return Mat.of([s[0], 0, 0, 0], [0, s[1], 0, 0], [0, 0, s[2], 0], [0, 0, 0, 1]);
}
// Requires a 3x1 Vec.
static translation(t) {
return Mat.of([1, 0, 0, t[0]], [0, 1, 0, t[1]], [0, 0, 1, t[2]], [0, 0, 0, 1]);
}
// Note: look_at() assumes the result will be used for a camera and stores its result in inverse space.
// You can also use it to point the basis of any *object* towards anything but you must re-invert it first.
// Each input must be 3x1 Vec.
static look_at(eye, at, up) {
let z = at.minus(eye).normalized(),
x = z.cross(up).normalized(), // Compute vectors along the requested coordinate axes.
y = x.cross(z).normalized(); // This is the "updated" and orthogonalized local y axis.
if (!x.every(i => i == i)) // Check for NaN, indicating a degenerate cross product, which
throw "Two parallel vectors were given"; // happens if eye == at, or if at minus eye is parallel to up.
z.scale(-1); // Enforce right-handed coordinate system.
return Mat4.translation([-x.dot(eye), -y.dot(eye), -z.dot(eye)])
.times(Mat.of(x.to4(0), y.to4(0), z.to4(0), Vec.of(0, 0, 0, 1)));
}
// Box-shaped view volume for projection.
static orthographic(left, right, bottom, top, near, far) {
return Mat4.scale(Vec.of(1 / (right - left), 1 / (top - bottom), 1 / (far - near)))
.times(Mat4.translation(Vec.of(-left - right, -top - bottom, -near - far)))
.times(Mat4.scale(Vec.of(2, 2, -2)));
}
// Frustum-shaped view volume for projection.
static perspective(fov_y, aspect, near, far) {
const f = 1 / Math.tan(fov_y / 2),
d = far - near;
return Mat.of([f / aspect, 0, 0, 0], [0, f, 0, 0], [0, 0, -(near + far) / d, -2 * near * far / d], [0, 0, -1, 0]);
}
// Computing a 4x4 inverse is slow because of the amount of steps; call fewer times when possible.
static inverse(m) {
const result = Mat4.identity(),
m00 = m[0][0],
m01 = m[0][1],
m02 = m[0][2],
m03 = m[0][3],
m10 = m[1][0],
m11 = m[1][1],
m12 = m[1][2],
m13 = m[1][3],
m20 = m[2][0],
m21 = m[2][1],
m22 = m[2][2],
m23 = m[2][3],
m30 = m[3][0],
m31 = m[3][1],
m32 = m[3][2],
m33 = m[3][3];
result[0][0] = m12 * m23 * m31 - m13 * m22 * m31 + m13 * m21 * m32 - m11 * m23 * m32 - m12 * m21 * m33 + m11 * m22 * m33;
result[0][1] = m03 * m22 * m31 - m02 * m23 * m31 - m03 * m21 * m32 + m01 * m23 * m32 + m02 * m21 * m33 - m01 * m22 * m33;
result[0][2] = m02 * m13 * m31 - m03 * m12 * m31 + m03 * m11 * m32 - m01 * m13 * m32 - m02 * m11 * m33 + m01 * m12 * m33;
result[0][3] = m03 * m12 * m21 - m02 * m13 * m21 - m03 * m11 * m22 + m01 * m13 * m22 + m02 * m11 * m23 - m01 * m12 * m23;
result[1][0] = m13 * m22 * m30 - m12 * m23 * m30 - m13 * m20 * m32 + m10 * m23 * m32 + m12 * m20 * m33 - m10 * m22 * m33;
result[1][1] = m02 * m23 * m30 - m03 * m22 * m30 + m03 * m20 * m32 - m00 * m23 * m32 - m02 * m20 * m33 + m00 * m22 * m33;
result[1][2] = m03 * m12 * m30 - m02 * m13 * m30 - m03 * m10 * m32 + m00 * m13 * m32 + m02 * m10 * m33 - m00 * m12 * m33;
result[1][3] = m02 * m13 * m20 - m03 * m12 * m20 + m03 * m10 * m22 - m00 * m13 * m22 - m02 * m10 * m23 + m00 * m12 * m23;
result[2][0] = m11 * m23 * m30 - m13 * m21 * m30 + m13 * m20 * m31 - m10 * m23 * m31 - m11 * m20 * m33 + m10 * m21 * m33;
result[2][1] = m03 * m21 * m30 - m01 * m23 * m30 - m03 * m20 * m31 + m00 * m23 * m31 + m01 * m20 * m33 - m00 * m21 * m33;
result[2][2] = m01 * m13 * m30 - m03 * m11 * m30 + m03 * m10 * m31 - m00 * m13 * m31 - m01 * m10 * m33 + m00 * m11 * m33;
result[2][3] = m03 * m11 * m20 - m01 * m13 * m20 - m03 * m10 * m21 + m00 * m13 * m21 + m01 * m10 * m23 - m00 * m11 * m23;
result[3][0] = m12 * m21 * m30 - m11 * m22 * m30 - m12 * m20 * m31 + m10 * m22 * m31 + m11 * m20 * m32 - m10 * m21 * m32;
result[3][1] = m01 * m22 * m30 - m02 * m21 * m30 + m02 * m20 * m31 - m00 * m22 * m31 - m01 * m20 * m32 + m00 * m21 * m32;
result[3][2] = m02 * m11 * m30 - m01 * m12 * m30 - m02 * m10 * m31 + m00 * m12 * m31 + m01 * m10 * m32 - m00 * m11 * m32;
result[3][3] = m01 * m12 * m20 - m02 * m11 * m20 + m02 * m10 * m21 - m00 * m12 * m21 - m01 * m10 * m22 + m00 * m11 * m22;
// Divide by determinant and return.
return result.times(1 / (m00 * result[0][0] + m10 * result[0][1] + m20 * result[0][2] + m30 * result[0][3]));
}
static quaternion_rotation(q) {
let a = q[0], b = q[1], c = q[2], d = q[3];
return Mat4.of(
[a*a + b*b - c*c - d*d, 2*b*c - 2*a*d, 2*b*d + 2*a*c, 0],
[2*b*c + 2*a*d, a*a - b*b + c*c - d*d, 2*c*d - 2*a*b, 0],
[2*b*d - 2*a*c, 2*c*d + 2*a*b, a*a - b*b - c*c + d*d, 0],
[0, 0, 0, 1]
)
}
static y_to_vec(v, at) {
let scale = v.norm(),
phi = Math.atan(v[1]/Math.sqrt(v[0]**2 + v[2]**2)),
theta = Math.atan(v[0]/v[2]) + PI*(v[2] < 0);
if (!scale)
return Mat4.scale(Vec.of(0, 0, 0));
if (isNaN(phi))
phi = PI;
if (isNaN(theta))
theta = PI;
return Mat4.translation(at).times(
Mat4.rotation(theta, Vec.of(0, 1, 0))).times(
Mat4.rotation(PI/2 - phi, Vec.of(1, 0, 0))).times(
Mat4.scale(Vec.of(1, scale, 1)));
}
}
class Triangle extends Array {
constructor(a, b, c) {
super(a, b, c);
this.normal = b.minus(a).cross(c.minus(a)).normalized();
// if (this.normal.dot(a) < 0)
// this.normal = this.normal.times(-1);
}
get a() { return this[0]; }
get b() { return this[1]; }
get c() { return this[2]; }
static of(a, b, c) {
return new Triangle(a, b, c);
}
projection_of(v) {
var b, c;
if (Math.abs(v[0]) >= 0.57735)
b = Vec.of(v[1], -v[0], 0);
else
b = Vec.of(0, v[2], -v[1]);
b.normalize();
c = a.cross(b);
return b.times(b.dot(v)).plus(c.times(c.dot(v)));
}
}
class Edge {
constructor(a, b) {
this.a = a;
this.b = b;
}
static of(a, b) {
return new Edge(a, b);
}
}
// This class maintains a running list of which keys are depressed. You can map combinations of shortcut
// keys to trigger callbacks you provide by calling add(). See add()'s arguments. The shortcut list is
// indexed by convenient strings showing each bound shortcut combination. The constructor optionally
// takes "target", which is the desired DOM element for keys to be pressed inside of, and
// "callback_behavior", which will be called for every key action and allows extra behavior on each event
// -- giving an opportunity to customize their bubbling, preventDefault, and more. It defaults to no
// additional behavior besides the callback itself on each assigned key action.
class Keyboard_Manager {
constructor(target = document, callback_behavior = (callback, event) => callback(event)) {
this.saved_controls = {};
this.actively_pressed_keys = new Set();
this.callback_behavior = callback_behavior;
target.addEventListener("keydown", this.key_down_handler.bind(this));
target.addEventListener("keyup", this.key_up_handler.bind(this));
window.addEventListener("focus", () => this.actively_pressed_keys.clear()); // Deal with stuck keys during focus change.
}
key_down_handler(event) {
// Don't interfere with typing.
if (["INPUT", "TEXTAREA"].includes(event.target.tagName))
return;
// Track the pressed key.
this.actively_pressed_keys.add(event.key);
// Re-check all the keydown handlers.
for (let saved of Object.values(this.saved_controls)) {
// Modifiers must exactly match.
if (saved.shortcut_combination.every(s => this.actively_pressed_keys.has(s))
&& event.ctrlKey == saved.shortcut_combination.includes("Control")
&& event.shiftKey == saved.shortcut_combination.includes("Shift")
&& event.altKey == saved.shortcut_combination.includes("Alt")
&& event.metaKey == saved.shortcut_combination.includes("Meta"))
// The keys match, so fire the callback.
this.callback_behavior(saved.callback, event);
}
}
key_up_handler(event) {
const lower_symbols = "qwertyuiopasdfghjklzxcvbnm1234567890-=[]\\;',./",
upper_symbols = "QWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*()_+{}|:\"<>?";
const lifted_key_symbols = [event.key, upper_symbols[lower_symbols.indexOf(event.key)],
lower_symbols[upper_symbols.indexOf(event.key)]
];
// Call keyup for any shortcuts
for (let saved of Object.values(this.saved_controls)) // that depended on the released
if (lifted_key_symbols.some(s => saved.shortcut_combination.includes(s))) // key or its shift-key counterparts.
this.callback_behavior(saved.keyup_callback, event); // The keys match, so fire the callback.
lifted_key_symbols.forEach(k => this.actively_pressed_keys.delete(k));
}
// Method add() adds a keyboard operation. The argument shortcut_combination wants an array of strings that follow
// standard KeyboardEvent key names. Both the keyup and keydown callbacks for any key combo are optional.
add(shortcut_combination, callback = () => {}, keyup_callback = () => {}) {
this.saved_controls[shortcut_combination.join('+')] = {
shortcut_combination, callback, keyup_callback
};
}
}
// Break up a string containing code (any es6 JavaScript). The parser expression
// is from https://github.com/lydell/js-tokens which states the following limitation:
class Code_Manager {
// "If the end of a statement looks like a regex literal (even if it isn’t), it will
constructor(code) {
const es6_tokens_parser = RegExp([ // be treated as one." (This can miscolor lines of code containing divisions and comments).
// Any string.
/((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)/,
// Any comment (2 forms).
/(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)/,
// And next, any regex:
/(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyu]{1,5}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))/,
// Any number.
/(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)/,
// Any name.
/((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)/,
// Any punctuator.
/(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])/,
// Any whitespace. Lastly, blank/invalid.
/(\s+)|(^$|[\s\S])/
].map(r => r.source).join('|'), 'g');
this.tokens = [];
this.no_comments = [];
let single_token = null;
while ((single_token = es6_tokens_parser.exec(code)) !== null) {
let token = {
type: "invalid",
value: single_token[0]
}
if (single_token[1])
token.type = "string", token.closed = !!(single_token[3] || single_token[4]);
else if (single_token[5])
token.type = "comment";
else if (single_token[6])
token.type = "comment", token.closed = !!single_token[7];
else if (single_token[8])
token.type = "regex";
else if (single_token[9])
token.type = "number";
else if (single_token[10])
token.type = "name";
else if (single_token[11])
token.type = "punctuator";
else if (single_token[12])
token.type = "whitespace";
this.tokens.push(token);
if (token.type != "whitespace" && token.type != "comment")
this.no_comments.push(token.value);
}
}
}
// To use Vertex_Buffer, make a subclass of it that overrides the constructor and fills in the right fields.
// Vertex_Buffer organizes data related to one 3D shape and copies it into GPU memory. That data is broken
// down per vertex in the shape. You can make several fields that you can look up in a vertex; for each
// field, a whole array will be made here of that data type and it will be indexed per vertex. Along with
// those lists is an additional array "indices" describing triangles, expressed as triples of vertex indices,
// connecting the vertices to one another.
class Vertex_Buffer {
// This superclass constructor expects a list of names of arrays that you plan for
// your subclass to fill in and associate with the vertices.
constructor(...array_names) {
this.array_names = array_names;
// Initialize a blank array member of the Shape with each of the names provided.
for (let n of array_names)
this[n] = [];
this.indices = [];
// By default all shapes assume indexed drawing using drawElements().
this.indexed = true;
// Get ready to associate a GPU buffer with each array.
this.array_names_mapping_to_WebGLBuffers = {};
}
// Send the completed vertex and index lists to their own buffers in the graphics card.
// Optional arguments allow calling this again to overwrite some or all GPU buffers as needed.
copy_onto_graphics_card(gl, selection_of_arrays = this.array_names, write_to_indices = true) {
for (let n of selection_of_arrays) {
let buffer = this.array_names_mapping_to_WebGLBuffers[n] = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, Mat.flatten_2D_to_1D(this[n]), gl.STATIC_DRAW);
}
if (this.indexed && write_to_indices) {
// Load an extension to allow shapes with more vertices than type "short" can hold.
gl.getExtension("OES_element_index_uint");
this.index_buffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.index_buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(this.indices), gl.STATIC_DRAW);
}
this.gl = gl;
}
// Draws this shape's entire vertex buffer.
execute_shaders(gl, type) {
if (this.indexed) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.index_buffer);
gl.drawElements(this.gl[type], this.indices.length, gl.UNSIGNED_INT, 0)
}
else {
// If no indices were provided, assume the vertices are arranged
// as triples of positions in a field called "positions".
gl.drawArrays(this.gl[type], 0, this.positions.length);
}
}
// To appear onscreen, a shape of any variety goes through this draw() function, which
// executes the shader programs. The shaders draw the right shape due to pre-selecting
// the correct buffer region in the GPU that holds that shape's data.
draw(graphics_state, model_transform, material, type = "TRIANGLES", gl = this.gl) {
if (!this.gl) throw "This shape's arrays are not copied over to graphics card yet.";
material.shader.activate();
material.shader.update_GPU(graphics_state, model_transform, material);
for (let [attr_name, attribute] of Object.entries(material.shader.g_addrs.shader_attributes)) {
const buffer_name = material.shader.map_attribute_name_to_buffer_name(attr_name)
if (!buffer_name || !attribute.enabled) {
if (attribute.index >= 0) gl.disableVertexAttribArray(attribute.index);
continue;
}
gl.enableVertexAttribArray(attribute.index);
// Activate the correct buffer.
gl.bindBuffer(gl.ARRAY_BUFFER, this.array_names_mapping_to_WebGLBuffers[buffer_name]);
// Populate each attribute from the active buffer.
gl.vertexAttribPointer(attribute.index, attribute.size, attribute.type,
attribute.normalized, attribute.stride, attribute.pointer);
}
// Run the shaders to draw every triangle now.
this.execute_shaders(gl, type);
}
}
// This class is used the same way as Vertex_Buffer, by subclassing it and writing a constructor that fills in certain fields.
// Shape extends Vertex_Buffer's functionality for copying shapes into buffers the graphics card's memory. It also adds the
// basic assumption that each vertex will have a 3D position and a 3D normal vector as available fields to look up. This means
// there will be at least two arrays for the user to fill in: "positions" enumerating all the vertices' locations, and "normals"
// enumerating all vertices' normal vectors pointing away from the surface. Both are of type Vec of length 3. By including
// these, Shape adds to class Vertex_Buffer the ability to compound shapes in together into a single performance-friendly
// Vertex_Buffer, placing this shape into a larger one at a custom transforms by adjusting positions and normals with a call to
// insert_transformed_copy_into(). Compared to Vertex_Buffer we also gain the ability via flat-shading to compute normals from
// scratch for a shape that has none, and the ability to eliminate inter-triangle sharing of vertices for any data we want to
// abruptly vary as we cross over a triangle edge (such as texture images).
//
// Like in class Vertex_Buffer we have an array "indices" to fill in as well, a list of index triples defining which three
// vertices belong to each triangle. Call new on a Shape and fill its arrays (probably in an overridden constructor). Then,
// submit it to Scene_Component's submit_shapes() and the GPU buffers will receive all the per-vertex data and the triangles
// list needed to draw the shape correctly.
//
// IMPORTANT: To use this class you must define all fields for every single vertex by filling in the arrays of each field, so
// this includes positions, normals, any more fields a specific Shape subclass decides to include per vertex, such as texture
// coordinates. Be warned that leaving any empty elements in the lists will result in an out of bounds GPU warning (and nothing
// drawn) whenever the "indices" list contains references to that position in the lists.
class Shape extends Vertex_Buffer {
// For building compound shapes.
static insert_transformed_copy_into(recipient, args, points_transform = Mat4.identity()) {
const temp_shape = new this(...args);
// If you try to bypass making a temporary shape and instead directly insert new data into
// the recipient, you'll run into trouble when the recursion tree stops at different depths.
recipient.indices.push(...temp_shape.indices.map(i => i + recipient.positions.length));
// Copy each array from temp_shape into the recipient shape.
for (let a of temp_shape.array_names) {
if (a == "positions") // Apply points_transform to all points added during this call:
recipient[a].push(...temp_shape[a].map(p => points_transform.times(p.to4(1)).to3()));
else if (a == "normals") // Do the same for normals, but use the inverse transpose matrix as math requires:
recipient[a].push(...temp_shape[a].map(n => Mat4.inverse(points_transform.transposed()).times(n.to4(1)).to3()));
else recipient[a].push(...temp_shape[a]); // All other arrays get copied in unmodified.
}
}
// Auto-generate a new class that re-uses any Shape's points,
// but with new normals generated from flat shading.
make_flat_shaded_version() {
return class extends this.constructor {
constructor(...args) {
super(...args);
this.duplicate_the_shared_vertices();
this.flat_shade();
}
duplicate_the_shared_vertices() {
// Prepare an indexed shape for flat shading if it is not ready -- that is, if there are any edges where
// the same vertices are indexed by both the adjacent triangles, and those two triangles are not co-planar.
// The two would therefore fight over assigning different normal vectors to the shared vertices.
const temp_positions = [],
temp_tex_coords = [],
temp_indices = [];
for (let [i, it] of this.indices.entries()) {
temp_positions.push(this.positions[it]);
temp_tex_coords.push(this.texture_coords[it]);
temp_indices.push(i);
}
this.positions = temp_positions;
this.indices = temp_indices;
this.texture_coords = temp_tex_coords;
}
// Automatically assign the correct normals to each triangular element to achieve flat shading.
// Affect all recently added triangles (those past "offset" in the list). Assumes that no
// vertices are shared across seams. First, iterate through the index or position triples:
flat_shade() {
this.indexed = false;
for (let counter = 0; counter < (this.indexed ? this.indices.length : this.positions.length); counter += 3) {
const indices = this.indexed ?
[this.indices[counter], this.indices[counter + 1], this.indices[counter + 2]] :
[counter, counter + 1, counter + 2];
const [p1, p2, p3] = indices.map(i => this.positions[i]);
// Cross the two edge vectors of this triangle together to get its normal.
const n1 = p1.minus(p2).cross(p3.minus(p1)).normalized();
// Flip the normal if adding it to the triangle brings it closer to the origin.
if (n1.times(.1).plus(p1).norm() < p1.norm()) n1.scale(-1);
// Propagate this normal to the 3 vertices.
for (let i of indices)
this.normals[i] = Vec.from(n1);
}
}
}
}
normalize_positions(keep_aspect_ratios = true) {
const average_position = this.positions.reduce((acc, p) =>
acc.plus(p.times(1 / this.positions.length)), Vec.of(0, 0, 0));
// Center the point cloud on the origin.
this.positions = this.positions.map(p => p.minus(average_position));
const average_lengths = this.positions.reduce((acc, p) =>
acc.plus(p.map(x => Math.abs(x)).times(1 / this.positions.length)), Vec.of(0, 0, 0));
// Divide each axis by its average distance from the origin.
if (keep_aspect_ratios)
this.positions = this.positions.map(p => p.map((x, i) => x / average_lengths[i]));
else
this.positions = this.positions.map(p => p.times(1 / average_lengths.norm()));
}
}
// Stores things that affect multiple shapes, such as lights and the camera.
class Graphics_State {
constructor(camera_transform = Mat4.identity(), projection_transform = Mat4.identity()) {
Object.assign(this, {
camera_transform, projection_transform, animation_time: 0, animation_delta_time: 0, lights: []
});
}
}
// The properties of one light in the scene (Two 4x1 Vecs and a scalar)
class Light {
constructor(position, color, size) {
Object.assign(this, {
position, color, attenuation: 1 / size
});
}
};
// Just an alias. Colors are special 4x1 vectors expressed as ( red, green, blue, opacity ) each from 0 to 1.
class Color extends Vec {}
// For organizing communication with the GPU for Shaders. Now that we've compiled the Shader, we can query
// some things about the compiled program, such as the memory addresses it will use for uniform variables,
// and the types and indices of its per-vertex attributes. We'll need those for building vertex buffers.
class Graphics_Addresses {
constructor(program, gl) {
const num_uniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
for (let i = 0; i < num_uniforms; ++i) {
// Retrieve the GPU addresses of each uniform variable in the shader
// based on their names, and store these pointers for later.
let u = gl.getActiveUniform(program, i).name.split('[')[0];
this[u + "_loc"] = gl.getUniformLocation(program, u);
}
this.shader_attributes = {};
// Assume per-vertex attributes will each be a set of 1 to 4 floats:
const type_to_size_mapping = {
0x1406: 1,
0x8B50: 2,
0x8B51: 3,
0x8B52: 4
};
const numAttribs = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
// https://github.com/greggman/twgl.js/blob/master/dist/twgl-full.js for another example.
for (let i = 0; i < numAttribs; i++) {
const attribInfo = gl.getActiveAttrib(program, i);
// Pointers to all shader attribute variables
this.shader_attributes[attribInfo.name] = {
index: gl.getAttribLocation(program, attribInfo.name),
size: type_to_size_mapping[attribInfo.type],
enabled: true,
type: gl.FLOAT,
normalized: false,
stride: 0,
pointer: 0
};
}
}
}
// Your subclasses of Shader will manage strings of GLSL code that will be sent to the GPU and will run to
// draw every shape. Extend the class and fill in the abstract functions to make the constructor work.
class Shader {
constructor(gl) {
Object.assign(this, {
gl, program: gl.createProgram()
});
const shared = this.shared_glsl_code() || "";
const vertShdr = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShdr, shared + this.vertex_glsl_code());
gl.compileShader(vertShdr);
if (!gl.getShaderParameter(vertShdr, gl.COMPILE_STATUS))
throw "Vertex shader compile error: " + gl.getShaderInfoLog(vertShdr);
const fragShdr = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShdr, shared + this.fragment_glsl_code());
gl.compileShader(fragShdr);
if (!gl.getShaderParameter(fragShdr, gl.COMPILE_STATUS))
throw "Fragment shader compile error: " + gl.getShaderInfoLog(fragShdr);
gl.attachShader(this.program, vertShdr);
gl.attachShader(this.program, fragShdr);
gl.linkProgram(this.program);
if (!gl.getProgramParameter(this.program, gl.LINK_STATUS))
throw "Shader linker error: " + gl.getProgramInfoLog(this.program);
this.g_addrs = new Graphics_Addresses(this.program, this.gl);
}
activate() {
this.gl.useProgram(this.program);
}
// Subclasses have to override the following five functions:
material() {}
update_GPU() {}
shared_glsl_code() {}
vertex_glsl_code() {}
fragment_glsl_code() {}
}
// Texture wraps a pointer to a new texture buffer along with a new HTML image object.
class Texture {
constructor(gl, filename, bool_mipMap, bool_will_copy_to_GPU = true) {
Object.assign(this, {
filename, bool_mipMap, bool_will_copy_to_GPU, id: gl.createTexture()
});
this.image = new Image();
gl.bindTexture(gl.TEXTURE_2D, this.id);
// A single red pixel, as a placeholder image to prevent a console warning.
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 0, 0, 255]));
// Instructions for whenever the real image file is ready
this.image.onload = () => {
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, bool_will_copy_to_GPU);
gl.bindTexture(gl.TEXTURE_2D, this.id);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.image);
// Always use bi-linear sampling when the image will appear magnified. When it will appear shrunk,
// it's best to use tri-linear sampling of its mip maps:
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
if (bool_mipMap) {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.generateMipmap(gl.TEXTURE_2D);
}
// We can also use the worst sampling method, to illustrate the difference that mip-mapping makes.
else
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
this.loaded = true;
};
// Avoid a browser warning, and load the image file.
if (bool_will_copy_to_GPU) {
this.image.crossOrigin = "Anonymous";
this.image.src = this.filename;
}
}
}
// This class manages a whole graphics program for one on-page canvas, including its textures, shapes, shaders,
// and scenes. In addition to requesting a WebGL context and storing the aforementioned items, it informs the
// canvas of which functions to call during events - such as a key getting pressed or it being time to redraw.
class Canvas_Manager {
constructor(canvas, background_color, dimensions) {
let gl, demos = [];
Object.assign(this, {
instances: new Map(),
shapes_in_use: {},
scene_components: [],
prev_time: 0,
canvas,
globals: {
animate: true,
graphics_state: new Graphics_State(),
gl: this.gl
}
});
// Get the GPU ready, creating a new WebGL context for this canvas.
for (let name of["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"])
if (gl = this.gl = this.canvas.getContext(name))
break;
if (!gl)
throw "Canvas failed to make a WebGL context.";
this.set_size(dimensions);
// Tell the GPU which color to clear the canvas with each frame.
gl.clearColor.apply(gl, background_color);
// Enable Z-Buffering test with blending.
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
// Specify an interpolation method for blending "transparent" triangles over the existing pixels.
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());
// A single red pixel, as a placeholder image to prevent a console warning:
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 0, 0, 255]));
this.globals.gl = gl;
// Find the correct browser's version of requestAnimationFrame()
// needed for queue-ing up re-display events:
window.requestAnimFrame = (w =>
w.requestAnimationFrame
|| w.webkitRequestAnimationFrame
|| w.mozRequestAnimationFrame
|| w.oRequestAnimationFrame
|| w.msRequestAnimationFrame
|| function(callback, element) {
w.setTimeout(callback, 1000 / 60);
})(window);
}
// Change the CSS, wait for style to re-flow, then change the canvas attributes.
set_size(dimensions = [1080, 600]) {
const [width, height] = dimensions;
this.canvas.style["width"] = width + "px";
this.canvas.style["height"] = height + "px";
// Have to assign to both; these attributes on a canvas have a special
// effect on buffers, separate from their style.
Object.assign(this, {
width, height
});
Object.assign(this.canvas, {
width, height
});
// Build the canvas's matrix for converting -1 to 1 ranged coords (NCDS)
// into its own pixel coords.
this.gl.viewport(0, 0, width, height);
}
// If a scene requests that the Canvas keeps a certain resource (a Shader
// or Texture) loaded, check if we already have one GPU-side first.
get_instance(shader_or_texture) {
// Return the one that already is loaded if it exists.
if (this.instances[shader_or_texture])
return this.instances[shader_or_texture];
// If a texture was requested, load it onto a GPU buffer.
if (typeof shader_or_texture == "string")
return this.instances[shader_or_texture] = new Texture(this.gl, shader_or_texture, true);
// Or if it's a shader: Compile it and put it on the GPU.
return this.instances[shader_or_texture] = new(shader_or_texture)(this.gl);
}
// Allow a Scene_Component to show their control panel and enter the event loop.
register_scene_component(component) {