-
Notifications
You must be signed in to change notification settings - Fork 1
/
cloud-5.js
1738 lines (1696 loc) · 64.6 KB
/
cloud-5.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
/**
* This script defines custom HTML elements and supporting code for the
* cloud-5 system. Once a custom element is used in the body of a Web page,
* its DOM object can be obtained, and then not only DOM methods but also
* custom methods can be called.
*
* In general, rather than subclassing these custom elements (although that
* is possible), users should define and set addon functions, code text, and
* other properties of the custom elements. All such user-defined properties
* have names ending in `_addon`.
*
* To simplify both usage and maintenance, internal styles are usually not
* used. Default styles are defined in the csound-5.css cascading style sheet.
* These styles can be overridden by the user.
*
* Usage:
*
* 1. Include the csound-5.js and csound-5.css scripts in the Web page.
* 2. Lay out and style the required custom elements as with any other HTNL
* elements. The w3.css style sheet is used internally and should also be
* included.
* 3. In a script element of the Web page:
* a. Define addons as JavaScript variables.
* b. Obtain DOM objects from custom elements.
* c. Assign custom elements and addons to their respective properties.
*/
/**
* Holds refernces to windows that must be closed on exit.
*/
globalThis.windows_to_close = [];
/**
* Close all secondary windows on exit.
*/
window.addEventListener("beforeunload", (event) => {
for (let window_to_close of globalThis.windows_to_close()) {
try {
window_to_close.close()
} catch (ex) {
console.warn(ex);
}
}
globalThis.windows_to_close = [];
});
/**
* Sets up the piece, and defines menu buttons. The user may assign the DOM
* objects of other cloud-5 elements to the `_overlay` properties.
*/
class Cloud5Piece extends HTMLElement {
constructor() {
super();
this.csound = null;
this.csoundac = null;
}
#csound_code_addon = null;
/**
* May be assigned the text of a Csound .csd patch. If so, the Csound
* patch will be compiled and run for every performance.
*/
set csound_code_addon(code) {
this.#csound_code_addon = code;
}
get csound_code_addon() {
return this.#csound_code_addon;
}
#shader_overlay = null;
/**
* May be assigned an instance of a cloud5-shader overlay. If so,
* the GLSL shader will run at all times, and will normally create the
* background for other overlays. The shader overlay may call
* addon functions either to visualize the audio of the performance,
* and/or to sample the video canvas to generate notes for performance by
* Csound.
*/
set shader_overlay(shader) {
this.#shader_overlay = shader;
// Back reference for shader to access Csound, etc.
shader.cloud5_piece = this;
this.show(this.#shader_overlay);
}
get shader_overlay() {
return this.#shader_overlay;
}
/**
* May be assigned the URL of a Web page to implement HTML-based controls
* for the performance. This is normally used only if there is a secondary
* display to use for these controls, so that the primary display can become
* fullscreen. The resulting Web page can obtain a reference to this piece
* from its `window.opener`, which is the window that opens the HTML
* controls window, and the opener can be used to control all aspects of the
* piece.
*
* For this to work the HTML controls and the piece must have the same
* origin.
*/
html_controls_url_addon = null;
/**
* Stores a reference to the HTML controls window; this reference will be
* used to close the HTML controls window upon leaving fullscreen.
*/
html_controls_window = null;
#control_parameters_addon = null;
/**
* May be assigned a JavaScript object consisting of Csound control
* parameters, with default values. The naming convention must be global
* Csound variable type, underscore{ , Csound instrument name},
* underscore, Csound control channel name. For example:
*
* control_parameters_addon = {
* "gk_Duration_factor": 0.8682696259761612,
* "gk_Iterations": 4,
* "gk_MasterOutput_level": -2.383888203863542,
* "gk_Shimmer_wetDry": 0.06843403205918619
* };
*
* The Csound orchestra should define matching control channels. Such
* parameters may also be used to control other processes.
* saveAs: function saveAs(presetName) {
if (!this.load.remembered) {
this.load.remembered = {};
this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
}
this.load.remembered[presetName] = getCurrentPreset(this);
this.preset = presetName;
addPresetOption(this, presetName, true);
this.saveToLocalStorageIfPossible();
},
*/
set control_parameters_addon(parameters) {
this.#control_parameters_addon = parameters;
this.create_dat_gui_menu(parameters);
}
get control_parameters_addon() {
return this.#control_parameters_addon;
}
#score_generator_function_addon = null;
/**
* May be assigned a score generating function. If so, the score generator
* will be called for each performance, and must generate and return a
* CsoundAC Score, which will be translated to a Csound score in text
* format, appended to the Csound patch, displayed in the piano roll
* overlay, and played or rendered by Csound.
*/
set score_generator_function_addon(score_generator_function) {
this.#score_generator_function_addon = score_generator_function;
}
get score_generator_function_addon() {
return this.#score_generator_function_addon;
}
#piano_roll_overlay = null;
/**
* May be assigned the DOM object of a <cloud5-piano-roll> element overlay.
* If so, the Score button will show or hide an animated, zoomable piano
* roll display of the generated CsoundAC Score.
*/
set piano_roll_overlay(piano_roll) {
this.#piano_roll_overlay = piano_roll;
this.#piano_roll_overlay.cloud5_piece = this;
}
get piano_roll_overlay() {
return this.#piano_roll_overlay;
}
/**
* May be assigned the DOM object of a <cloud5-log> element overlay. If so,
* the Log button will show or hide a scrolling view of messages from Csound or
* other sources.
*/
#log_overlay = null;
#about_overlay = null;
/**
* May be assigned the DOM object of a <cloud5-about> element overlay. If
* so, the About button will show or hide the overlay. The inner HTML of
* this element may contain license information, authorship, credits,
* program notes for the piece, or other information.
*/
get about_overlay() {
return this.#about_overlay;
}
set about_overlay(overlay) {
this.#about_overlay = overlay;
}
/**
* Called by Csound during performance, and prints the message to the
* scrolling text area of a <csound5-log> element overlay. This function may
* also be called by user code.
*
* @param {string} message
*/
csound_message_callback = async function (message) {
if (message === null) {
return;
}
this.log_overlay?.log(message);
let level_left = -100;
let level_right = -100;
if (non_csound(this.csound) == false) {
let score_time = await this.csound.getScoreTime();
level_left = await this.csound.getControlChannel("gk_MasterOutput_output_level_left");
level_right = await this.csound.getControlChannel("gk_MasterOutput_output_level_right");
let delta = score_time;
// calculate (and subtract) whole days
let days = Math.floor(delta / 86400);
delta -= days * 86400;
// calculate (and subtract) whole hours
let hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
// calculate (and subtract) whole minutes
let minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
// what's left is seconds
let seconds = delta % 60; // in theory the modulus is not required
if (level_left > 0) {
$("#vu_meter_left").css("color", "red");
} else if (level_left > -12) {
$("#vu_meter_left").css("color", "orange")
} else {
$("#vu_meter_left").css("color", "lightgreen");
}
if (level_right > 0) {
$("#vu_meter_right").css("color", "red");
} else if (level_right > -12) {
$("#vu_meter_right").css("color", "orange")
} else {
$("#vu_meter_right").css("color", "lightgreen");
}
$("#mini_console").html(sprintf("d:%4d h:%02d m:%02d s:%06.3f", days, hours, minutes, seconds));
$("#vu_meter_left").html(sprintf("L%+7.1f dBA", level_right));
$("#vu_meter_right").html(sprintf("R%+7.1f dBA", level_right));
};
}
/**
* A convenience function for printing the message in the
* scrolling <csound5-log> element overlay.
* @param {string} message
*/
log(message) {
this.csound_message_callback(message);
}
/**
* Metadata to be written to output files. The user may assign
* values to any of these fields.
*/
metadata = {
"artist": null,
"copyright": null,
"performer": null,
"title": null,
"album": null,
"track": null,
"tracknumber": null,
"date": null,
"publisher": null,
"comment": null,
"license": null,
"genre": null,
};
connectedCallback() {
this.innerHTML = `
<div class="w3-bar" id="main_menu" style="position:fixed;background:transparent;z-index:1000;">
<ul class="menu">
<li id="menu_item_play" title="Play piece on system audio output" class="w3-btn w3-hover-text-light-green">
Play</li>
<li id="menu_item_render" title="Render piece to soundfile" class="w3-btn w3-hover-text-light-green">Render
</li>
<li id="menu_item_record" title="Record live audio to soundfile" class="w3-btn w3-hover-text-light-green">Record</li>
<li id="menu_item_stop" title="Stop performance" class="w3-btn w3-hover-text-light-green">Stop</li>
<li id="menu_item_fullscreen" class="w3-btn w3-hover-text-light-green">Fullscreen</li>
<li id="menu_item_strudel" class="w3-btn w3-hover-text-light-green" style="display:none;">Strudel</li>
<li id="menu_item_piano_roll" title="Show/hide piano roll score" class="w3-btn w3-hover-text-light-green" style="display:none;">Score
</li>
<li id="menu_item_log" title="Show/hide message log" class="w3-btn w3-hover-text-light-green">Log
</li>
<li id="menu_item_about" title="Show/hide information about this piece"
class="w3-btn w3-hover-text-light-green">About</li>
<li id="mini_console" class="w3-btn w3-text-green w3-hover-text-light-green"></li>
<li id="vu_meter_left" class="w3-btn w3-hover-text-light-green"></li>
<li id="vu_meter_right" class="w3-btn w3-hover-text-light-green"></li>
<li id="menu_item_dat_gui"
title="Show/hide performance controls; 'Save' copies all control parameters to system clipboard"
class="w3-btn w3-left-align w3-hover-text-light-green w3-right"></li>
</ul>
</div>`;
this.vu_meter_left = document.querySelector("#vu_mter_left");
this.vu_meter_right = document.querySelector("#vu_mter_right");
this.mini_console = document.querySelector("#mini_console");
let menu_item_play = document.querySelector('#menu_item_play');
menu_item_play.onclick = ((event) => {
console.info("menu_item_play click...");
this.show(this.piano_roll_overlay)
// this.hide(this.strudel_overlay);
// this.hide(this.shader_overlay);
this.hide(this.log_overlay);
this.hide(this.about_overlay);
(() => this.render(false))();
});
let menu_item_render = document.querySelector('#menu_item_render');
menu_item_render.onclick = ((event) => {
console.info("menu_item_render click...");
this.show(this.piano_roll_overlay)
this.hide(this.strudel_overlay);
// this.hide(this.shader_overlay);
this.hide(this.log_overlay);
this.hide(this.about_overlay);
(() => this.render(true))();
});
let menu_item_record = document.querySelector('#menu_item_record');
menu_item_record.onclick = ((event) => {
this.log("menu_item_record click...\n");
// Start recording if not already recording,
// stop recording if already recording.
if (menu_item_record.innerText == "Record") {
this.csound?.setControlChannel("gk_record", 1);
menu_item_record.innerText = "Pause";
this.log("Csound has started recording...\n");
} else {
this.csound?.setControlChannel("gk_record", 0);
menu_item_record.innerText = "Record";
this.log("Csound has stopped recording.\n");
let soundefile_url = url_for_soundfile(this.csound);
}
});
let menu_item_stop = document.querySelector('#menu_item_stop');
menu_item_stop.onclick = ((event) => {
console.info("menu_item_stop click...");
this.stop();
});
let menu_item_fullscreen = document.querySelector('#menu_item_fullscreen');
menu_item_fullscreen.onclick = (async (event) => {
console.info("menu_item_fullscreen click...");
try {
if (this.#shader_overlay?.canvas?.requestFullscreen) {
let new_window = null;
// Make the shader canvas fullscreen in the primary window.
await this.#shader_overlay.canvas.requestFullscreen();
// Try to make the HTML controls, if available, fullscreen
// in the secondary window.
const secondary_screen = (await getScreenDetails()).screens.find(
(screen) => screen.isExtended,
);
if (secondary_screen && this?.html_controls_url_addon) {
let permissions_granted = false;
const { state } = await navigator.permissions.query({ name: 'window-management' });
if (state === 'granted') {
permissions_granted = true;
}
}
const url = window.location.origin + this?.html_controls_url_addon;
const window_features = `top=${secondary_screen.availTop}, left=${secondary_screen.availLeft}, width=${secondary_screen.availWidth}, height=${secondary_screen.availHeight}`;
let opened_window = window.open(url, 'HTMLControls', window_features);
if (!opened_window || opened_window.closed || typeof opened_window.closed == 'undefined') {
alert("Your browser is blocking popups. Please allow popups and redirects in the browser settings for this Web site.")
return;
} else {
this.html_controls_window = opened_window;
}
globalThis.windows_to_close.push(this.html_controls_window);
if (this.html_controls_window) {
// These will pile up and that would be a problem... if users
// repeatedly toggled fullscreen.
window.addEventListener("fullscreenchange", (event) => {
if (document.fullscreenElement) {
} else {
this.html_controls_window.close();
(value) => {
globalThis.windows_to_close = globalThis.windows_to_close.filter(function (ele) {
return ele != value;
});
}
}
});
}
}
} catch (ex) {
alert(ex.message + "\nIn the browser's 'Site permissions' for this Web site, set 'Pop-ups and redirects' to 'Allow' and 'Window management' to 'Allow'.");
};
});
let menu_item_strudel = document.querySelector('#menu_item_strudel');
menu_item_strudel.onclick = ((event) => {
console.info("menu_item_strudel click...");
//this.hide(this.piano_roll_overlay)
this.toggle(this.strudel_overlay);
// this.hide(this.shader_overlay);
// this.hide(this.log_overlay);
this.hide(this.about_overlay);
});
let menu_item_piano_roll = document.querySelector('#menu_item_piano_roll');
menu_item_piano_roll.onclick = ((evemt) => {
console.info("menu_item_piano_roll click...");
this.toggle(this.piano_roll_overlay)
//this.hide(this.strudel_overlay);
// this.hide(this.shader_overlay);
// this.hide(this.log_overlay);
this.hide(this.about_overlay);
});
let menu_item_log = document.querySelector('#menu_item_log');
menu_item_log.onclick = ((event) => {
console.info("menu_item_log click...");
//this.show(this.piano_roll_overlay)
//this.hide(this.strudel_overlay);
//this.hide(this.shader_overlay);
this.toggle(this.log_overlay);
this.hide(this.about_overlay);
});
let menu_item_about = document.querySelector('#menu_item_about');
menu_item_about.onclick = ((event) => {
console.info("menu_item_about click...");
this.hide(this.piano_roll_overlay)
this.hide(this.strudel_overlay);
///this.hide(this.shader_overlay);
this.hide(this.log_overlay);
this.toggle(this.about_overlay);
this.strudel_component?.focus(true);
});
// Ensure that the dat.gui controls are children of the _Controls_ button.
this.create_dat_gui_menu();
document.onkeydown = ((e) => {
let e_char = String.fromCharCode(e.keyCode || e.charCode);
if (e.ctrlKey === true) {
if (e_char === 'H') {
let console = document.getElementById("console");
if (console.style.display === "none") {
console.style.display = "block";
} else {
console.style.display = "none";
}
this.gui.closed = true;
gui.closed = false;
} else if (e_char === 'G') {
this.score_generator_function_addon();
} else if (e_char === 'P') {
this.play();
} else if (e_char === 'S') {
this.stop();
} else if (e_char === 'C') {
this?.piano_roll_overlay.recenter();
}
}
});
this.show(this.shader_overlay);
window.addEventListener('load', function (event) {
let save_button = this.gui.domElement.querySelector('span.button.save');
save_button.onclick = function (event) {
this.copy_parameters()
}.bind(this);
}.bind(this));
window.addEventListener("unload", function (event) {
nw_window?.close();
});
}
/**
* Copies all _current_ dat.gui parameters to the system clipboard in
* JSON format.
*
* @param {Object} parameters A dictionary containing the current state of all
* controls; keys are control parameter names, values are control parameter
* values. This can be pasted from the clipboard into source code, as a
* convenient method of updating a piece with parameters that have been tweaked
* during performance.
*/
copy_parameters() {
let copied_parameters = JSON.parse(JSON.stringify(this?.control_parameters_addon))
delete copied_parameters?.load;
const json_text = JSON.stringify(copied_parameters, null, 4);
navigator.clipboard.writeText(json_text);
if (this.csound) {
this.csound.Message("Copied all control parameters to system clipboard.\n");
}
}
/**
* @function render
*
* @memberof Cloud5Piece
*
* @description Invokes Csound and/or Strudel to perform music, by default to
* the audio output interface, but optionally to a local soundfile. Acts as an
* async member function because it is bound to this.
*
* @param {Boolean} is_offline If true, renders to a local soundfile.
*/
render = async function (is_offline) {
this.csound = await get_csound((message) => this.csound_message_callback(message));
if (non_csound(this.csound)) {
return;
}
this?.log_overlay.clear();
this.csoundac = await createCsoundAC();
for (const key in this.metadata) {
const value = this.metadata[key];
if (value !== null) {
// CsoundAudioNode does not have the metadata facility.
this.csound?.setMetadata(key, value);
}
}
let csd;
csd = this.csound_code_addon.slice();
if (this.score_generator_function_addon) {
let score = await this.score_generator_function_addon();
if (score) {
let csound_score = await score.getCsoundScore(12., false);
csound_score = csound_score.concat("\n</CsScore>");
csd = this.csound_code_addon.replace("</CsScore>", csound_score);
}
}
if (is_offline == true) {
csd = csd.replace("-odac", "-o" + document.title + ".wav");
}
// Save the .csd file so we can debug a failing orchestra,
// instead of it just nullifying Csound.
const csd_filename = document.title + '-generated.csd';
write_file(csd_filename, csd);
try {
let result = await this.csound.compileCsdText(csd);
this.csound_message_callback("CompileCsdText returned: " + result + "\n");
} catch (e) {
alert(e);
}
await this.csound.start();
this.csound_message_callback("Csound has started...\n");
// Send _current_ dat.gui parameter values to Csound
// before actually performing.
this.send_parameters(this.control_parameters_addon);
if (is_offline == false) {
if (!(this?.csound.getNode)) {
this.csound.perform();
}
if (typeof strudel_view !== 'undefined') {
if (strudel_view !== null) {
console.info("strudel_view:", this.strudel_view);
strudel_view?.setCsound(this.csound);
strudel_view?.setCsoundAC(this.csoundac);
strudel_view?.setParameters(this.control_parameters_addon);
strudel_view?.startPlaying();
}
}
} else {
// Returns before finishing because Csound will perform in a separate
// thread.
await this.csound.performAndPostProcess();
}
this?.piano_roll_overlay?.trackScoreTime();
this?.csound_message_callback("Csound is playing...\n");
}
/**
* Stops both Csound and Strudel from performing.
*/
stop = async function () {
this.piano_roll_overlay?.stop();
await this.csound.stop();
await this.csound.cleanup();
this.csound.reset();
this.strudel_overlay?.stop();
this.csound_message_callback("Csound has stopped.\n");
};
/**
* Helper function to show custom element overlays.
*
* @param {Object} overlay
*/
show(overlay) {
if (overlay) {
overlay.style.display = 'block';
}
}
/**
* Helper function to hide custom element overlays.
*
* @param {Object} overlay
*/
hide(overlay) {
if (overlay) {
overlay.style.display = 'none';
}
}
/**
* Helper function to show the overlay if it is
* hidden, or to hide the overlay if it is visible
*
* @param {Object} overlay
*/
toggle(overlay) {
if (overlay) {
if (overlay.checkVisibility() == true) {
this.hide(overlay);
} else {
this.show(overlay);
}
}
}
create_dat_gui_menu(parameters) {
let dat_gui_parameters = { autoPlace: false, closeOnTop: true, closed: true, width: 400, useLocalStorage: false };
if (parameters) {
dat_gui_parameters = Object.assign(this.get_default_preset(), dat_gui_parameters);
}
this.gui = new dat.GUI(dat_gui_parameters);
let dat_gui = document.getElementById('menu_item_dat_gui');
// The following assumes that there is only ever one child node of the
// menu item.
if (dat_gui.children.length == 0) {
dat_gui.appendChild(this.gui.domElement);
} else {
// Replaces the existing dat.gui root node with the new one.
dat_gui.replaceChild(this.gui.domElement, dat_gui.children.item(0));
}
}
get_default_preset() {
if (this.#control_parameters_addon.hasOwnProperty('preset')) {
const preset_name = this.#control_parameters_addon.preset;
const preset = this.#control_parameters_addon.remembered[preset_name][0];
return preset;
} else {
return this.#control_parameters_addon;
}
}
/**
* Sends a dictionary of parameters to Csound at the start of performance.
* The keys are the literal Csound control channel names, and the values are
* the values of those channels.
*
* @param {Object} parameters
*/
send_parameters(parameters) {
if (non_csound(this.csound) == false) {
this.csound_message_callback("Sending initial state of control perameters to Csound...\n")
for (const [name, value] of Object.entries(parameters)) {
this.csound_message_callback(name + ": " + value + "\n");
this.csound?.setControlChannel(name, parseFloat(value));
}
}
}
/**
* Adds a new folder to the Controls menu of the piece.
*
* @param {string} name The name of the folder.
* @returns {Object} The new folder.
*/
menu_folder_addon(name) {
let folder = this.gui.addFolder(name);
return folder;
}
/**
* Adds a new slider to a folder of the Controls menu of the piece.
*
* @param {Object} gui_folder The folder in which to place the slider.
* @param {string} token The name of the slider, usually the name of a
* Csound message channel.
* @param {number} minimum The minimum value of the slider (may be
* negative).
* @param {number} maximum The maximum value of the slider.
* @param {number} step An optional value for the granularity of values.
*/
menu_slider_addon(gui_folder, token, minimum, maximum, step, name_) {
const on_parameter_change = ((value) => {
this.gk_update(token, value);
});
if (name_) {
gui_folder.add(this.get_default_preset(), token, minimum, maximum, step).name(name_).listen().onChange(on_parameter_change);
} else {
gui_folder.add(this.get_default_preset(), token, minimum, maximum, step).listen().onChange(on_parameter_change);
}
// Remembers parameter values. Required for the 'Revert' button to
// work, and to be able to save/restore new presets.
this.gui.remember(this.control_parameters_addon);
};
/**
* Called by the browser when the user updates the value of a control in the
* Controls menu, and sends the update to the Csound control channel with
* the same name.
*
* @param {string} name The literal name of the Csound control channel.
* @param {number} value The current value of that channel.
*/
gk_update(name, value) {
const numberValue = parseFloat(value);
console.info("gk_update: name: " + name + " value: " + numberValue);
if (non_csound(this.csound) == false) {
this.csound?.setControlChannel(name, numberValue);
}
};
/**
* Adds a user-defined onclick handler function to the Controls menu of the
* piece.
*
* @param {Object} control_parameters_addon Dictionary containing all control parameters.
* @param {Object} gui_folder The folder to which the command will be added.
* @param {string} name The name of the command.
* @param {Function} onclick User-defined function to execute the command.
*/
menu_add_command(control_parameters_addon, gui_folder, name, onclick) {
control_parameters_addon['name'] = onclick;
gui_folder.add(this.control_parameters_addon, name)
}
}
customElements.define("cloud5-piece", Cloud5Piece);
/**
* Displays a CsoundAC Score as a 3-dimensional piano roll. During
* performance, a moving red ball indicates the current position of
* the performance in the score. The user may use the trackball
* to zoom in or out of the score, to drag it, or to spin it around.
*/
class Cloud5PianoRoll extends HTMLElement {
constructor() {
super();
this.cloud5_piece = null;
this.silencio_score = new Silencio.Score();
this.csoundac_score = null;
this.canvas = null;
this.interval_id = null;
}
connectedCallback() {
this.innerHTML = `
<canvas id="display" class="cloud5-score-canvas">
`;
this.canvas = this.querySelector('#display');
if (this.csoundac_score !== null) {
this.draw(this.csoundac_score);
}
let menu_button = document.getElementById("menu_item_piano_roll");
menu_button.style.display = 'inline';
}
/**
* Called by the browser to update the display of the Score. It is
* translated to a Silencio.Score object, which is what is actually
* displayed.
*
* @param {CsoundAC.Score} score A generated CsoundAC.Score object.
*/
draw_csoundac_score(score) {
this.silencio_score = new Silencio.Score();
let i;
let n = score.size();
for (i = 0; i < n; ++i) {
let event = score.get(i);
let p0_time = event.getTime();
let p1_duration = event.getDuration();
let p2_status = event.getStatus();
let p3_channel = event.getChannel();
let p4_key = event.getKey();
let p5_velocity = event.getVelocity();
let p6_x = event.getHeight();
let p7_y = event.getPan();
let p8_z = event.getDepth();
let p9_phase = event.getPhase();
this.silencio_score.add(p0_time, p1_duration, p2_status, p3_channel, p4_key, p5_velocity, p6_x, p7_y, p8_z, p9_phase);
}
this.draw_silencio_score(this.silencio_score);
}
/**
* A updates the WebGL display of the generated Silencio Score object.
*
* @param {Silencio.Score} score
*/
draw_silencio_score(score) {
this.silencio_score = score;
this.silencio_score.draw3D(this.canvas);
}
/**
* Called by a timer during performance to update the play
* position in the piano roll display.
*/
trackScoreTime() {
if (non_csound(this?.cloud5_piece?.csound)) {
return;
}
let interval_callback = async function () {
let score_time = await this?.cloud5_piece?.csound?.GetScoreTime();
this?.silencio_score.progress3D(score_time);
};
let bound_interval_callback = interval_callback.bind(this);
this.interval_id = setInterval(bound_interval_callback, 200);
}
/**
* Stops the timer that is updating the play position of the score.
*/
stop() {
clearInterval(this.interval_id);
}
recenter() {
this.silencio_score.lookAtFullScore3D();
}
}
customElements.define("cloud5-piano-roll", Cloud5PianoRoll);
/**
* Contains an instance of the Strudel REPL that can use Csound as an output,
* and that starts and stops along wth Csound.
*/
class Cloud5Strudel extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.innerHTML = `
<strudel-repl-component id="strudel_view" class='cloud5-strudel-repl' style='position:fixed;z-index:4001;'>
<!--
${this.#strudel_code_addon}
-->
</strudel-repl-component>
`;
this.strudel_component = this.querySelector('#strudel_view');
this.strudel_component.addEventListener("focusout", (event) => {
console.log("strudel_component lost focus.");
});
let menu_button = document.getElementById("menu_item_strudel");
menu_button.style.display = 'inline';
}
/**
* Starts the Strudel performance loop (the Cyclist).
*/
start() {
this.strudel_component.startPlaying();
}
/**
* Stops the Strudel performance loop (the Cyclist).
*/
stop() {
this.strudel_component.stopPlaying();
}
#strudel_code_addon = null;
/**
* Contains the text of a user-defined Strudel patch, exactly as would
* normally be entered by the user in the Strudel REPL. This patch may
* also import and reference modules defined by the cloud-5 system, such
* as statefulpatterns.mjs or csoundac.js.
*/
set strudel_code_addon(code) {
this.#strudel_code_addon = code;
// Reconstruct the element.
this.connectedCallback();
}
get strudel_code_addon() {
return this.#strudel_code_addon;
}
#control_parameters_addon = null;
/**
* Gets or sets optional control parameters.
*/
set control_parameters_addon(parameters_) {
this.#control_parameters_addon = parameters_;
globalThis.parameters = parameters_;
// Reconstruct the element.
this.connectedCallback();
}
get control_parameters_addon() {
return this.#control_parameters_addon;
}
}
customElements.define("cloud5-strudel", Cloud5Strudel);
/**
* Presents visuals generated by a GLSL shader. These visuals can show a
* visualization of the music, or be sampled to generate notes for Csound to
* perform.
*
* The SWSS glsl function accepts a dictionary of parameters, documented
* here: https://github.com/google/swissgl/blob/main/docs/API.md. The most
* often used of these parameters have setters in this class.
*/
class Cloud5Shader extends HTMLElement {
constructor() {
super();
/**
* The user may define a vertex shader in GLSL code for generating
* visuals, and assign a string containing the code to this property.
*/
this.glsl_parameters = {};
/**
* The user may define a function that will be called at intervals to
* receive a real-time FFT analysis of the audio; the function should
* downsample and/or otherwise process the analysis to generate CsoundAC
* Notes, which must be returned in a CsoundAC Score. The user-defined
* function must be assigned to this property.
*/
this.shader_sampler_hook = null;
/**
* The user may define a function that will be called at intervals to
* receive an FFT analysis of the performance; the function should use
* these to compute GLSL uniforms that will in some way control the
* appearance and behavior of the shader visuals. The user-defined
* function must be assigned to this property.
*/
this.audio_visualizer_hook = null;
}
/**
* Called by the browser whenever this element is added to the document.
*/
connectedCallback() {
this.canvas = document.createElement('canvas');
this.appendChild(this.canvas);
this.canvas.style.position = 'absolute';
this.canvas.style.top = '0';
this.canvas.style.left = '0';
this.canvas.style.margin_top = '40px';
this.canvas.style.display = 'block';
this.canvas.style.width = '100%';
this.canvas.style.height = '100%';
//this.canvas.style.zIndex = '0';
this.glsl = SwissGL(this.canvas);
this.slowdown = 1000;
}
#shader_parameters_addon = null;
/**
* Several objects must be defined at the same time before creating the
* shader. These objects are passed in these options.
*/
set shader_parameters_addon(options) {
this.#shader_parameters_addon = options;
this.glsl = SwissGL(this.canvas);
let render = ((t) => {
t /= 1000;
this.glsl({ ...this.#shader_parameters_addon, t });
requestAnimationFrame(render);
});
requestAnimationFrame(render);
}
get shader_parameters_addon() {
return this.#shader_parameters_addon;
}
#cloud5_piece = null;
/**
* Back reference to the piece, which can be used e.g. to get a reference to
* Csound.
*/
set cloud5_piece(piece) {
this.#cloud5_piece = piece;
}
get cloud5_piece() {
return this.#cloud5_piece;
}
}
customElements.define("cloud5-shader", Cloud5Shader);
/**
* Presents visuals generated by a GLSL shader. These visuals can show a
* visualization of the music, or be sampled to generate notes for Csound to
* perform.
*
* This class is specifically designed to simplify the use of shaders
* developed in or adapted from the ShaderToy Web site. Other types of shader
* also can be used.
*/
class Cloud5ShaderToy extends HTMLElement {
gl = null;
shader_program = null;
vertex_shader = `#version 300 es
in vec2 inPos;
void main() {
gl_Position = vec4(inPos.xy, 0.0, 1.0);
}`;
analyser = null;
uniforms = {};
uniform_locations = {};
attributes = null;
set_uniforms = null;
get_attributes = null;
frequency_domain_data = null;
time_domain_data = null;
image_sample_buffer = null;
channel0_texture_unit = null;
channel0_texture = null;
channel0_sampler = null;
current_events = {};
prior_events = {};
rendering_frame = 0;
image_sample_buffer = null;
prior_image_sample_buffer = null;
vertex_shader_code_addon = `#version 300 es
in vec2 inPos;
void main() {
gl_Position = vec4(inPos.xy, 0.0, 1.0);
}
`;
constructor() {
super();
}
connectedCallback() {
this.innerHTML = `
<canvas id="display" class="cloud5-shader-canvas">
`;
this.canvas = this.querySelector('#display');
}
#cloud5_piece = null;
/**
* Back reference to the piece, which can be used e.g. to get a reference to
* Csound.
*/
set cloud5_piece(piece) {
this.#cloud5_piece = piece;
}
get cloud5_piece() {