forked from sugarlabs/musicblocks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogo.js
2441 lines (2193 loc) · 84.4 KB
/
logo.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
// Copyright (c) 2014-2021 Walter Bender
// Copyright (c) 2015 Yash Khandelwal
// Copyright (c) 2020 Anindya Kundu
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the The GNU Affero General Public
// License as published by the Free Software Foundatioff; either
// version 3 of the License, or (at your option) any later version.
//
// You should have received a copy of the GNU Affero General Public
// License along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
/*
global
_, Notation, Synth, instruments, instrumentsFilters,
instrumentsEffects, Singer, Tone, CAMERAVALUE, doUseCamera,
VIDEOVALUE, last, getIntervalDirection, getIntervalNumber,
mixedNumber, rationalToFraction, doStopVideoCam, StatusMatrix,
getStatsFromNotation, delayExecution, DEFAULTVOICE
*/
/*
exported
Queue, Logo, DEFAULTVOLUME, PREVIEWVOLUME, DEFAULTDELAY,
OSCVOLUMEADJUSTMENT, TONEBPM, TARGETBPM, TURTLESTEP, NOTEDIV,
NOMICERRORMSG, NANERRORMSG, NOSTRINGERRORMSG, NOBOXERRORMSG,
NOACTIONERRORMSG, NOINPUTERRORMSG, NOSQRTERRORMSG,
ZERODIVIDEERRORMSG, EMPTYHEAPERRORMSG, INVALIDPITCH, POSNUMBER,
NOTATIONNOTE, NOTATIONDURATION, NOTATIONDOTCOUNT,
NOTATIONTUPLETVALUE, NOTATIONROUNDDOWN, NOTATIONINSIDECHORD,
NOTATIONSTACCATO
*/
const DEFAULTVOLUME = 50;
const PREVIEWVOLUME = 80;
const DEFAULTDELAY = 500; // milliseconds
// The oscillator runs hot. We must scale back its volume.
const OSCVOLUMEADJUSTMENT = 1.5;
const TONEBPM = 240; // seems to be the default
const TARGETBPM = 90; // what we'd like to use for beats per minute
const TURTLESTEP = -1; // run in step-by-step mode
const NOTEDIV = 8; // number of steps to divide turtle graphics
// These error messages don't need translation since they are
// converted into artwork w/o text.
const NOMICERRORMSG = "The microphone is not available.";
const NANERRORMSG = "Not a number.";
const NOSTRINGERRORMSG = "Not a string.";
const NOBOXERRORMSG = "Cannot find box";
const NOACTIONERRORMSG = "Cannot find action.";
const NOINPUTERRORMSG = "Missing argument.";
const NOSQRTERRORMSG = "Cannot take square root of negative number.";
const ZERODIVIDEERRORMSG = "Cannot divide by zero.";
const EMPTYHEAPERRORMSG = "empty heap.";
const POSNUMBER = "Argument must be a positive number";
const INVALIDPITCH = _("Not a valid pitch name");
const NOTATIONNOTE = 0;
const NOTATIONDURATION = 1;
const NOTATIONDOTCOUNT = 2;
const NOTATIONTUPLETVALUE = 3;
const NOTATIONROUNDDOWN = 4;
const NOTATIONINSIDECHORD = 5; // deprecated
const NOTATIONSTACCATO = 6;
/**
* @class
* @classdesc Queue entry for managing running blocks.
*/
class Queue {
/**
* @constructor
* @param blk - block
* @param count - count
* @param parentBlk - parent block
* @param args - arguments
*/
constructor(blk, count, parentBlk, args) {
this.blk = blk;
this.count = count;
this.parentBlk = parentBlk;
this.args = args;
}
}
/**
* Class dealing with executing the programs.
*
* @class
* @classdesc This contains all the variables and the methods which
* control the execution of the programs. Contains a method to dispatch
* turtle commands which call methods of Turtle and Turles. Also contains
* notation code.
*/
class Logo {
/**
* @constructor
*/
constructor(activity) {
this.activity = activity;
this.blockList = this.activity.blocks.blockList;
this._onStopTurtle = this.activity.onStopTurtle;
this._onRunTurtle = this.activity.onRunTurtle;
this._meSpeak = this.activity.meSpeak;
// Widgets
this.phraseMaker = null;
this.pitchDrumMatrix = null;
this.arpeggio = null;
this.rhythmRuler = null;
this.timbre = null;
this.pitchStaircase = null;
this.temperament = null;
this.tempo = null;
this.pitchSlider = null;
this.musicKeyboard = null;
this.modeWidget = null;
this.Oscilloscope = null;
this.oscilloscopeTurtles = [];
this.meterWidget = null;
this.statusMatrix = null;
this.evalFlowDict = {};
this.evalArgDict = {};
this.evalParameterDict = {};
this.evalSetterDict = {};
this.evalOnStartList = {};
this.evalOnStopList = {};
this.pluginVars = {};
this.pluginReturnValue = null;
this.eventList = {};
this.receivedArg = null;
this.inputValues = {};
this.boxes = {};
this.actions = {};
this.returns = {};
this.turtleHeaps = {};
this.turtleDicts = {};
// We store each case arg and flow by switch block no. and turtle
this.switchCases = {};
this.switchBlocks = {};
// Related to running programs
this._lastNoteTimeout = null;
this._alreadyRunning = false;
this._prematureRestart = false;
this._runningBlock = null;
this._ignoringBlock = null;
this.time = 0;
this.firstNoteTime = null;
this._turtleDelay = 0;
this.sounds = [];
this.cameraID = null;
this.stopTurtle = false;
this.lastKeyCode = null;
// Widget-related attributes
this.showPitchDrumMatrix = false;
this.inPitchDrumMatrix = false;
this.inRhythmRuler = false;
this.rhythmRulerMeasure = null;
this.inPitchStaircase = false;
this.inTempo = false;
this.inPitchSlider = false;
this.inMusicKeyboard = false;
this._currentDrumlock = null;
this.inTimbre = false;
this.inArpeggio = false;
this.insideModeWidget = false;
this.insideMeterWidget = false;
this.insideTemperament = false;
// pitch-rhythm matrix
this.inMatrix = false;
this.tupletRhythms = [];
this.addingNotesToTuplet = false;
this.drumBlocks = [];
this.pitchBlocks = [];
// Parameters used by duplicate block
this.connectionStore = {};
this.connectionStoreLock = false;
// tuplet
this.tuplet = false;
this.tupletParams = [];
// object that deals with notations
this._notation = new Notation(this.activity);
// parameters used by notations
this.notationOutput = "";
this.notationNotes = {};
this.MIDIOutput = "";
this.guitarOutputHead = "";
this.guitarOutputEnd = "";
this.runningLilypond = false;
this.collectingStats = false;
this.runningAbc = false;
this.runningMxml = false;
this._checkingCompletionState = false;
this.recording = false;
this.temperamentSelected = [];
this.customTemperamentDefined = false;
this.specialArgs = [];
// Load the default synthesizer
this.synth = new Synth();
this.synth.changeInTemperament = false;
// Mode widget
this.modeBlock = null;
// Meter widget
this._meterBlock = null;
// Status matrix
this.inStatusMatrix = false;
this.inOscilloscope = false;
this.updatingStatusMatrix = false;
this.statusFields = [];
// When running in step-by-step mode, the next command to run
// is queued here.
this.stepQueue = {};
this._unhighlightStepQueue = {};
this.svgOutput = "";
this.svgBackground = true;
this.mic = null;
this.volumeAnalyser = null;
this.pitchAnalyser = null;
}
// ========= Setters, Getters =================================================================
/**
* @param {Function} onStopTurtle
*/
set onStopTurtle(onStopTurtle) {
this._onStopTurtle = onStopTurtle;
}
/**
* @returns {Function}
*/
get onStopTurtle() {
return this._onStopTurtle;
}
/**
* @param {Function} onRunTurtle
*/
set onRunTurtle(onRunTurtle) {
this._onRunTurtle = onRunTurtle;
}
/**
* @returns {Function}
*/
get onRunTurtle() {
return this._onRunTurtle;
}
/**
* @param {Number} turtleDelay - pause between each block as the program executes
*/
set turtleDelay(turtleDelay) {
this._turtleDelay = turtleDelay;
}
/**
* @returns {Number} pause between each block as the program executes
*/
get turtleDelay() {
return this._turtleDelay;
}
/**
* @returns {Object} object of Notation
*/
get notation() {
return this._notation;
}
// ========= Utilities ========================================================================
/**
* Restores any broken connections made in duplicate notes clamps.
*
* @returns {void}
*/
_restoreConnections() {
for (const turtle in this.connectionStore) {
for (const blk in this.connectionStore[turtle]) {
const n = this.connectionStore[turtle][blk].length;
for (let i = 0; i < n; i++) {
const obj = this.connectionStore[turtle][blk].pop();
this.blockList[obj[0]].connections[obj[1]] = obj[2];
if (obj[2] != null) {
this.blockList[obj[2]].connections[0] = obj[0];
}
}
}
}
}
/**
* Preps synths for each turtle.
*
* @returns {void}
*/
prepSynths() {
this.synth.newTone();
for (const turtle in this.activity.turtles.turtleList) {
const tur = this.activity.turtles.ithTurtle(turtle);
if (!(turtle in instruments)) {
instruments[turtle] = {};
instrumentsFilters[turtle] = {};
instrumentsEffects[turtle] = {};
}
// Make sure there is a default synth for each turtle
if (!(DEFAULTVOICE in instruments[turtle])) {
this.synth.createDefaultSynth(turtle);
}
// Copy any preloaded synths from the default turtle
for (const instrumentName in instruments[0]) {
if (!(instrumentName in instruments[turtle])) {
this.synth.loadSynth(turtle, instrumentName);
// Copy any filters
if (instrumentName in instrumentsFilters[0]) {
instrumentsFilters[turtle][instrumentName] =
instrumentsFilters[0][instrumentName];
}
// ...and any effects
if (instrumentName in instrumentsEffects[0]) {
instrumentsEffects[turtle][instrumentName] =
instrumentsEffects[0][instrumentName];
}
}
}
tur.singer.synthVolume = {
"electronic synth": [DEFAULTVOLUME],
"noise1": [DEFAULTVOLUME],
"noise2": [DEFAULTVOLUME],
"noise3": [DEFAULTVOLUME]
};
tur.singer.synthVolume[DEFAULTVOICE] = [DEFAULTVOLUME];
}
Singer.setMasterVolume(this, DEFAULTVOLUME);
for (const turtle in this.activity.turtles.turtleList) {
for (const synth in this.activity.turtles.ithTurtle(turtle).singer.synthVolume) {
Singer.setSynthVolume(this, turtle, synth, DEFAULTVOLUME);
}
}
}
/**
* Initialises and starts a default synth.
*
* @param turtle
* @returns {void}
*/
resetSynth(turtle) {
if (!(DEFAULTVOICE in instruments[turtle])) {
this.synth.createDefaultSynth(turtle);
}
Singer.setMasterVolume(this.activity.logo, DEFAULTVOLUME);
for (const turtle in this.activity.turtles.turtleList) {
for (const synth in this.activity.turtles.ithTurtle(turtle).singer.synthVolume) {
Singer.setSynthVolume(this, turtle, synth, DEFAULTVOLUME);
}
}
this.synth.start();
}
/**
* Initialises the microphone.
*
* @returns {void}
*/
initMediaDevices() {
let mic = new Tone.UserMedia();
try {
mic.open();
} catch (e) {
this.activity.errorMsg(NOMICERRORMSG);
mic = null;
}
this.mic = mic;
this.limit = 16384;
}
/**
* Clears note params.
*
* @param {Object} turtle - Turtle object
* @param blk
* @param drums
* @returns {void}
*/
clearNoteParams(turtle, blk, drums) {
turtle.singer.oscList[blk] = [];
turtle.singer.noteBeat[blk] = [];
turtle.singer.noteBeatValues[blk] = [];
turtle.singer.noteValue[blk] = null;
turtle.singer.notePitches[blk] = [];
turtle.singer.noteOctaves[blk] = [];
turtle.singer.noteCents[blk] = [];
turtle.singer.noteHertz[blk] = [];
turtle.singer.embeddedGraphics[blk] = [];
turtle.singer.noteDrums[blk] = drums !== null ? drums : [];
}
/**
* Speaks all characters in the range of comma, full stop, space, A to Z, a to z in the input text.
*
* @param {string} text
* @returns {void}
*/
processSpeak(text) {
let new_text = "";
for (const i in text) {
if (new RegExp("^[A-Za-z,. ]$").test(text[i])) new_text += text[i];
}
if (this.meSpeak !== null) {
this.meSpeak.speak(new_text);
}
}
/**
* Shows information: with camera, in image form, at URL, as text.
*
* @param turtle
* @param blk
* @param arg0
* @param arg1
* @returns {void}
*/
processShow(turtle, blk, arg0, arg1) {
if (typeof arg1 === "string") {
const len = arg1.length;
if (len === 14 && arg1.substr(0, 14) === CAMERAVALUE) {
doUseCamera(
[arg0],
this.activity.turtles,
turtle,
false,
this.cameraID,
this.setCameraID,
this.activity.errorMsg
);
} else if (len === 13 && arg1.substr(0, 13) === VIDEOVALUE) {
doUseCamera(
[arg0],
this.activity.turtles,
turtle,
true,
this.cameraID,
this.setCameraID,
this.activity.errorMsg
);
} else if (len > 10 && arg1.substr(0, 10) === "data:image") {
this.activity.turtles.turtleList[turtle].doShowImage(arg0, arg1);
} else if (len > 8 && arg1.substr(0, 8) === "https://") {
this.activity.turtles.turtleList[turtle].doShowURL(arg0, arg1);
} else if (len > 7 && arg1.substr(0, 7) === "http://") {
this.activity.turtles.turtleList[turtle].doShowURL(arg0, arg1);
} else if (len > 7 && arg1.substr(0, 7) === "file://") {
this.activity.turtles.turtleList[turtle].doShowURL(arg0, arg1);
} else {
this.activity.turtles.turtleList[turtle].doShowText(arg0, arg1);
}
} else if (
typeof arg1 === "object" &&
blk !== null &&
this.blockList[this.blockList[blk].connections[2]]
.name === "loadFile"
) {
if (arg1) {
this.activity.turtles.turtleList[turtle].doShowText(arg0, arg1[1]);
} else {
this.activity.errorMsg(_("You must select a file."));
}
} else {
this.activity.turtles.turtleList[turtle].doShowText(arg0, arg1);
}
}
// ========================================================================
/**
* Sets the cameraID property.
*
* @param id
* @returns {void}
*/
setCameraID(id) {
this.cameraID = id;
}
// ========= Action ===========================================================================
/**
* Sets a named listener after removing any existing listener in the same place.
*
* @param {Number} turtle - Turtle index in turtles.turtleList
* @param {String} listenerName
* @param {Function} listener
* @returns {void}
*/
setTurtleListener(turtle, listenerName, listener) {
const tur = this.activity.turtles.ithTurtle(turtle);
if (listenerName in tur.listeners) {
this.activity.stage.removeEventListener(
listenerName,
tur.listeners[listenerName],
false
);
}
tur.listeners[listenerName] = listener;
this.activity.stage.addEventListener(listenerName, listener, false);
}
/**
* Sets a listener to the triggering (dispatch) block (usually the hidden block) for a clamp block.
*
* @param blk
* @param turtle
* @param {string} listenerName
* @returns {void}
*/
setDispatchBlock(blk, turtle, listenerName) {
const tur = this.activity.turtles.ithTurtle(turtle);
let nextBlock = null;
if (!tur.singer.inDuplicate && tur.singer.backward.length > 0) {
const c =
this.blockList[last(tur.singer.backward)].name === "backward"
? 1
: 2;
if (
this.activity.blocks.sameGeneration(
this.blockList[last(tur.singer.backward)].connections[c],
blk
)
) {
nextBlock = this.blockList[blk].connections[0];
} else {
nextBlock = last(this.blockList[blk].connections);
}
} else {
nextBlock = last(this.blockList[blk].connections);
}
if (nextBlock !== null) {
if (nextBlock in tur.endOfClampSignals) {
tur.endOfClampSignals[nextBlock].push(listenerName);
} else {
tur.endOfClampSignals[nextBlock] = [listenerName];
}
}
}
/**
* Parses receivedArg.
*
* @param logo
* @param turtle
* @param blk
* @param parentBlk
* @param receivedArg
* @returns {*}
*/
parseArg(logo, turtle, blk, parentBlk, receivedArg) {
const tur = logo.activity.turtles.ithTurtle(turtle);
// Retrieve the value of a block
if (blk == null) {
logo.activity.errorMsg(NOINPUTERRORMSG, parentBlk);
// logo.stopTurtle = true;
return null;
}
if (logo.blockList[blk].protoblock.parameter) {
if (tur.parameterQueue.indexOf(blk) === -1) {
tur.parameterQueue.push(blk);
}
}
if (typeof logo.blockList[blk].protoblock.arg === "function") {
return (logo.blockList[blk].value = logo.blockList[
blk
].protoblock.arg(logo, turtle, blk, receivedArg));
}
if (logo.blockList[blk].name === "intervalname") {
if (typeof logo.blockList[blk].value === "string") {
tur.singer.noteDirection = getIntervalDirection(
logo.blockList[blk].value
);
return getIntervalNumber(logo.blockList[blk].value);
} else return 0;
} else if (logo.blockList[blk].isValueBlock()) {
return logo.blockList[blk].value;
} else if (
["anyout", "numberout", "textout", "booleanout"].indexOf(
logo.blockList[blk].protoblock.dockTypes[0]
) !== -1
) {
switch (logo.blockList[blk].name) {
case "dectofrac":
if (
logo.inStatusMatrix &&
logo.blockList[
logo.blockList[blk].connections[0]
].name === "print"
) {
logo.statusFields.push([blk, "dectofrac"]);
} else {
const cblk = logo.blockList[blk].connections[1];
if (cblk === null) {
logo.activity.errorMsg(NOINPUTERRORMSG, blk);
logo.blockList[blk].value = 0;
} else {
const a = logo.parseArg(logo, turtle, cblk, blk, receivedArg);
if (typeof a === "number") {
logo.blockList[blk].value =
a < 0 ? "-" + mixedNumber(-a) : mixedNumber(a);
} else {
logo.activity.errorMsg(NANERRORMSG, blk);
logo.blockList[blk].value = 0;
}
}
}
break;
case "hue":
if (
logo.inStatusMatrix &&
logo.blockList[
logo.blockList[blk].connections[0]
].name === "print"
) {
logo.statusFields.push([blk, "color"]);
} else {
logo.blockList[blk].value =
logo.activity.turtles.turtleList[turtle].painter.color;
}
break;
/** @deprecated */
case "returnValue":
if (logo.returns[turtle].length > 0) {
logo.blockList[blk].value = logo.returns[turtle].pop();
} else {
logo.blockList[blk].value = 0;
}
break;
default:
// Is it a plugin?
if (logo.blockList[blk].name in logo.evalArgDict) {
// eslint-disable-next-line no-console
console.log("running eval on " + logo.blockList[blk].name);
eval(logo.evalArgDict[logo.blockList[blk].name]);
} else {
// eslint-disable-next-line no-console
console.error("I do not know how to " + logo.blockList[blk].name);
}
break;
}
return logo.blockList[blk].value;
} else {
return blk;
}
}
/**
* Updates the music notation used for Lilypond output.
*
* @param note
* @param {number} duration
* @param turtle
* @param insideChord
* @param drum
* @param {boolean} [split]
* @returns {void}
*/
updateNotation(note, duration, turtle, insideChord, drum, split) {
// Note: At this point, the note of duration "duration" has
// already been added to notesPlayed
// Don't split the note if we are already splitting the note
if (split == undefined) split = true;
const tur = this.activity.turtles.ithTurtle(turtle);
// Check to see if this note straddles a measure boundary
const durationTime = 1 / duration;
const beatsIntoMeasure =
((tur.singer.notesPlayed[0] / tur.singer.notesPlayed[1] -
tur.singer.pickup -
durationTime) *
tur.singer.noteValuePerBeat) %
tur.singer.beatsPerMeasure;
const timeIntoMeasure = beatsIntoMeasure / tur.singer.noteValuePerBeat;
const timeLeftInMeasure =
tur.singer.beatsPerMeasure / tur.singer.noteValuePerBeat - timeIntoMeasure;
if (split && durationTime > timeLeftInMeasure) {
const d = durationTime - timeLeftInMeasure;
let d2 = timeLeftInMeasure;
const b = tur.singer.beatsPerMeasure / tur.singer.noteValuePerBeat;
// console.debug("splitting note across measure boundary.");
const obj = rationalToFraction(d);
if (d2 > 0) {
// Check to see if the note straddles multiple measures
let i = 0;
while (d2 > b) {
++i;
d2 -= b;
}
let obj2 = rationalToFraction(d2);
if (obj2[0] !== 0) {
this.updateNotation(note, obj2[1] / obj2[0], turtle, insideChord, drum, false);
}
if (i > 0 || obj[0] > 0) {
if (note[0] !== "R") {
// Don't tie rests
this.notation.notationInsertTie(turtle);
this.notation.notationDrumStaging[turtle].push("tie");
}
obj2 = rationalToFraction(1 / b);
}
// Add any measures we straddled
while (i > 0) {
i -= 1;
if (obj2[0] !== 0) {
this.updateNotation(
note,
obj2[1] / obj2[0],
turtle,
insideChord,
drum,
false
);
}
if (obj[0] > 0) {
if (note[0] !== "R") {
// Don't tie rests
this.notation.notationInsertTie(turtle);
this.notation.notationDrumStaging[turtle].push("tie");
}
}
}
}
if (obj[0] > 0) {
if (obj[0] !== 0) {
this.updateNotation(note, obj[1] / obj[0], turtle, insideChord, drum, false);
}
}
} else {
// .. otherwise proceed as normal
this.notation.doUpdateNotation(...arguments);
}
}
// ========================================================================
/**
* Clears the delay timeout after a successful input, and runs from
* next block.
*
* @param {Object} turtle
* @returns {void}
*/
clearTurtleRun(turtle) {
const tur = this.activity.turtles.ithTurtle(turtle);
if (tur.delayTimeout !== null) {
clearTimeout(tur.delayTimeout);
tur.delayTimeout = null;
this.runFromBlockNow(
this,
turtle,
tur.delayParameters["blk"],
tur.delayParameters["flow"],
tur.delayParameters["arg"]
);
}
}
/**
* Breaks a loop.
*
* @param turtle - Turtle object
* @returns {void}
*/
doBreak(turtle) {
// Look for a parent loopBlock in queue and set its count to 1
let parentLoopBlock = null;
let loopBlkIdx = -1;
const queueLength = turtle.queue.length;
for (let i = queueLength - 1; i > -1; i--) {
if (
["forever", "repeat", "while", "until"].indexOf(
this.blockList[turtle.queue[i].blk].name
) !== -1
) {
// while or until
loopBlkIdx = turtle.queue[i].blk;
parentLoopBlock = this.blockList[loopBlkIdx];
// Flush the parent from the queue
turtle.queue.pop();
break;
} else if (
["forever", "repeat", "while", "until"].indexOf(
this.blockList[turtle.queue[i].parentBlk].name
) !== -1
) {
// repeat or forever
loopBlkIdx = turtle.queue[i].parentBlk;
parentLoopBlock = this.blockList[loopBlkIdx];
// Flush the parent from the queue
turtle.queue.pop();
break;
}
}
if (parentLoopBlock == null) {
// Flush the child flow
turtle.queue.pop();
return;
}
// For while and until, we need to add any childflow from the parent to the queue
if (parentLoopBlock.name === "while" || parentLoopBlock.name === "until") {
const childFlow = last(parentLoopBlock.connections);
if (childFlow != null) {
const queueBlock = new Queue(childFlow, 1, loopBlkIdx);
// We need to keep track of the parent block to the child flow so we can
// unlightlight the parent block after the child flow completes
turtle.parentFlowQueue.push(loopBlkIdx);
turtle.queue.push(queueBlock);
}
}
}
// ========= Behavior =========================================================================
/**
* Initialises a turtle.
*
* @param turtle
* @returns {void}
*/
initTurtle(turtle) {
this.connectionStore[turtle] = {};
this.connectionStoreLock = false;
this.switchCases[turtle] = {};
this.switchBlocks[turtle] = [];
this.returns[turtle] = [];
this.notation.notationStaging[turtle] = [];
this.notation.notationDrumStaging[turtle] = [];
this.notation.pickupPoint[turtle] = null;
this.notation.pickupPOW2[turtle] = false;
this.activity.turtles
.ithTurtle(turtle)
.initTurtle(this.runningLilypond || this.runningAbc || this.runningMxml);
}
/**
* Stops the turtles and cleans up a few odds and ends.
* The stop button was pressed.
*
* @returns {void}
*/
doStopTurtles() {
this.stopTurtle = true;
this.activity.turtles.markAllAsStopped();
for (const sound in this.sounds) {
this.sounds[sound].stop();
}
this.sounds = [];
for (const turtle in this.activity.turtles.turtleList) {
for (const instrumentName in instruments[turtle]) {
this.synth.stopSound(turtle, instrumentName);
}
const comp = this.activity.turtles.turtleList[turtle].companionTurtle;
if (comp) {
this.activity.turtles.turtleList[comp].running = false;
const interval = this.activity.turtles.turtleList[comp].interval;
if (interval) clearInterval(interval);
}
}
this.synth.stop();
if (this.synth.recorder && this.synth.recorder.state == "recording")
this.synth.recorder.stop();
if (this.cameraID != null) {
doStopVideoCam(this.cameraID, this.setCameraID);
}
this.onStopTurtle();
this.activity.blocks.bringToTop();
this.stepQueue = {};
for (const turtle of this.activity.turtles.turtleList) {
turtle.unhighlightQueue = [];
}
this._restoreConnections();
document.body.style.cursor = "default";
if (this.activity.showBlocksAfterRun) {
this.activity.blocks.showBlocks();
document.getElementById("stop").style.color = "white";
}
this.activity.showBlocksAfterRun = false;
}
/**
* Takes one step for each turtle in executing Logo commands.
*
* @returns {void}
*/
step() {
for (const turtle in this.stepQueue) {
if (this.stepQueue[turtle].length > 0) {
if (
turtle in this._unhighlightStepQueue &&
this._unhighlightStepQueue[turtle] != null
) {
if (this.activity.blocks.visible) {
this.activity.blocks.unhighlight(this._unhighlightStepQueue[turtle]);
}
this._unhighlightStepQueue[turtle] = null;
}
const blk = this.stepQueue[turtle].pop();
if (blk != null) {
this.runFromBlockNow(this, turtle, blk, 0, null);
}
}
}
}
/**
* Runs Logo commands.
*
* @param startHere - index of a block to start from
* @param env
* @returns {void}
*/
runLogoCommands(startHere, env) {
this._prematureRestart = this._alreadyRunning;
if (this._alreadyRunning && this._runningBlock !== null) {
this._ignoringBlock = this._runningBlock;
} else {
this._ignoringBlock = null;
}