-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
1095 lines (891 loc) · 36.9 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Interactive Graphics - Final Project</title>
<link rel="stylesheet" href="style/style.css">
<meta name="description" content="Interactive Graphics - Final Project - 2019">
<meta name="keywords" content="HTML, CSS, JavaScript, GLSL">
<meta name="author" content="JohnnyMDA">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="img/ig_cube.ico">
<!-- STYLE -->
<link rel="stylesheet" type="text/css" href="style/style.css">
<link rel="stylesheet" type="text/css" href="style/player-style/styles.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Droid+Serif:400,400i,700|PT+Serif:400,400i&subset=latin-ext">
<link rel="stylesheet" href="style/player-style/font-awesome-4.3.0/css/font-awesome.min.css">
<!-- SCRIPTS -->
<script type="text/javascript" src="Common/three.min.js"> </script> <!-- JavaScript 3D library with a WebGL render -->
<script type="text/javascript" src="Common/OrbitControls.js"> </script> <!-- Camera orbit controls library for THREE.JS -->
<script type="text/javascript" src="Common/dat.gui.min.js"> </script> <!-- A GUI library for changing the variables values in JavaScript -->
<script type="text/javascript" src="Common/Stats.js"> </script> <!-- JavaScript Performance Monitor -->
<script src="Common/jquery-3.4.0.min.js"></script>
</head>
<body>
<!-- Player Container -->
<div id="container" class="disabled">
<div id="cover-art">
<div id="animate"></div> <!-- THREE.JS ANIMATION HERE -->
</div>
<div id="wave"></div> <!-- WAVESURFER HERE -->
<div id="control-bar">
<div class="player-control">
<div id="previous-button" title="Previous"> <i class="fa fa-fast-backward"> </i></div>
<div id="play-button" title="Play"> <i class="fa fa-play"> </i></div>
<div id="pause-button" title="Pause"> <i class="fa fa-pause"> </i></div>
<div id="stop-button" title="Stop"> <i class="fa fa-stop"> </i></div>
<div id="next-button" title="Next"> <i class="fa fa-fast-forward"> </i></div>
<div id="shuffle-button" title="Shuffle Off"> <i class="fa fa-random"> </i></div>
<div id="repeat-button" title="Repeat Off"> <i class="fa fa-refresh"><span>1</span></i></div>
</div>
<div id="playlist">
<div id="track-details" title="Show playlist">
<i class="fa fa-sort"></i>
<p id="track-desc">There are no tracks loaded in the player. Drag and Drop some from your PC or wait for loading the default ones.</p>
<p id="track-time">
<span id="current">-</span> / <span id="total">-</span>
</p>
</div>
<div id="expand-bar" class="hidden">
<ul id="list"></ul>
</div>
</div>
</div> <!-- END control-bar -->
<div id="drop-zone" class="hidden">Drag & Drop Audio Files Here</div>
<a id="help-icon" href="help.html" target="_blank">
<img id="help-icon"
src="img/help.png"
style="
position : absolute;
z-index : 1000;
top : 6px;
right : 6px;
height : 40px;
opacity : 0.5;
cursor : pointer;
"
>
</a>
</div>
<!-- Web Audio Player SCRIPTS -->
<script src="Common/id3-minimized.js"> </script>
<script src="Common/wavesurfer.min.js"> </script>
<script src="Common/player_script.js"> </script>
<!-- MAIN visualization SCRIPT -->
<script>
// set variables
var clock = new THREE.Clock(),
stats, // STATS.JS
renderer,
scene,
sceneHeight,
sceneWidth,
display, // Animation DOM element;
camera,
cameraFar,
cameraNear,
cameraAspect,
cameraViewAngle,
gui, // dat.GUI()
controls, // Orbit Controls;
sphere,
radius = 100,
rings = 64,
segments = 8,
alpha_texture_path = 'img/stripes_alpha_texture_3.png',
// Load the alpha texture image
alphaTexture= new THREE.TextureLoader().load(alpha_texture_path),
spiralSphereNorth,
spiralSphereSouth,
radiusSS = 16,
ringsSS = 64,
segmentsSS = 64,
lightNorthIntensity = 130,
lightNorthColor = 0x0101FC,
lightNorth,
lightSouth,
lightSouthColor = 0xFC0101,
lightSouthIntensity = 30,
offsetUpdateSpeed = 0.23, // Regulate the y-offset of the alpha texture at render time (scale the 'tdd' AVG);
numWaves = segments,
waves = [],
sampleRate = 0.04, // spline curve sample rate for wave lines building
wavesCreated = false,
changeWavesColor = false,
cubes,
cubeSize = 8,
cube_L_coef = 1.6,
cube_l_coef = 0.5,
cube_h_coef = 0.85,
numCubes,
particles_systems = [],
no_particle_space = 0.7 * 540,
analyser, // Web Audio API analyser node var;
numChannels,
tdd, // Time Domain Data (array);
fft, // Frequency Domain Data (from Fast Fourier Transform)(array);
peaks, // FFT based array (used for cubes' scaling);
fftSize = 2*segments * 2*rings, // Powers of 2 (default --> 2048) (lower --> faster);
// We use one array's spot for each cube on the sphere;
smoothingTimeConstantFFT = 0.0, // A more immediate response to the played audio;
deltaPeaks = 10.0, // Upperbound threshold for peaks update;
peaksDecreasingParam = 0.96, // Decreasing speed in time (at least one update per frame);
audio_path = "audio/", // Default audio track list to be loaded in the player;
audio_list = ["Aloe Blacc - I Need a Dollar.mp3", "Elvis Presley - Heartbreak Hotel.mp3", "Gun N' Roses - Sweet Child O' Mine.mp3", "Jeff Buckley - Hallelujah.mp3", "Jhon Lennon - Imagine.mp3", "Michael Jackson - Billie Jean.mp3", "Pink Floyd - Another brick in the wall.mp3", "Queen - Under Pressure.mp3", "R.E.M. - Losing My Religion.mp3", "Radiohead - Creep.mp3", "The Animals - The House of the Rising Sun.mp3", "The Eagles - Hotel California.mp3", "The Police - Every Breath You Take.mp3"]; // default songs list to be loaded //
// Initialize the visualization
window.onload=function()
{
init();
}
function init()
{
// Load the default songs in the playlist asynchronously
createDefaultPlaylist( audio_path, audio_list );
// Get the DOM element where to display
display = document.getElementById("animate");
// Set up the scene dimensions
sceneHeight = window.innerHeight;
sceneWidth = window.innerWidth;
// Set the camera properties
cameraFar = 10000;
cameraNear = 0.1;
cameraAspect = sceneWidth / sceneHeight;
cameraViewAngle = 65;
camera = new THREE.PerspectiveCamera(
cameraViewAngle,
cameraAspect,
cameraNear,
cameraFar
);
// Set the camera (initial) position
camera.position.z = no_particle_space; // move backward
// Create the renderer and camera (the WebGL one)s
renderer = new THREE.WebGLRenderer( {
antialias : true, // default false
alpha : false, // default false
depth : true, // default true
powerPreference : 'high-performance',
shadowMapEnable : true,
physicallyCorrectLights : true
} );
// START the (WebGL) renderer
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( sceneWidth, sceneHeight );
// Append the renderer DOM element on 'display'
display.appendChild( renderer.domElement );
// Create the scene
scene = new THREE.Scene();
// add some fog in the scene (black fog)
scene.fog = new THREE.FogExp2( 0x000000 , 0.00075 );
// Add the camera controls
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.target.set( 0, 0, 0 );
controls.enableZoom = true;
controls.maxDistance = no_particle_space; // limit the zoom-out by default (Perspective Camera);
controls.zoomSpeed = 0.55;
controls.autoRotate = false;
controls.enabled = true;
controls.update();
//#########################//
//#### STATS.js ####//
//#########################//
// set up the Stats.js for statistic display
// and add them to the DOM
stats = new Stats();
stats.showPanel( 0 ); // 0: fps, 1: ms, 2: mb, 3+: custom
stats.dom.style.top = '3px';
stats.dom.style.left = '1px';
document.body.appendChild( stats.dom );
//#########################//
//#### EVENT LISTENERS ####//
//#########################//
// Update the scene on window resize dynamically
window.addEventListener("resize", function()
{
// Set up the scene dimensions
sceneHeight = window.innerHeight;
sceneWidth = window.innerWidth;
camera.aspect = sceneWidth / sceneHeight;
camera.updateProjectionMatrix();
renderer.setSize(sceneWidth, sceneHeight);
renderer.render( scene, camera );
console.log("DEBUG: window resized !\n");
});
// Keyboard Controls event listener (on key down)
document.addEventListener("keydown", setupKeyControls);
// computational resources optimization when out of view
// document.addEventListener('visibilitychange', function()
// {
// if (document.hidden)
// {
// // stop rendering && stop audio
// wavesurfer.pause();
// }else{
// // resume rendering && audio
// wavesurfer.play();
// }
// });
// 'audioprocess' event fires continuously as the audio plays.
wavesurfer.on('audioprocess', function(e) {
// update the 'fft' and 'tdd' arrays
analyser.getByteFrequencyData( fft );
analyser.getByteTimeDomainData( tdd );
// update the peaks array
onAudioAvailable(); // console.log("\nDEBUG:\n\nfft \t= " + fft + "\n\npeaks \t= " + peaks + "\n\ntdd \t= " + tdd + "\n\n");
});
// Creates the main sphere //
function createSphere()
{
var sphereFaces,
sphereMaterial,
cubeHalfSize = cubeSize / 2,
spaceRangePS = 1000;
//#########################//
//###### MAIN SPHERE ######//
//#########################//
sphere = new THREE.Mesh(
new THREE.SphereGeometry( radius, segments, rings),
new THREE.MeshNormalMaterial({
wireframe : false,
transparent : true,
flatShading : true,
opacity : 0.001,
fog : false // we have black fog in the scene
})
);
// Add the sphere to the scene
scene.add(sphere);
//###################//
//###### CUBES ######//
//###################//
// Get the faces of the sphere
sphereFaces = sphere.geometry.faces;
// New cubes array
cubes = [];
// Loop through every sphere's face
var cube, sphereFace, vertices, scaleVector, faceCentroid;
for (var i=0, len=sphereFaces.length; i < len; i++)
{
// Get the i-th sphere's face
sphereFace = sphereFaces[i];
// Create the i-th cube
cube = new THREE.Mesh(
new THREE.BoxGeometry(cube_L_coef * cubeSize, cube_l_coef * cubeSize, cube_h_coef * cubeSize),
new THREE.MeshNormalMaterial({
wireframe : false,
flatShading : true,
transparent : true,
opacity : 0.68,
fog : false // we have black fog in the scene
})
);
// Get the cube vertexes (corners)
vertices = cube.geometry.vertices;
for (var v=0; v < vertices.length; v++)
{
// Shift each vertex in order to e able to scale
// the cube from the bottom rather then the center
vertices[v].z -= cubeHalfSize;
}
// Move the v-th cube to the i-th face's center
faceCentroid = new THREE.Vector3( 0, 0, 0 );
faceCentroid.add( sphere.geometry.vertices[ sphereFace.a ] );
faceCentroid.add( sphere.geometry.vertices[ sphereFace.b ] );
faceCentroid.add( sphere.geometry.vertices[ sphereFace.c ] );
faceCentroid.x = (faceCentroid.x < 0) ? faceCentroid.x - 5 : faceCentroid.x + 5;
faceCentroid.y = (faceCentroid.y < 0) ? faceCentroid.y - 5 : faceCentroid.y + 5;
faceCentroid.z = (faceCentroid.z < 0) ? faceCentroid.z - 5 : faceCentroid.z + 5;
faceCentroid.divideScalar( 3 );
cube.position.x = faceCentroid.x;
cube.position.y = faceCentroid.y;
cube.position.z = faceCentroid.z;
// Scale the cube so it's smaller near the poles of the sphere (visual effect)
scaleValue = Math.abs(cube.position.y) / (radius);
cube.scale.x = 1 - (scaleValue * 0.7);
cube.scale.y = 1 - (scaleValue * 0.7);
cube.scale.z = 1 - (scaleValue * 0.7);
cube.scaleValue = 1 - (scaleValue * 0.7);
// Make the cube look at the center of the sphere
cube.lookAt(sphere.position);
// Push the new cube in the cubes' array
cubes.push(cube);
// Add the new cube to the scene
sphere.add(cube);
};
numCubes = cubes.length;
cube_l_coef = cube_L_coef = cube_h_coef = 0.0;
//#########################//
//#### PARTICLE SYSTEM ####//
//#########################//
var v,
color,
size,
particles,
particleGeometry,
numParticles = 1600, // x 7 (final number)(different properties)
materials = [],
particlesParamsCollection = [// [hex color, size] //
[0xA31621, 3.05], // red
[0x3CB371, 3.15], // green
[0x235686, 3.55], // blue
[0xfefefe, 2.70], // white
[0xA31621, 2.05], // red
[0x3CB371, 2.25], // green
[0x235686, 2.65] // blue
];
// New geometry for the particles
particleGeometry = new THREE.Geometry();
// Create and add the particles' vectors to the geometry
var rand_x, rand_y, rand_z
for (var i=0; i < numParticles; i++)
{
do {
// at least one out of three needs to be greater then | no_particle_space |
rand_x = randomRangeNumber( randomOutOfTwo(0, no_particle_space), spaceRangePS ) * randomOutOfTwo(-1, 1);
rand_y = randomRangeNumber( randomOutOfTwo(0, no_particle_space), spaceRangePS ) * randomOutOfTwo(-1, 1);
rand_z = randomRangeNumber( randomOutOfTwo(0, no_particle_space), spaceRangePS ) * randomOutOfTwo(-1, 1);
} // rarely is doing more than 1-2 cycles here
while( (Math.abs(rand_x) < no_particle_space && Math.abs(rand_y) < no_particle_space && Math.abs(rand_z) < no_particle_space) );
v = new THREE.Vector3( rand_x, //(rand_x < 0) ? rand_x - no_particle_space : rand_x + no_particle_space,
rand_y, //(rand_y < 0) ? rand_y - no_particle_space : rand_y + no_particle_space,
rand_z //(rand_z < 0) ? rand_z - no_particle_space : rand_z + no_particle_space
); // (random points around 0 in spaceRangePS)
particleGeometry.vertices.push(v);
};
// create ONE PARTICLE SYSTEM for each [size, color]
for (var i=0, len=particlesParamsCollection.length; i < len; i++)
{
color = particlesParamsCollection[i][0];
size = particlesParamsCollection[i][1];
materials[i] = new THREE.PointsMaterial( {size : size, sizeAttenuation : true} );
materials[i].color.setHex(color);
particles = new THREE.Points( particleGeometry, materials[i] );
particles.rotation.x = randomOutOfTwo(-1, 1) * Math.random() * 1000 + (i+1);
particles.rotation.y = randomOutOfTwo(-1, 1) * Math.random() * 1000 + (i+1);
particles.rotation.z = randomOutOfTwo(-1, 1) * Math.random() * 1000 + (i+1);
particles_systems.push(particles);
scene.add(particles);
};
}; // --- END createSphere() --- //
// Create two animated spiral spheres to be included on the poles of the main sphere
function createSpiralSpheres()
{
// Create the sphere geometry;
var sphereGeometry = new THREE.SphereGeometry(radiusSS, segmentsSS, ringsSS);
// Create the material for the spiral sphere
var material = new THREE.MeshStandardMaterial({
side : THREE.DoubleSide, // both side rendering;
color : 0x000000,
lights : true,
transparent : true,
alphaTest : 0.5
});
// Load the alpha texture image
var alphaTexture = new THREE.TextureLoader().load(alpha_texture_path);
// Add the alpha texture to the material and setup it
material.alphaMap = alphaTexture;
material.alphaMap.magFilter = THREE.NearestFilter;
material.alphaMap.wrapT = THREE.RepeatWrapping;
material.alphaMap.repeat.y = 1;
spiralSphereNorth = new THREE.Mesh(sphereGeometry, material);
spiralSphereSouth = spiralSphereNorth.clone();
sphere.add(spiralSphereNorth);
sphere.add(spiralSphereSouth);
spiralSphereSouth.position.y += radius;
spiralSphereNorth.position.y -= radius;
spiralSphereNorth.rotation.x = Math.PI;
}; // --- END createSpiralSpheres() --- //
// Creates and adds a set of lines (splineCurves) to the main sphere
// reproducing the Time Domain Data of the audio ('tdd').
function createLines()
{
var deltaPhi = 2*Math.PI / numWaves,
nextAngle = deltaPhi / 2, // set the picks in the desired position (start-angle)
tdd_size = tdd.length,
pickRate = 32,
delta_x = (2*radius - 1.5 * radiusSS) / tdd_size * pickRate;
for (var j = 0; j < numWaves; j++)
{
var splineCurve,
linePoints,
waveColor = getRandomColor(), // Get a random HEX color
curvePoints = [],
x_pos = 0 - radius + (1.5 / 2)*radiusSS;// sphere centered in (0, 0, 0)
for (var i = tdd_size - 1; i >= 0; i -= pickRate)
{
curvePoints.push(new THREE.Vector2( x_pos , 4*Math.random() - 2 )); // curvePoints.push(new THREE.Vector2( x_pos , 4*((tdd[j] - 255/2) / 10)));
x_pos += delta_x;
}
console.log("DEBUG:\n\tcurvePoints.length = " + curvePoints.length + "\t(pickRate = " + pickRate + ")\n\twaveColor = " + waveColor);
// Build the SplineCurve
splineCurve = new THREE.SplineCurve( curvePoints );
// Get enough points for the SplineCurve in order to build a smooth wave line (greater --> better --> costly)
linePoints = splineCurve.getPoints( tdd_size * sampleRate );
var waveGeometry = new THREE.BufferGeometry().setFromPoints( linePoints );
var waveMaterial = new THREE.LineBasicMaterial({
color : waveColor
});
// Create the final object to add to the scene
var wave = new THREE.Line( waveGeometry, waveMaterial );
// Put it on the correct axis
wave.rotateZ( Math.PI / 2 );
wave.rotateX( nextAngle );
wave.geometry.computeBoundingSphere();
// Save the wave for further use
waves.push(wave);
// Add it to the scene
sphere.add(wave);
// Get the next angle
nextAngle += deltaPhi;
}
wavesCreated = true;
}; // --- END createLines() --- //
//#########################//
//#### Audio Data ####//
//#########################//
// Log wavesurfer's warnings
wavesurfer.on('error', function(e) {
console.warn(e);
});
// Get the wavesurfer's analyser node object
analyser = wavesurfer.backend.analyser;
// 'channelCountMode' is set to 'explicit' on an analyserNode,
// so we can get the correct # of channels of the AudioNode in input
numChannels = analyser.channelCount;
console.log("DEBUG:\n\tnumChannels = " + numChannels);
// Set the FFT size (default fftSize=2048)(powers of 2)
// (fft scale to one channel size)
analyser.fftSize = fftSize * numChannels;
// FFT time averaging (0 meaning no time averaging). The default value is 0.8;
analyser.smoothingTimeConstant = smoothingTimeConstantFFT;
// Initialize the buffers for the Frequency and Time Domain Data:
// (it will be updated on 'onaudioprocess' event firing)
fft = new Uint8Array(analyser.frequencyBinCount);
tdd = new Uint8Array(analyser.fftSize); // this array should be the same length as the fftSize of the analyser;
// Array that will track smoothly the frequencies variations in time
// (it will be updated in onAudioAvailable() function, on 'onaudioprocess' event firing);
peaks = new Float32Array(fftSize);
console.log("DEBUG:\n\tfft-length \t\t= " + fft.length + "\n\tpeaks-length \t= " + peaks.length + "\n\ttdd-length \t\t= " + tdd.length);
// Run when audio data is available (after fft updates)
function onAudioAvailable()
{
// Compute and get the peaks' values of the audio signal
for (var i=0, fft_size = fft.length; i < fft_size; i++)
{
// Equalizer: attenuate low frequents and boost the high ones
//fft[i] *= -1 * Math.log((fft_size / 2 - 1.0*i) * (0.5 / fft_size / 2)) * fft_size;
if (peaks[i] < fft[i] + deltaPeaks) // to much vibration
{
// Assign a new peak value
peaks[i] = fft[i];
}
else
{
// decreasing the peak slowly till a new peaks is found
peaks[i] *= peaksDecreasingParam;
}
}
}; // --- END onAudioAvailable() --- //
// 'onKeyDown' events function
function setupKeyControls(e) {
// var x = camera.position.x,
// y = camera.position.y,
// z = camera.position.z;
switch (e.keyCode)
{
case 49: // 1 (Num. 1 key)
changeWavesColor = true;
break;
//default:
//console.log("DEBUG: pressed key: " + e.keyCode + " === " + e.code);
//break;
} // --- END switch --- //
// Update camera and look again at the origin
// camera.lookAt(scene.position);
// controls.update();
}; // --- END setupKeyControls(e)
// Add light to the spiral Spheres
function addLight()
{
lightNorth = new THREE.PointLight(lightNorthColor, lightNorthIntensity);
lightNorth.decay = 2;
lightSouth = new THREE.PointLight(lightSouthColor, lightSouthIntensity);
lightSouth.decay = 2;
spiralSphereNorth.add(lightNorth);
spiralSphereSouth.add(lightSouth);
lightNorth.position = spiralSphereNorth.position;
lightSouth.position = spiralSphereSouth.position;
}
// Create the (main) sphere
createSphere();
// Create the alpha texture animated spiral spheres
createSpiralSpheres();
// Add the lights to the spiral sphere
addLight();
// Create the wave lines
createLines();
// Call the animate() routine
animate();
// Call the GUI controller
guiController();
gui.closed = true;
}; // --- END init() --- //
function animate()
{
// Update the camera controls
// controls.update();
// New Animation Frame Request
window.requestAnimationFrame(animate);
// Call the main renderer
render();
// START STATS.js monitoring
stats.update();
}; // --- END animate() --- //
//##################################//
//#### //\\// RENDERER \\//\\ ####//
//##################################//
function render()
{
var tddAvg = 1.0,
time = Date.now() * 0.001;
//console.log("DEBUG:\ntime = " + time);
if (analyser) // "analyser" needs to be active here ! //
{
// Cubes scale's update as 'fft' variates //
var cube, sum;
for (var i=0, fft_size = peaks.length; i < numCubes; i++)
{
cube = cubes[i];
fft_index = i % fft_size;
// Scale the cube high as the i-th peaks amplitude (demo 1)
cube.scale.z = cube.scaleValue + cube_h_coef + ( (peaks[fft_index]) ? 1 + (3 * (fft[fft_index] / peaks[fft_index])) : 0);
cube.scale.y = cube.scaleValue + cube_L_coef;
cube.scale.x = cube.scaleValue + cube_l_coef;
}
// Lines points update as 'tdd' variates //
if (wavesCreated && tdd[0] > 0)
{
// Get the array average for spiral spheres' y-offset speed change
sum = tdd.reduce(function(a, b) { return a + b; });
tddAvg = sum / tdd.length;
updateLines();
}
}
// Spiral spheres alpha texture animation (y-offset variation)(buffer bouncing effect)
spiralSphereNorth.material.alphaMap.offset.y = offsetUpdateSpeed * tddAvg; // 10 * tddAvg * Math.cos(0.24 * time);
spiralSphereSouth.material.alphaMap.offset.y = offsetUpdateSpeed * tddAvg; // 10 * tddAvg * Math.cos(0.24 * time);
// Make the lights bouncing
lightNorth.position.y = spiralSphereNorth.position.y + offsetUpdateSpeed * tddAvg;
lightSouth.position.y = spiralSphereSouth.position.y - offsetUpdateSpeed * tddAvg;
// Sphere rotation (all the hierarchical structure of the sphere will rotate)
sphere.rotation.x = 0.7 * Math.sin(0.45 * time) + 1.72;
sphere.rotation.y = 0.6 * Math.sin(0.35 * time) + 2.31;
sphere.rotation.z = 0.5 * Math.cos(0.15 * time) + 1.57;
// Particle systems' rotation
for (var i = particles_systems.length - 1; i >= 0; i--) {
particles_systems[i].rotation.x = 0.57 * Math.cos(0.23 * time) + 0.11 * (i+1);
particles_systems[i].rotation.y = 0.55 * Math.cos(0.24 * time) + 0.12 * (i+1);
particles_systems[i].rotation.z = 0.53 * Math.sin(0.21 * time) + 0.13 * (i+1);
}
// Render the scene
renderer.render(scene, camera);
} // --- END render() --- //
function updateLines()
{
var deltaPhi = 2*Math.PI / numWaves,
nextAngle = deltaPhi / 2, // set the picks in the desired position (start-angle)
tdd_size = tdd.length,
pickRate = 32,
delta_x = (2*radius - 1.5 * radiusSS) / tdd_size * pickRate;
for (var i = 0; i < waves.length; i++)
{
var splineCurve,
linePoints,
waveColor = getRandomColor(), // Get a random HEX color
curvePoints = [],
x_pos = 0 - radius + (1.5 / 2)*radiusSS; // sphere centered in (0, 0, 0)
oldBufferPositions = waves[i].geometry.attributes.position.array;
for (var j = tdd_size - 1; j >= 0; j -= pickRate)
{
curvePoints.push(new THREE.Vector2( x_pos , 4*((tdd[j] - 255/2)/10)));
x_pos += delta_x;
}
// Build the SplineCurve
splineCurve = new THREE.SplineCurve( curvePoints );
// Get enough points for the SplineCurve in order to build a smooth wave line (greater --> better --> costly)
linePoints = splineCurve.getPoints( tdd_size * sampleRate );
var waveGeometry = new THREE.BufferGeometry().setFromPoints( linePoints );
var waveMaterial = new THREE.LineBasicMaterial({
color : waveColor
});
// Create the final object to get the properties from
var wave = new THREE.Line( waveGeometry, waveMaterial );
// COPY the position arrays content from the new 'wave'
var newBufferpositions = wave.geometry.attributes.position.array;
for ( var index = 0, l = oldBufferPositions.length; index < l; index ++ ) {
oldBufferPositions[ index ] = newBufferpositions[ index ];
oldBufferPositions[ index ] = newBufferpositions[ index ];
oldBufferPositions[ index ] = newBufferpositions[ index ];
if (changeWavesColor)
{
waves[i].material.color = wave.material.color; // update colors on-demand;
}
}
waves[i].geometry.attributes.position.needsUpdate = true; // required after the first render
sphere.geometry.computeBoundingSphere();
}
changeWavesColor = false; // update colors on-demand;
};
//###############################//
//#### Helper Functions ####//
//###############################//
// Returns a random number between min (inclusive) and max (exclusive)
function randomRangeNumber(min, max) {
return Math.random() * (max - min) + min;
}
// Returns on of the two arguments randomly
function randomOutOfTwo(first, second) {
return (Math.random() < 0.5) ? first : second;
}
// Returns a random HEX color string
function getRandomColor() // string HEX color
{
var c = '#'+Math.floor(Math.random()*16777215).toString(16);
while (c.length < 7) // We need a HEX color (7 chars)
{
c += Math.floor( Math.random()*10 ).toString();
}
return c;
};
var controller = {
SET_DEFAULT : function(){
setDefaultParams();
},
changeWavesColor : function(){
changeWavesColor = true;
},
ZOOM_OUT__ON_OFF : function(){
controls.maxDistance = controls.maxDistance === Infinity ? no_particle_space : Infinity;
if (controls.maxDistance === no_particle_space && Math.abs(camera.position.z) > no_particle_space) camera.position.z = no_particle_space;
},
Smoothness : 0.0,
PeaksTresholdUpdate : -55.5,
PeaksDecreasingRate : 1.0,
AudioVolume : 1.0,
cubeScale_L : -0.7,
cubeScale_l : -0.7,
cubeScale_h : -1.19,
NorthIntensity : 30,
NorthColor : "#0101FC",
SouthColor : "#FC0101",
SouthIntensity : 30,
SetSideRengering : THREE.DoubleSide, // spiral spheres internal side rendering ( THREE.DoubleSide )
BounceSpeed : 0.23
};
// GUI controller
function guiController()
{
gui = new dat.GUI({
width : 300,
load : getPresets(),
preset : 'RockPreset',
closeOnTop : true,
closed : false
});
gui.remember(controller);
gui.add(controller, "SET_DEFAULT").name("SET DEFAULT");
var f1 = gui.addFolder('Audio'); f1.open();
f1.add(controller, "Smoothness", 0.0, 1.0, 0.01).onChange(function()
{
analyser.smoothingTimeConstant = controller.Smoothness;
});
f1.add(controller, "PeaksTresholdUpdate", -255.0, 255.0, 0.5).onChange(function()
{
deltaPeaks = controller.PeaksTresholdUpdate;
});
f1.add(controller, "PeaksDecreasingRate", 0.5, 1.0, 0.001).onChange(function()
{
peaksDecreasingParam = controller.PeaksDecreasingRate;
});
f1.add(controller, "AudioVolume", 0.0, 1.0, 0.01).onChange(function()
{
wavesurfer.setVolume(controller.AudioVolume);
}).name("Change Audio Volume");
var f2 = gui.addFolder('Colors and Light'); f2.close();
f2.add(controller, "changeWavesColor").name("Change Wave Lines Colors (Random)");
f2.add(controller, "BounceSpeed", -2.0, 2.0, 0.01).onChange(function()
{
BounceSpeed = controller.BounceSpeed;
}).name("Bounce Speed");
f2.addColor(controller, "NorthColor").onChange(function(){
lightNorthColor = new THREE.Color( controller.NorthColor ).getHex();
lightNorth.color.setHex( lightNorthColor );
}).name("North Light Color");
f2.addColor(controller, "SouthColor").onChange(function(){
lightSouthColor = new THREE.Color( controller.SouthColor ).getHex();
lightSouth.color.setHex( lightSouthColor );
}).name("South Light Color");
f2.add(controller, "NorthIntensity", 0, 200, 0.5).onChange(function(){
lightNorthIntensity = controller.NorthIntensity;
lightNorth.intensity = lightNorthIntensity;
}).name("North Light Intensity");
f2.add(controller, "SouthIntensity", 0, 200, 0.5).onChange(function(){
lightSouthIntensity = controller.SouthIntensity;
lightSouth.intensity = lightSouthIntensity;
}).name("South Light Intensity");
f2.add(controller, "SetSideRengering", { Front: THREE.FrontSide, Back: THREE.BackSide, Double: THREE.DoubleSide }).onChange(function(){
spiralSphereNorth.material.side = controller.SetSideRengering;
spiralSphereSouth.material.side = controller.SetSideRengering;
}).name("Set Side Rendering (Material)");
var f3 = gui.addFolder('Cubes/Bars');
f3.add(controller, "cubeScale_L", -1.0, 1.0, 0.005).onChange(function()
{
cube_L_coef = controller.cubeScale_L;
});
f3.add(controller, "cubeScale_l", -1.0, 1.0, 0.005).onChange(function()
{
cube_l_coef = controller.cubeScale_l;
});
f3.add(controller, "cubeScale_h", -3.0, 3.0, 0.005).onChange(function()
{
cube_h_coef = controller.cubeScale_h;
});
gui.add(controller, "ZOOM_OUT__ON_OFF").name("ZOOM-OUT switch ON/OFF");
gui.preset = "Default"
}; // --- END guiController() --- //
// presetJSON: created from pressing the gear.
function getPresets() {
return {
"preset" : "RockPreset",
"closeOnTop" : true,
"closed" : false,
"remembered": {
"Default": {
"0": {
"Smoothness": 0,
"PeaksTresholdUpdate": -55.50,
"PeaksDecreasingRate": 1.0,
"AudioVolume": 1,
"BounceSpeed": 0.23,
"NorthColor": "#0101FC",
"SouthColor": "#FC0101",
"NorthIntensity": 30,
"SouthIntensity": 30,
"SetSideRengering": 2,
"cubeScale_L": -0.7,
"cubeScale_l": -0.7,
"cubeScale_h": -1.19
}
},
"BasicPreset": {
"0": {
"Smoothness": 0,
"PeaksTresholdUpdate": 10,
"PeaksDecreasingRate": 0.96,
"AudioVolume": 1,
"BounceSpeed": 0.23,
"NorthColor": "#0101FC",
"SouthColor": "#FC0101",
"NorthIntensity": 30,
"SouthIntensity": 30,
"SetSideRengering": 2,
"cubeScale_L": 0,
"cubeScale_l": 0,
"cubeScale_h": 0
}
},
"RocketPreset": {
"0": {
"Smoothness": 0,
"PeaksTresholdUpdate": -230,
"PeaksDecreasingRate": 0.96,
"AudioVolume": 1,
"BounceSpeed": 0.23,