-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdrawn-objects.js
More file actions
1208 lines (1058 loc) · 40.2 KB
/
Copy pathdrawn-objects.js
File metadata and controls
1208 lines (1058 loc) · 40.2 KB
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
import { BALL_SIZE, BALL_SUSTAIN_SCALE_FACTOR, CAMPOS, CAM_ROT_ACCEL, CAM_ROT_SPEED, CAM_SPEED, CAM_SPEED_HAPPENINGNESS, CHORD_TONE_TEMPERED, DEBUG_DRAWING, DIST_CHANGE_SPEED, DIST_STD_DEV_CONST, DIST_STD_DEV_RATIO, DRAW_BALL_SIZE, DRAW_COORDS, EDO, FIFTHS_COLOR, FIXED_CAM, HARMONIC_CENTER_SPEED, HARMONIC_CENTER_SPEED_HAPPENINGNESS, HARMONIC_CENTROID_SIZE, JITTER_HAPPENINGNESS, JI_COLORS, MAX_LINE_THICKNESS, MAX_BALLS, MAX_CAM_DIST, MAX_CAM_ROT_SPEED, MAX_FIFTH_HUE, MIN_CAM_DIST, MIN_FIFTH_HUE, NON_CHORD_TONE_SAT_EFFECT, OCTAVES_COLOR, ORIGIN_SIZE, SCULPTURE_CAM_DIST, SCULPTURE_CAM_PHI_CYCLES, SCULPTURE_CAM_THETA_CYCLES, SCULPTURE_CYCLE_DURATION, SCULPTURE_MODE, SEPTIMAL_COLOR, SHOW_DEBUG_BALLS, TEXT_SIZE, TEXT_TYPE, THIRDS_COLOR, UNDECIMAL_COLOR, MIN_LINE_THICKNESS, NON_CHORD_TONE_SIZE_EFFECT } from "./configs.js";
import { HarmonicContext } from "./harmonic-context.js";
import { EDOSTEPS_TO_FIFTHS_MAP, HarmonicCoordinates } from "./just-intonation.js";
import * as THREE from "three/webgpu";
import { mod } from "./helpers.js";
import { WebGPUText as Text } from "troika-three-text/webgpu";
import { MeshBasicMaterial } from "three/webgpu";
/**
* Adds jitter to a vector based on {@linkcode HAPPENINGNESS}
*
* @param {THREE.Vector3} vec Input vector.
* @returns {THREE.Vector3} A new vector with jitter applied.
*/
function addJitter(vec) {
return vec.clone()
.add(new THREE.Vector3().random().multiplyScalar(Math.pow(HAPPENINGNESS, 2.3) * JITTER_HAPPENINGNESS));
}
/**
* Wrapper around THREE's camera.
*
* In 3D, camera always points at centerX/Y/Z and is located in terms of
* spherical coordinates (radius, theta, phi) about the center point.
*/
export class Camera {
/**
* Three JS camera instance
*
* @type {THREE.Camera}
*/
camera;
/**
* The target 3D coords of the centroid of the harmonic context.
*
* The camera will smoothly move to point towards this point.
*
* Note: the +ve Z coordinate points outwards from the screen.
*
* @type {THREE.Vector3}
*/
targetCenter = new THREE.Vector3();
/**
* The current smoothed 3D coords of the centroid of the harmonic context.
*
* The camera will point towards this point.
*
* Note: the +ve Z coordinate points outwards from the screen.
*
* @type {THREE.Vector3}
*/
center = new THREE.Vector3();
/**
* @type {number}
*
* The rotation of the camera about the center point along the X-Z plane. (circling the Y axis)
* For 3D.
*
* 0: right of center
* PI/2: in front of center
* PI: left of center
* 3PI/2: behind center
*
* x = radius * sin(phi) * cos(theta)
* z = radius * sin(phi) * sin(theta)
*/
theta = 1 / 2 * Math.PI; // start 'in front' of the center point
/**
* Stores current yaw rotation speed
*
* @type {number}
*/
dTheta = 0;
/**
* @type {number}
*
* The Y rotation of the camera about the center point after applying theta rotation.
* For 3D.
*
* 0: directly above center
* PI/2: center
* PI: directly below center
*
* y = radius * cos(phi)
*/
phi = Math.PI * 0.65; // start under center point
/**
* @type {HarmonicContext}
*/
#harmonicContext;
// These zoom settings are for 3D
dist = MIN_CAM_DIST;
distTarget = MIN_CAM_DIST;
/**
* @type {THREE.PointLight}
*/
pointLight;
constructor(harmonicContext) {
this.#harmonicContext = harmonicContext;
this.camera = new THREE.PerspectiveCamera(
SCULPTURE_MODE ? 75 : 50,
window.innerWidth / window.innerHeight,
1,
SCULPTURE_MODE ? 10000 : 1000);
this.pointLight = new THREE.PointLight(0xffffff, 0, 0, 1.4);
scene.add(this.pointLight);
}
/**
* To be called when the window is resized
*/
updateAspectRatio() {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
}
/**
* Update the camera's position.
*
* @param {number} stdDeviation The stdDeviation of the {@linkcode BallsManager}
*/
tick(stdDeviation) {
let dt = deltaTime > 1000 ? 1000 : deltaTime;
if (!SCULPTURE_MODE) {
if (!FIXED_CAM) {
[this.targetCenter.x, this.targetCenter.y, this.targetCenter.z] = this.#harmonicContext.tonalCenterUnscaledCoords;
this.center.x += (this.targetCenter.x - this.center.x) * dt / 1000 * (1 + HAPPENINGNESS * CAM_SPEED_HAPPENINGNESS) * CAM_SPEED;
this.center.y += (this.targetCenter.y - this.center.y) * dt / 1000 * (1 + HAPPENINGNESS * CAM_SPEED_HAPPENINGNESS) * CAM_SPEED;
this.center.z += (this.targetCenter.z - this.center.z) * dt / 1000 * (1 + HAPPENINGNESS * CAM_SPEED_HAPPENINGNESS) * CAM_SPEED;
this.distTarget = MIN_CAM_DIST + Math.exp(stdDeviation * DIST_STD_DEV_RATIO + DIST_STD_DEV_CONST) + HAPPENINGNESS * CAM_SPEED_HAPPENINGNESS;
this.distTarget = Math.max(MIN_CAM_DIST, Math.min(MAX_CAM_DIST, this.distTarget));
this.dist += (this.distTarget - this.dist) * dt / 1000 * DIST_CHANGE_SPEED;
} else {
this.center.x = CAMPOS.x;
this.center.y = CAMPOS.y;
this.center.z = CAMPOS.z;
this.phi = CAMPOS.phi;
this.theta = CAMPOS.theta;
this.dist = CAMPOS.dist;
}
}
// Calculate where the camera actually is positioned.
let camX = this.center.x + this.dist * Math.sin(this.phi) * Math.cos(this.theta);
let camY = this.center.y + this.dist * Math.cos(this.phi);
let camZ = this.center.z + this.dist * Math.sin(this.phi) * Math.sin(this.theta);
let camPosVec = new THREE.Vector3(camX, camY, camZ);
this.camera.position.copy(camPosVec);
this.camera.lookAt(this.center);
if (!FIXED_CAM) {
if (!SCULPTURE_MODE) {
// Calculate how to rotate depending on whether the target is left or right of
// the current center point. (If left, rotate CCW, if right, rotate CW)
let camToCenter = new THREE.Vector3().subVectors(this.center, camPosVec);
let targetToCenter = new THREE.Vector3().subVectors(this.center, this.targetCenter);
let cross = camToCenter.cross(targetToCenter);
let crossDivNormalized = cross.dot(cross.clone().normalize()) * cross.y >= 0 ? 1 : -1;
// Rotation speed in radians per second
let targetRotSpd = HAPPENINGNESS * crossDivNormalized * CAM_ROT_SPEED;
targetRotSpd = Math.min(MAX_CAM_ROT_SPEED, Math.abs(targetRotSpd)) * Math.sign(targetRotSpd);
this.dTheta = CAM_ROT_ACCEL * targetRotSpd + (1 - CAM_ROT_ACCEL) * this.dTheta;
this.theta += dt / 1000 * this.dTheta;
if (this.theta > 2 * Math.PI) this.theta -= 2 * Math.PI;
this.phi = 0.97 * this.phi + 0.03 * Math.PI * (0.65 - Math.pow(HAPPENINGNESS, 0.7) * 0.25);
this.pointLight.position.set(camX, camY + 50, camZ);
this.pointLight.intensity = 30 + 90 * (HAPPENINGNESS);
} else {
// In sculpture mode, the camera rotates theta once per N animation cycles.
let currTime = Date.now();
this.theta = (currTime / (1000 * SCULPTURE_CYCLE_DURATION * SCULPTURE_CAM_THETA_CYCLES) % 1) * 2 * Math.PI;
this.phi = Math.PI * (0.5 + Math.sin(currTime / (1000 * SCULPTURE_CYCLE_DURATION * SCULPTURE_CAM_PHI_CYCLES) % 1 * 2 * Math.PI) * 0.1);
this.dist = SCULPTURE_CAM_DIST + 50 * Math.sin(currTime / (1000 * SCULPTURE_CYCLE_DURATION * SCULPTURE_CAM_THETA_CYCLES) % 1 * 2 * Math.PI);
this.pointLight.position.set(camX, camY, camZ);
this.pointLight.intensity = 130;
}
}
}
}
/** Helper for underlining text using UTF */
function underline(text) {
const UNDERLINE_CHAR = '\u0332';
return text.split('').map(char => char + UNDERLINE_CHAR).join('');
// return text;
}
/**
* Contains a lookup of {@linkcode THREE.Mesh} object UUIDs to {@linkcode Ball} objects.
*
* If the UUID is for the {@linkcode THREE.InstancedMesh} of balls, the value will instead be an
* array of {@linkcode Ball}s (specifically, the one in
* {@linkcode BallsManager}`.#listOfPermaDeadBalls`), indexed by the `instanceId`. For the
* `InstancedMesh`, `instanceId` is an attribute of the returned object in of the raycaster's
* intersect methods.
*
* @type {Object.<string, Ball | [Ball]>}
*/
const MESH_UUID_BALL_DICT = {};
window.MESH_UUID_BALL_DICT = MESH_UUID_BALL_DICT;
export class Ball {
/**
* Absolute harmonic coordinates
*
* @type {HarmonicCoordinates}
*/
harmCoords;
/**
* Harmonic coordinates relative to {@linkcode HarmonicContext.effectiveOrigin}
*
* @type {HarmonicCoordinates}
*/
relativeHarmCoords;
#presence; // Number from 0-1
stepsFromA;
/**
* Position of the center of the ball
*
* @type {THREE.Vector3}
*/
pos = new THREE.Vector3();
hue;
saturation;
/**
* @type {THREE.Color}
*/
ballColor;
size;
isChordTone = true;
isRoot = false;
isDebug = false; // set this manually to true if the ball is debug and has no relativeHarmCoords./
/**
* If true, the ball will stay on the screen indefinitely.
* @type {boolean}
*/
isPermanent = false;
/**
* If true, this is a dead permanent ball.
*/
isPermaDead = false;
/**
* The sphere geometry
*
* @type {THREE.SphereGeometry}
*/
#geometry;
/**
* The material for the sphere
*
* @type {THREE.MeshStandardMaterial}
*/
#material;
/**
* The mesh representing the ball object
*
* @type {THREE.Mesh}
*/
#sphereMesh;
/**
* The text below the ball.
*
* @type {Text}
*/
#text;
/**
* Which type of text to display on the ball.
*
* If `TEXT_TYPE` is 'namefraction', this should initially be set to 'name', then 'relfraction'
* after a set amount of time.
*
* @type {'none' | 'relfraction' | 'relmonzo' | 'name'}
*/
#textType = TEXT_TYPE;
/**
* The time at which the ball was constructed or revived.
* @type {Date}
*/
#noteOnTime;
/**
* Common setup between constructor and {@linkcode revive} functions.
*
* @param {HarmonicCoordinates} harmCoords
* @param {number} stepsFromA
* @param {number} presence
* @param {boolean} isDebug
*/
setup(harmCoords, stepsFromA, presence, isDebug, isPermanent) {
this.isDebug = isDebug;
this.isPermanent = isPermanent;
this.harmCoords = harmCoords;
this.#presence = presence;
this.stepsFromA = stepsFromA;
[this.pos.x, this.pos.y, this.pos.z] = this.harmCoords.toUnscaledCoords();
let edosteps = mod(stepsFromA, EDO);
let octaves = Math.floor(stepsFromA / EDO) + 4;
this.hue = MIN_FIFTH_HUE + (MAX_FIFTH_HUE - MIN_FIFTH_HUE) * EDOSTEPS_TO_FIFTHS_MAP[edosteps] / EDO;
this.saturation = .95 - .25 * (octaves - 2) / 5 // Let saturation start to fall at octave 2
this.size = Math.pow(presence, 0.5);
this.#noteOnTime = new Date();
if (TEXT_TYPE === 'namefraction') {
this.#textType = 'name';
}
}
constructor(harmCoords, stepsFromA, presence, isDebug = false, isPermanent = false) {
this.setup(harmCoords, stepsFromA, presence, isDebug, isPermanent);
this.ballColor = new THREE.Color();
this.ballColor.setHSL(this.hue, this.saturation, this.lightness);
this.#geometry = new THREE.SphereGeometry(BALL_SIZE, 24, 24);
this.#material = new THREE.MeshStandardMaterial({
color: this.ballColor,
metalness: 0,
roughness: 0.3,
opacity: this.isDebug ? 0.4 : this.opacity,
transparent: true,
side: THREE.DoubleSide,
});
this.#sphereMesh = new THREE.Mesh(this.#geometry, this.#material);
MESH_UUID_BALL_DICT[this.#sphereMesh.uuid] = this;
this.updateDrawing();
window.scene.add(this.#sphereMesh);
if (!this.isDebug) {
if (this.#textType !== 'none') {
this.#text = new Text();
this.#text.font = "FiraSansExtralight-AyaD.ttf";
this.#text.position.set(0, this.#textType === 'relfraction' ? -25 : -25, 0);
this.#text.fontSize = this.size * TEXT_SIZE;
this.#text.anchorX = 'center';
this.#text.anchorY = 'middle';
this.#text.textAlign = 'center';
this.#text.gpuAccelerateSDF = true;
this.#text.sdfGlyphSize = 64;
this.#text.lineHeight = 0.9;
this.#text.maxWidth = 100;
this.#sphereMesh.add(this.#text);
}
} else {
this.#sphereMesh.renderOrder = -100;
}
}
/**
* Reactivate a dead ball and put in into the scene.
*
* @param {HarmonicCoordinates} harmCoords
* @param {number} stepsFromA
* @param {number} presence
* @returns {Ball} this instance
*/
revive(harmCoords, stepsFromA, presence, isPermanent) {
if (this.isPermaDead) {
throw new Error('Cannot revive a permanently dead ball.');
}
this.setup(harmCoords, stepsFromA, presence, false, isPermanent);
this.ballColor.setHSL(this.hue, this.saturation, .36 + .29 * Math.pow(presence, 0.5));
this.#material.opacity = this.isDebug ? 0.3 : this.opacity;
this.updateDrawing();
window.scene.add(this.#sphereMesh);
return this;
}
get isDead() {
return this.presence <= 0;
}
get presence() {
return this.#presence;
}
get lightness() {
return 0.29 + 0.26 * Math.pow(this.presence, 0.5);
}
get opacity() {
return 0.3 + 0.5 * Math.pow(this.presence, 0.45);
}
/**
* Call this whenever ball is to be set inactive.
*
* Removes ball from scene and stops it from updating.
*
* If this ball is a permanent ball, the Ball class will be marked as permanently dead, and
* cannot be {@linkcode revive}d. The geometry and material objects will be disposed.
*
* However, a permanently dead {@linkcode Ball} class should still be saved in memory as it will
* stay on screen, but it should be transformed into an instance in an InstancedMesh.
*/
kill() {
if (this.isPermaDead) return;
this.#presence = 0;
if (this.isPermanent) {
// A permanent ball will be converted to an instance in an InstancedMesh.
// Delete & free resources.
window.scene.remove(this.#sphereMesh);
this.#geometry.dispose();
this.#material.dispose();
this.isPermaDead = true;
} else {
window.scene.remove(this.#sphereMesh);
}
}
/**
* Call this when a ball that is already in the scene/active is restruck again.
*/
revitalize(presence) {
this.#presence = presence;
this.#noteOnTime = new Date();
if (TEXT_TYPE === 'namefraction') {
this.#textType = 'name';
// reset back to 'name' text display.
this.#text.position.set(0, -25, 0);
console.log(`notename: ${harmonicContext.getNoteName(this.harmCoords)}`);
}
}
updateDrawing() {
this.#sphereMesh.scale.set(this.size, this.size, this.size);
this.#sphereMesh.position.copy(addJitter(this.pos));
this.#material.color.set(this.ballColor);
}
/**
*
* @param {KEYS_STATE} keyState
* @param {HarmonicContext} harmonicContext
*/
tick(keyState, harmonicContext) {
if (this.isDead) return;
this.isChordTone = CHORD_TONE_TEMPERED ?
harmonicContext.containsNote(this.stepsFromA)
: harmonicContext.containsHarmCoords(this.harmCoords);
this.isRoot = harmonicContext.effectiveOrigin.equals(this.harmCoords);
if (this.stepsFromA in keyState) {
if (this.presence > BALL_SUSTAIN_SCALE_FACTOR)
this.#presence = this.presence * (1 - (2 - HAPPENINGNESS) * deltaTime / 1000);
else if (this.presence < BALL_SUSTAIN_SCALE_FACTOR)
this.#presence = BALL_SUSTAIN_SCALE_FACTOR;
} else {
this.#presence = this.presence * (1 - 2 * deltaTime / 1000) - 0.01 * deltaTime / 1000;
}
if (this.isDead) {
this.kill();
return;
}
let nonChordToneMult = this.isChordTone ? 1 : NON_CHORD_TONE_SAT_EFFECT;
let nonChordToneSizeMult = this.isChordTone ? 1 : NON_CHORD_TONE_SIZE_EFFECT;
let rootMult = this.isRoot ? 1.3 : 0.8;
this.ballColor.setHSL(
this.hue,
this.saturation * nonChordToneMult * rootMult,
this.lightness * rootMult,
);
this.#material.opacity = this.opacity;
this.#material.roughness = 0.3 + 0.3 * HAPPENINGNESS;
this.size = Math.pow(this.presence, 0.5) * rootMult * nonChordToneSizeMult;
[this.pos.x, this.pos.y, this.pos.z] = this.harmCoords.toUnscaledCoords();
this.updateDrawing();
this.relativeHarmCoords = harmonicContext.relativeToEffectiveOrigin(this.harmCoords);
let textColor = this.ballColor.clone().offsetHSL(0, 0, 0.2);
if (this.#text) {
if (this.#textType === 'name' && TEXT_TYPE === 'namefraction' && new Date() - this.#noteOnTime > 800) {
// after 0.8s, switch note name to fraction.
this.#textType = 'relfraction';
// this.#text.position.set(0, -25, 0);
}
if (this.#textType === 'relfraction') {
let [num, den] = this.relativeHarmCoords.toRatio();
this.#text.text = underline(`${num}`) + `\n${den}`;
} else if (this.#textType === 'relmonzo') {
this.#text.text = this.relativeHarmCoords.toMonzoString();
} else if (this.#textType === 'name') {
this.#text.text = harmonicContext.getNoteName(this.harmCoords);
}
this.#text.color = textColor;
this.#text.opacity = this.opacity * 0.5 + 0.5;
this.#text.lookAt(window.cam.camera.position);
}
}
}
export class BallsManager {
/**
* Represents active balls indexed by their harmonic coordinates
*
* @type {Object.<HarmonicCoordinates, Ball>}
*/
balls = {};
/**
* Ball for showing where the origin is.
*
* @type {Ball}
*/
originBall;
/**
* Ball for showing where the harmonic center is.
*
* @type {Ball}
*/
harmonicCenterBall;
/**
* An instanced mesh for all permanent dead balls & debug drawing balls.
*
* @type {THREE.InstancedMesh}
*/
#permaDeadMesh;
/**
* Material for instanced mesh.
*
* @type {THREE.MeshStandardMaterial}
*/
#permaDeadMaterial;
/**
* Geometry for instanced mesh.
*
* @type {THREE.SphereGeometry}
*/
#permaDeadGeometry;
/**
* Contains list of inactive ball objects
*
* @type {[Ball]}
*/
#listOfDeadBalls = [];
/**
* Contains list of balls that are permanent but dead.
*
* The global {@linkcode MESH_UUID_BALL_DICT} of the UUID of the `#permaDeadMesh` will point to
* this list, don't update both of them.
*
* @type {[Ball]}
*/
#listOfPermaDeadBalls = [];
/**
* The mean of the standard deviation of the x, y (and z, if 3D) coordinates of the balls.
*/
#stddev = 0;
constructor() {
this.originBall = new Ball(new HarmonicCoordinates([0]), 0, ORIGIN_SIZE, true);
this.originBall.ballColor = new THREE.Color(0xEEEEEE);
this.originBall.updateDrawing();
this.harmonicCenterBall = new Ball(new HarmonicCoordinates([0]), 0, HARMONIC_CENTROID_SIZE, true);
this.#permaDeadGeometry = new THREE.SphereGeometry(BALL_SIZE * DRAW_BALL_SIZE, 24, 24);
this.#permaDeadMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
metalness: 0,
roughness: 0.45,
opacity: 0.5,
transparent: true,
side: THREE.DoubleSide,
});
this.#permaDeadMesh = new THREE.InstancedMesh(this.#permaDeadGeometry, this.#permaDeadMaterial, DRAW_COORDS.length + 50);
this.#permaDeadMesh.count = 0; // we update the count as we add more balls. All instances up to `count` will be drawn.
this.#permaDeadMesh.position.set(0, 0, 0);
window.scene.add(this.#permaDeadMesh);
MESH_UUID_BALL_DICT[this.#permaDeadMesh.uuid] = this.#listOfPermaDeadBalls;
if (DEBUG_DRAWING) {
let positionMatrix = new THREE.Matrix4(); // transform matrix.
let color = new THREE.Color();
// We add the drawing to the list of perma dead balls as already perma dead.
for (let harmCoord of DRAW_COORDS) {
let ball = new Ball(new HarmonicCoordinates(harmCoord), 0, 0.6, false, true);
ball.kill();
this.#listOfPermaDeadBalls.push(ball);
positionMatrix.setPosition(ball.pos);
this.#permaDeadMesh.setMatrixAt(this.#permaDeadMesh.count, positionMatrix);
color.setHSL(this.#permaDeadMesh.count / DRAW_COORDS.length, 0.91, 0.13);
this.#permaDeadMesh.setColorAt(this.#permaDeadMesh.count, color);
this.#permaDeadMesh.count++;
}
}
}
/**
*
* @param {HarmonicCoordinates} harmCoords
* @param {number} stepsFromA
* @param {number} velocity
* @param {bool} isPermanent Set to `true` if the ball should stay on the screen indefinitely.
* @returns {Ball} The ball that was created/reused
*/
noteOn(harmCoords, stepsFromA, velocity, isPermanent = false) {
// console.log('ball note on: ', harmCoords.toMonzoString(), stepsFromA, harmCoords);
let presence = Math.pow(velocity / 127, 1) * 0.9 + 0.1;
/** @type {Ball} */
let existingBall = this.balls[harmCoords];
if (existingBall !== undefined) {
existingBall.revitalize(presence);
return existingBall;
} else {
let keys = Object.keys(this.balls);
if (this.#listOfDeadBalls.length > 0 || keys.length >= MAX_BALLS) {
// Reuse a dead ball whenever possible/necessary
/** @type {Ball} */
let oldBall = this.#listOfDeadBalls.pop();
if (!oldBall) {
// if there aren't any dead balls, but MAX_BALLS are exceeded,
// delete a random ball to re-use.
let randomKey = keys[Math.floor(Math.random() * keys.length)];
this.deleteBall(randomKey);
oldBall = this.#listOfDeadBalls.pop();
}
oldBall.revive(harmCoords, stepsFromA, presence, isPermanent);
// if there was already an existing ball object in the new location for some reason,
// put it into the reserve to prevent memory leaks.
this.deleteBall(harmCoords);
// put the revived old ball in the active list.
this.balls[harmCoords] = oldBall;
return oldBall;
}
// otherwise, just make a new ball.
let ball = new Ball(harmCoords, stepsFromA, presence, false, isPermanent);
// if there was already a ball object in this new location for some reason,
// delete it.
this.deleteBall(harmCoords);
this.balls[harmCoords] = ball;
return ball;
}
}
/**
* Deletes an active ball at given harmonic coordinate.
*
* Doesn't actually delete it, just moves the ball object into the reserve
*
* @param {HarmonicCoordinates} harmCoords
*/
deleteBall(harmCoords) {
if (this.balls[harmCoords]) {
/** @type {Ball} */
let toDelete = this.balls[harmCoords];
toDelete.kill();
if (toDelete.isPermaDead) {
this.#listOfPermaDeadBalls.push(toDelete);
MESH_UUID_BALL_DICT[this.#permaDeadMesh.uuid] = this.#listOfPermaDeadBalls;
let positionMatrix = new THREE.Matrix4();
positionMatrix.setPosition(toDelete.pos);
this.#permaDeadMesh.setMatrixAt(this.#permaDeadMesh.count, positionMatrix);
let color = new THREE.Color();
color.setHSL(this.#permaDeadMesh.count / DRAW_COORDS.length, 0.91, 0.13);
this.#permaDeadMesh.setColorAt(this.#permaDeadMesh.count, color);
this.#permaDeadMesh.count = this.#listOfPermaDeadBalls.length;
this.#permaDeadMesh.instanceMatrix.needsUpdate = true;
this.#permaDeadMesh.instanceColor.needsUpdate = true;
this.#permaDeadMesh.geometry.computeVertexNormals();
this.#permaDeadMesh.computeBoundingSphere();
} else {
this.#listOfDeadBalls.push(toDelete);
}
delete this.balls[harmCoords];
}
}
/**
*
* @param {Object.<number, KeyState>} keyState
* @param {HarmonicContext} harmonicContext
*/
tick(keyState, harmonicContext) {
let xValues = [], yValues = [], zValues = [];
Object.entries(this.balls).forEach(
([hcKey, b]) => {
/** @type {Ball} */
let ball = b;
ball.tick(keyState, harmonicContext);
if (ball.isDead) {
this.deleteBall(ball.harmCoords);
return;
}
if (ball.harmCoords != hcKey) {
console.warn('ball key mismatch: ', ball.harmCoords, hcKey);
}
xValues.push(ball.pos.x);
yValues.push(ball.pos.y);
zValues.push(ball.pos.z);
}
);
if (xValues.length !== 0) {
this.#stddev = (math.std(xValues) + math.std(yValues) + math.std(zValues)) / 3;
}
else
this.#stddev = 0;
if (SHOW_DEBUG_BALLS) {
[this.harmonicCenterBall.pos.x, this.harmonicCenterBall.pos.y, this.harmonicCenterBall.pos.z] = harmonicContext.tonalCenterUnscaledCoords;
let hue = MIN_FIFTH_HUE + harmonicContext.centralFifth / EDO * (MAX_FIFTH_HUE - MIN_FIFTH_HUE);
this.harmonicCenterBall.ballColor.setHSL(hue, 0.9, 0.6);
this.harmonicCenterBall.updateDrawing();
this.originBall.updateDrawing();
}
}
get stdDeviation() {
return this.#stddev;
}
/**
* Retrieves total amount of ball objects in memory including inactive/dead balls.
*/
get numBallObjects() {
return Object.keys(this.balls).length + this.#listOfDeadBalls.length;
}
/**
* Retrieves current number of balls active.
*/
get numBallsAlive() {
return Object.keys(this.balls).length;
}
/**
* Number of dead permanent balls.
*/
get numPermaDead() {
return this.#listOfPermaDeadBalls.length;
}
}
export class KeyCenterParticleFountain {
/**
* Position of the particle emitter
*
* @type {THREE.Vector3}
*/
pos = new THREE.Vector3();
/**
* A number from {@linkcode MIN_FIFTH_HUE} to {@linkcode MAX_FIFTH_HUE} representing the hue of the fountain.
*/
hue;
/**
* @type {Nebula.System}
*/
system;
/**
* @type {Nebula.Emitter}
*/
emitter;
/**
* @type {Nebula.SpriteRenderer}
*/
particleRenderer;
/**
* @type {THREE.Sprite}
*/
sprite;
/**
* @type {THREE.PointLight}
*/
pointLight;
constructor() {
this.system = new Nebula.System(THREE);
this.emitter = new Nebula.Emitter();
this.particleRenderer = new Nebula.SpriteRenderer(window.scene, THREE);
let spriteMap = new THREE.TextureLoader().load('./dot.png');
let material = new THREE.SpriteMaterial({
map: spriteMap,
color: 0xffffff,
blending: THREE.AdditiveBlending,
fog: true
});
this.sprite = new THREE.Sprite(material);
this.emitter
.setRate(new Nebula.Rate(new Nebula.Span(5, 10), new Nebula.Span(0.01, 0.03)))
.addInitializers([
new Nebula.Body(this.sprite),
new Nebula.Mass(1),
new Nebula.Life(1, 3),
new Nebula.Radius(0, 2),
new Nebula.Position(new Nebula.SphereZone(0, 0, 0, 1)), // x, y, z, radius
])
.addBehaviours([
])
.setPosition({
x: 0, y: 0, z: 0
})
.emit();
this.system
.addEmitter(this.emitter)
.addRenderer(this.particleRenderer)
.emit({});
this.pointLight = new THREE.PointLight(0xffffff, 0, 0, 1);
scene.add(this.pointLight);
}
/**
* @param {HarmonicContext} harmonicContext
* @param {number} dRotator
* @param {Camera} camera
*/
tick(harmonicContext) {
this.hue = MIN_FIFTH_HUE + harmonicContext.centralFifth / EDO * (MAX_FIFTH_HUE - MIN_FIFTH_HUE);
let [targetX, targetY, targetZ] = harmonicContext.tonalCenterUnscaledCoords;
this.pos.x += (targetX - this.pos.x) * deltaTime / 1000 * (1 + HAPPENINGNESS * HARMONIC_CENTER_SPEED_HAPPENINGNESS) * HARMONIC_CENTER_SPEED;
this.pos.y += (targetY - this.pos.y) * deltaTime / 1000 * (1 + HAPPENINGNESS * HARMONIC_CENTER_SPEED_HAPPENINGNESS) * HARMONIC_CENTER_SPEED;
this.pos.z += (targetZ - this.pos.z) * deltaTime / 1000 * (1 + HAPPENINGNESS * HARMONIC_CENTER_SPEED_HAPPENINGNESS) * HARMONIC_CENTER_SPEED;
let color = new THREE.Color().setHSL(this.hue, 0.6 + 0.4 * HAPPENINGNESS, 0.4 + 0.2 * HAPPENINGNESS);
this.emitter.setPosition({
x: this.pos.x,
y: this.pos.y,
z: this.pos.z
}).setBehaviours([
new Nebula.Alpha(0.08 + 0.13 * HAPPENINGNESS, 0 + 0.04 * HAPPENINGNESS, Infinity, Nebula.ease.easeInSine),
new Nebula.RandomDrift(1 + 1 * HAPPENINGNESS, 1 + 1 * HAPPENINGNESS, 1 + 1 * HAPPENINGNESS, 0.1),
new Nebula.Repulsion(this.pos, 0.1 + 0.3 * HAPPENINGNESS * HAPPENINGNESS, BALL_SIZE * 2, Infinity, Nebula.ease.easeInQuad),
new Nebula.Scale(new Nebula.Span(2 + HAPPENINGNESS, 1), 0),
new Nebula.Color(
color,
new THREE.Color().setHSL(this.hue, 0.3 + 0.3 * HAPPENINGNESS, 0.5 + 0.2 * HAPPENINGNESS),
Infinity, Nebula.ease.easeOutSine)
]).setInitializers([
new Nebula.Body(this.sprite),
new Nebula.Mass(1),
new Nebula.Life(1 + 1 * HAPPENINGNESS, 2 + 2 * HAPPENINGNESS),
new Nebula.Radius(0 + HAPPENINGNESS, 1.5 + 1.6 * HAPPENINGNESS),
new Nebula.Position(new Nebula.SphereZone(0, 0, 0, 1 + 13 * HAPPENINGNESS)), // x, y, z, radius
new Nebula.RadialVelocity(5, new Nebula.Vector3D(0, 1, 1), 2)
]);
this.system.update(deltaTime / 1000);
this.pointLight.position.copy(this.pos);
this.pointLight.color.set(color).addScalar(0.3);
this.pointLight.intensity = 200 + 2000 * Math.pow(HAPPENINGNESS, 2.5);
}
get numParticles() {
return this.system.getCount();
}
}
export class Scaffolding {
/**
* Contains the most recent Ball object which requires the existence of this line.
*
* @type {Ball}
*/
reasonForExisting;
/**
* @type {THREE.Vector3}
*/
from = new THREE.Vector3();
/**
* @type {THREE.Vector3}
*/
to = new THREE.Vector3();
/**
* @type {HarmonicCoordinates}
*/
fromHarmCoords;
/**
* @type {HarmonicCoordinates}
*/
toHarmCoords;
thickness = MAX_LINE_THICKNESS;
color;
/**
* A prime number that represents the unit direction that this scaffolding points towards.
*
* Is negative if the direction is negative.
*
* @type {number}
*/
adjacency;
presence;
/**
* Contains the geometry of the cylinder
*
* @type {THREE.CylinderGeometry}
*/
#geometry;
/**
* Contains the line material
*
* @type {THREE.MeshStandardMaterial}
*/
#material;
/**
* Contains cylinder mesh
*
* @type {THREE.Mesh}
*/
#mesh;
/**
* Common setup between scaffolding constructor and {@linkcode revive} methods
*
* @param {HarmonicCoordinates} from
* @param {HarmonicCoordinates} to
* @param {Ball} reasonForExisting
*/
setup(from, to, reasonForExisting) {
this.adjacency = from.checkAdjacent(to);
if (this.adjacency === 0) {
console.log(from, to);
throw new Error('Attempted to construct scaffolding between non-adjacent coordinates');
}
this.reasonForExisting = reasonForExisting;
this.presence = this.reasonForExisting.presence;
this.fromHarmCoords = from;
this.toHarmCoords = to;
[this.from.x, this.from.y, this.from.z] = from.toUnscaledCoords();
[this.to.x, this.to.y, this.to.z] = to.toUnscaledCoords();
this.color = JI_COLORS[Math.abs(this.adjacency)];
// this.color.setAlpha(Math.pow(this.presence, 0.8));
this.thickness = Math.pow(this.presence, 0.9) * (MAX_LINE_THICKNESS + 0.2 * HAPPENINGNESS);
}
/**
*
* @param {HarmonicCoordinates} from
* @param {HarmonicCoordinates} to
* @param {Ball} reasonForExisting
*/