-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
3407 lines (3304 loc) · 122 KB
/
Copy pathapp.js
File metadata and controls
3407 lines (3304 loc) · 122 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ============================================================================
PROPAGATOR (WebMIDI) — the cultivating surface for Spore
SPDX-License-Identifier: GPL-3.0-or-later
Copyright (C) 2026 Joakim Langkilde
The CC map is the contract with the firmware (see daisy repo
docs/MIDI_PROTOCOL.md). Edit CONFIG to extend.
========================================================================== */
'use strict';
const CONFIG = {
channel: 0, // MIDI channel (0-based)
ccMode: [20, 21, 22, 23, 24, 25], // MODE-layer knobs 1..6
ccFx: [26, 27, 28, 29, 30, 31], // FX-layer knobs 1..6
ccModeSelect: 16, // mode select (0/64/127 -> synth/granular/generative)
ccFxSelect: 17, // FX select (0/64/127 -> off/delay/reverb)
ccTempo: 14, // internal clock BPM (0..1 -> 40..200)
ccDelaySync: 15, // delay tempo-sync division (0 off / ¼ / ⅛ / ⅛. / 16)
ccDaisyReboot: 118, // CC 118 >=64 -> reboot into the Daisy bootloader (reflash the app, QSPI)
ccSysReboot: 119, // CC 119 >=64 -> reboot into the STM ROM DFU (reflash the bootloader itself)
ccChaos: [18], // CC 18 -> Lorenz chaos speed (single-knob "bank")
ccVar: 93, // CC 93 -> VAR / Toggle 2 (thirds: 0 / 1 / 2)
ccFs1: 91, // CC 91 >=64 -> bypass on, <64 -> engaged
ccFs2: 92, // CC 92 >=64 -> mode action (freeze / re-seed)
ccMasterFilt: 88, // CC 88 -> master filter type (0 off / 1 LP / 2 BP / 3 HP)
ccMaster: [7, 89, 90], // master "bank": [volume(CC7) · cutoff(CC89) · res(CC90)]
ccGen: [32, 33, 34, 35, 36, 37], // GENERATIVE pod bank: chord·swell·motion·bright·texture·wander
ccGran: [94, 95, 96, 97], // GRANULAR pod bank: reverse·width·shape·scale
ccSynth: [
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,
], // 0-7 voice · 8 wave · 9-12 LFO · 13 voices · 14-19 wavetable · 20-24 tone · 25-26 LFO2 · 27-44 matrix · 45 LFO2 depth · 46 LFO1 sync · 47 LFO2 sync
synthLabels: [
'Detune',
'Sub',
'Sustain',
'Release',
'F.Env Amt',
'F.Env Time',
'Glide',
'Width',
],
modeOrder: ['synth', 'granular', 'generative'], // toggle 1: up / middle / down
modeLabels: {
synth: ['Cutoff', 'Resonance', 'Attack', 'Decay', 'Mod Depth', 'Gen-mod Mix'],
granular: ['Grain Size', 'Density', 'Pitch', 'Pitch Spread', 'Scatter', 'Dry/Wet'],
generative: ['Tempo', 'Range', 'Tone', 'Reverb', 'Density', 'Drift'],
},
modeNotes: {
synth: 'osc → moog filter → envelope · USB MIDI',
granular: 'records input → grains · footswitch freeze',
generative: 'ambient pad · self-playing · slow tempo · big reverb',
},
fxLabels: ['Mix', 'Delay Time', 'Feedback', 'Tone', 'Reverb Decay', 'Reverb Damp'],
fxOrder: ['Off', 'Delay', 'Reverb'],
toggle2Labels: ['Wave A', 'Wave B', 'Wave C'],
// Footswitch 2 action per mode (Footswitch 1 is always bypass/engage).
fsActions: { synth: 'SUSTAIN', granular: 'FREEZE', generative: 'RE-SEED' },
};
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
/* ---------- DOM ---------- */
const $ = (s, r = document) => r.querySelector(s);
const el = (tag, cls) => {
const e = document.createElement(tag);
if (cls) e.className = cls;
return e;
};
const stage = $('#stage');
const annot = $('#annot');
const knobsRow = $('#knobs');
const fxKnobsEl = $('#fxKnobs');
const togglesEl = $('#toggles');
const stompsEl = $('#stomps');
const midiAct = $('#midiAct'),
midiLast = $('#midiLast');
/* ---------- MIDI state ---------- */
let midi = null,
midiOut = null,
midiIn = null;
let sporeIn = null; // Spore's own MIDI input (telemetry), independent of the performance input
let thru = true; // forward IN-device messages to Spore (OUT)
let latestFw = null; // {version,size,file} from ./firmware/latest.json
let connectedFw = null; // version string from Spore's SysEx identify reply
let clockMaster = 'off'; // tempo master: 'off' | 'gui' | 'in'
let delaySyncIdx = 0; // delay tempo-sync division (part of a patch/preset)
// clock forwarding off by default; the UI's beat sync reads clock locally
const thruFilter = { notes: true, cc: true, other: true, clock: false };
let clockSync = true; // derive BPM + beat from incoming MIDI clock
let clockCount = 0,
lastClockMs = 0,
clockBpm = 0; // MIDI clock tracking (24 PPQN)
let activeMode = 0; // 0 synth / 1 granular / 2 generative
let activeFx = 0; // 0 off / 1 delay / 2 reverb
const knobValue = {
mode: [0.5, 0.5, 0.5, 0.5, 0.5, 0.5],
fx: [0.3, 0.4, 0.35, 0.7, 0.6, 0.7],
// 0-7 voice · 8 wave · 9 LFO rate · 10 LFO depth · 11 LFO shape · 12 LFO dest · 13 voices(0.6->4)
// 14 engine(0=analog) · 15 wt scan · 16 FM amt · 17 FM ratio · 18 fold · 19 wt bank
// 20 drive · 21 filter(0=Svf) · 22 unison(0.33->2) · 23 sub oct · 24 sub wave
// 25 LFO2 rate · 26 LFO2 shape · 27-44 mod matrix (6 slots: src/dst/amt)
synth: [
0.25, 0.4, 0.7, 0.3, 0.5, 0.3, 0.0, 0.6, 0.66, 0.3, 0.0, 0.0, 0.33, 0.6, 0.0, 0.3, 0.0,
0.25, 0.0, 0.0, 0.0, 0.0, 0.33, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.5, 0.0, 0.0,
0.5, 0.0, 0.0, 0.5, 0.0, 0.0, 0.5, 0.0, 0.0, 0.5, 1.0, 0.0, 0.0,
],
chaos: [0.15], // Lorenz speed (0..1 -> CC 18); 0.15 ~= the firmware default 2.0
master: [1.0, 1.0, 0.0], // master out: [volume · filter cutoff · resonance]
gen: [0.4, 0.5, 0.45, 0.5, 0.5, 0.35], // generative: chord·swell·motion·bright·texture·wander
gran: [0.3, 0.0, 0.0, 0.0], // granular: reverse·width·shape·scale (defaults = stock sound)
};
let activeVar = 0; // VAR / Toggle 2 position (0/1/2), part of a patch
let activeMasterFilt = 0; // master filter type: 0 off / 1 LP / 2 BP / 3 HP
let applyingRemote = false; // true while mirroring incoming CC -> UI (suppresses re-send)
// pristine defaults, captured before any preset/autosave restore — used by "new"
const KNOB_DEFAULTS = {
mode: knobValue.mode.slice(),
fx: knobValue.fx.slice(),
synth: knobValue.synth.slice(),
chaos: knobValue.chaos.slice(),
master: knobValue.master.slice(),
gen: knobValue.gen.slice(),
gran: knobValue.gran.slice(),
};
/* ===========================================================================
KNOBS
========================================================================= */
let envRedraw = () => {}; // set by the envelope pod; lets knob edits redraw the ADSR graph
function makeKnob(bank, idx, label) {
const k = el('div', 'knob');
k.dataset.bank = bank;
k.dataset.idx = idx;
const dial = el('div', 'knob-dial');
const ptr = el('span', 'knob-pointer');
dial.appendChild(ptr);
const lab = el('div', 'knob-label');
lab.textContent = label;
const val = el('div', 'knob-val');
k.append(dial, lab, val);
const apply = () => {
const v = knobValue[bank][idx];
dial.style.setProperty('--rot', rotFor(v) + 'deg');
val.textContent = String(Math.round(v * 127)).padStart(3, '0');
};
apply();
attachKnobDrag(k, dial, bank, idx, apply, lab);
k._apply = apply;
k._label = lab;
return k;
}
function attachKnobDrag(k, dial, bank, idx, apply, lab) {
let startY = 0,
startV = 0,
dragging = false;
const cc = (
bank === 'mode'
? CONFIG.ccMode
: bank === 'fx'
? CONFIG.ccFx
: bank === 'chaos'
? CONFIG.ccChaos
: bank === 'master'
? CONFIG.ccMaster
: bank === 'gen'
? CONFIG.ccGen
: bank === 'gran'
? CONFIG.ccGran
: CONFIG.ccSynth
)[idx];
const showAnnot = (e) => {
annot.hidden = false;
annot.innerHTML = `<b>${lab.textContent}</b><br><span class="cc">CC ${cc}</span> · ${Math.round(knobValue[bank][idx] * 127)}/127`;
annot.style.left = e.clientX + 'px';
annot.style.top = e.clientY + 'px';
};
dial.addEventListener('pointerdown', (e) => {
dragging = true;
startY = e.clientY;
startV = knobValue[bank][idx];
k.classList.add('grabbing');
dial.setPointerCapture(e.pointerId);
showAnnot(e);
e.preventDefault();
});
dial.addEventListener('pointermove', (e) => {
if (dragging) {
const dv = (startY - e.clientY) / 200;
knobValue[bank][idx] = Math.max(0, Math.min(1, startV + dv));
apply();
sendCC(cc, knobValue[bank][idx]);
showAnnot(e);
envRedraw();
} else if (e.buttons === 0) {
showAnnot(e);
}
});
const end = (e) => {
if (!dragging) return;
dragging = false;
k.classList.remove('grabbing');
try {
dial.releasePointerCapture(e.pointerId);
} catch (_) {}
};
dial.addEventListener('pointerup', end);
dial.addEventListener('pointercancel', end);
dial.addEventListener('pointerleave', () => {
if (!dragging) annot.hidden = true;
});
// double-click resets to centre
dial.addEventListener('dblclick', () => {
knobValue[bank][idx] = 0.5;
apply();
sendCC(cc, 0.5);
envRedraw();
});
// wheel fine-tune
dial.addEventListener(
'wheel',
(e) => {
e.preventDefault();
knobValue[bank][idx] = Math.max(
0,
Math.min(1, knobValue[bank][idx] - Math.sign(e.deltaY) * 0.02),
);
apply();
sendCC(cc, knobValue[bank][idx]);
envRedraw();
},
{ passive: false },
);
}
/* build mode knobs */
const modeKnobs = CONFIG.modeLabels[CONFIG.modeOrder[0]].map((lab, i) => makeKnob('mode', i, lab));
modeKnobs.forEach((k) => knobsRow.appendChild(k));
/* build fx knobs */
CONFIG.fxLabels.forEach((lab, i) => fxKnobsEl.appendChild(makeKnob('fx', i, lab)));
/* build synth-panel knobs — VOICE pod keeps the timbre params; the envelope
params (Sustain/Release + filter env) are broken out into the ENV pod below */
const synthKnobsEl = $('#synthKnobs');
const VOICE_KNOBS = [0, 1, 6, 7]; // Detune, Sub, Glide, Width
VOICE_KNOBS.forEach((i) => synthKnobsEl.appendChild(makeKnob('synth', i, CONFIG.synthLabels[i])));
synthKnobsEl.appendChild(makeKnob('synth', 20, 'Drive')); // pre-filter saturation (grit)
/* waveform selector -> synth CC */
$('#synthWaveSeg').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const w = +b.dataset.w,
idx = 8; // SP_WAVE
document
.querySelectorAll('#synthWaveSeg button')
.forEach((x) => x.classList.toggle('on', +x.dataset.w === w));
knobValue.synth[idx] = w / 3;
sendCC(CONFIG.ccSynth[idx], w / 3);
});
/* voices selector -> SP_VOICES (idx 13): 1..6 voices map to (v-1)/5 */
$('#voiceSeg').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const v = +b.dataset.v; // 1..6
document
.querySelectorAll('#voiceSeg button')
.forEach((x) => x.classList.toggle('on', +x.dataset.v === v));
knobValue.synth[13] = (v - 1) / 5;
sendCC(CONFIG.ccSynth[13], (v - 1) / 5);
});
/* filter type -> SP_FILTER (idx 21): 0 = clean Svf, 1 = fat Moog */
$('#synthFilterSeg').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const f = +b.dataset.f;
document
.querySelectorAll('#synthFilterSeg button')
.forEach((x) => x.classList.toggle('on', +x.dataset.f === f));
knobValue.synth[21] = f;
sendCC(CONFIG.ccSynth[21], f);
envRedraw(); // redraw the synth filter curve (Svf 2-pole <-> Moog 4-pole)
});
/* unison -> SP_UNISON (idx 22): 1..4 osc map to (u-1)/3 */
$('#synthUniSeg').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const u = +b.dataset.u;
document
.querySelectorAll('#synthUniSeg button')
.forEach((x) => x.classList.toggle('on', +x.dataset.u === u));
knobValue.synth[22] = (u - 1) / 3;
sendCC(CONFIG.ccSynth[22], (u - 1) / 3);
});
/* sub octave -> SP_SUB_OCT (idx 23): 0 = -1, 1 = -2 */
$('#subOctSeg').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const o = +b.dataset.o;
document
.querySelectorAll('#subOctSeg button')
.forEach((x) => x.classList.toggle('on', +x.dataset.o === o));
knobValue.synth[23] = o;
sendCC(CONFIG.ccSynth[23], o);
});
/* sub waveform -> SP_SUB_WAVE (idx 24): 0 = square, 1 = sine */
$('#subWaveSeg').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const w = +b.dataset.w;
document
.querySelectorAll('#subWaveSeg button')
.forEach((x) => x.classList.toggle('on', +x.dataset.w === w));
knobValue.synth[24] = w;
sendCC(CONFIG.ccSynth[24], w);
});
/* MOD / LFO pod: rate + depth knobs, shape + destination selectors */
const modKnobsEl = $('#modKnobs');
modKnobsEl.appendChild(makeKnob('synth', 9, 'LFO Rate'));
modKnobsEl.appendChild(makeKnob('synth', 10, 'Depth'));
$('#lfoShapeSeg').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const w = +b.dataset.w; // SP_LFO_SHAPE -> idx 11
document
.querySelectorAll('#lfoShapeSeg button')
.forEach((x) => x.classList.toggle('on', +x.dataset.w === w));
knobValue.synth[11] = w / 3;
sendCC(CONFIG.ccSynth[11], w / 3);
});
/* ===========================================================================
ENVELOPE pod — an interactive ADSR graph that edits the amp envelope spread
across the knob banks: Attack = mode CC, Decay = mode CC, Sustain/Release =
synth CC. Dragging the handles drives those params (and the dials stay in
sync via refreshKnobs). Filter-env amount/time live here as two knobs.
========================================================================= */
const ENV = { X0: 10, AW: 62, DW: 62, SUS: 34, RW: 62, TOP: 8, BOT: 84, VBW: 236, VBH: 92 };
ENV.H = ENV.BOT - ENV.TOP;
const NSVG = 'http://www.w3.org/2000/svg';
const envHost = $('#envGraph');
let envSvg = null,
envFill = null,
envLine = null,
envHA = null,
envHS = null,
envHR = null;
// Attack/Decay are the synth-mode MODE knobs 3/4; Sustain/Release are synth params.
function envGet() {
return {
A: knobValue.mode[2],
D: knobValue.mode[3],
S: knobValue.synth[2],
R: knobValue.synth[3],
};
}
function envSet(bank, idx, v) {
knobValue[bank][idx] = clamp01(v);
sendCC((bank === 'mode' ? CONFIG.ccMode : CONFIG.ccSynth)[idx], knobValue[bank][idx]);
}
function drawEnv() {
if (!envSvg) {
buildEnv();
if (!envSvg) return;
} // build on first draw
const { A, D, S, R } = envGet();
const peakX = ENV.X0 + A * ENV.AW;
const susStartX = peakX + D * ENV.DW;
const ySus = ENV.BOT - S * ENV.H;
const susEndX = susStartX + ENV.SUS;
const endX = susEndX + R * ENV.RW;
const d = `M ${ENV.X0} ${ENV.BOT} L ${peakX.toFixed(1)} ${ENV.TOP} L ${susStartX.toFixed(1)} ${ySus.toFixed(1)} L ${susEndX.toFixed(1)} ${ySus.toFixed(1)} L ${endX.toFixed(1)} ${ENV.BOT}`;
envLine.setAttribute('d', d);
envFill.setAttribute('d', d + ` L ${ENV.X0} ${ENV.BOT} Z`);
envHA.setAttribute('cx', peakX.toFixed(1));
envHA.setAttribute('cy', ENV.TOP);
envHS.setAttribute('cx', susStartX.toFixed(1));
envHS.setAttribute('cy', ySus.toFixed(1));
envHR.setAttribute('cx', endX.toFixed(1));
envHR.setAttribute('cy', ENV.BOT);
}
function envPoint(e) {
const r = envSvg.getBoundingClientRect();
return {
x: ((e.clientX - r.left) / r.width) * ENV.VBW,
y: ((e.clientY - r.top) / r.height) * ENV.VBH,
};
}
function envDrag(handle, onMove) {
handle.addEventListener('pointerdown', (e) => {
e.preventDefault();
e.stopPropagation();
const mv = (ev) => {
onMove(envPoint(ev));
drawEnv();
refreshKnobs();
};
const up = () => {
window.removeEventListener('pointermove', mv);
window.removeEventListener('pointerup', up);
window.removeEventListener('pointercancel', up);
};
window.addEventListener('pointermove', mv);
window.addEventListener('pointerup', up);
window.addEventListener('pointercancel', up);
mv(e);
});
}
function buildEnv() {
if (!envHost || envSvg) return; // build once; idempotent for the lazy path
envSvg = document.createElementNS(NSVG, 'svg');
envSvg.setAttribute('viewBox', `0 0 ${ENV.VBW} ${ENV.VBH}`);
envSvg.setAttribute('class', 'env-svg');
const base = document.createElementNS(NSVG, 'line'); // baseline
base.setAttribute('x1', ENV.X0);
base.setAttribute('y1', ENV.BOT);
base.setAttribute('x2', ENV.VBW - 2);
base.setAttribute('y2', ENV.BOT);
base.setAttribute('class', 'env-base');
envFill = document.createElementNS(NSVG, 'path');
envFill.setAttribute('class', 'env-fill');
envLine = document.createElementNS(NSVG, 'path');
envLine.setAttribute('class', 'env-line');
const mkH = (cls) => {
const c = document.createElementNS(NSVG, 'circle');
c.setAttribute('r', '7');
c.setAttribute('class', 'env-handle ' + cls);
return c;
};
envHA = mkH('hA');
envHS = mkH('hS');
envHR = mkH('hR');
envSvg.append(base, envFill, envLine, envHA, envHS, envHR);
envHost.appendChild(envSvg);
envDrag(envHA, (p) => envSet('mode', 2, (p.x - ENV.X0) / ENV.AW)); // attack: x
envDrag(envHS, (p) => {
// decay+sustain
const peakX = ENV.X0 + knobValue.mode[2] * ENV.AW;
envSet('mode', 3, (p.x - peakX) / ENV.DW); // decay: x
envSet('synth', 2, (ENV.BOT - p.y) / ENV.H); // sustain: y
});
envDrag(envHR, (p) => {
// release: x
const relStart = ENV.X0 + knobValue.mode[2] * ENV.AW + knobValue.mode[3] * ENV.DW + ENV.SUS;
envSet('synth', 3, (p.x - relStart) / ENV.RW);
});
}
buildEnv();
/* filter-env knobs (broken out of the voice pod) */
const envFilterEl = $('#envFilter');
if (envFilterEl)
[4, 5].forEach((i) => envFilterEl.appendChild(makeKnob('synth', i, CONFIG.synthLabels[i])));
/* ---- filter response curves (master output + synth filter-env "pluck") ---- */
// Idealised state-variable magnitude over a 20Hz-20kHz log axis. type: 0 off/flat,
// 1 LP, 2 BP, 3 HP. poles 2 or 4 (4 = steeper, drawn as the 2-pole response squared).
function drawFilterCurve(canvas, type, fc01, q01, fmin, fmax, opts) {
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const W = canvas.width,
H = canvas.height,
pad = 4;
ctx.clearRect(0, 0, W, H);
const fLo = 20,
fHi = 20000;
const fc = fmin * Math.pow(fmax / fmin, fc01); // cutoff (knob 0..1 -> Hz, exp)
const Q = 0.5 + q01 * 9.0; // resonance -> Q (visual)
const poles = (opts && opts.poles) || 2;
const ghost = opts && opts.ghost; // dim "no-filter" look when off
const dB = (f) => {
if (type === 0) return 0; // off -> flat
const w = f / fc;
const d = Math.sqrt((1 - w * w) * (1 - w * w) + (w / Q) * (w / Q));
let m = type === 1 ? 1 / d : type === 3 ? (w * w) / d : w / Q / d; // LP / HP / BP
if (poles >= 4) m *= m; // cascade ~ 4-pole
return 20 * Math.log10(Math.max(m, 1e-4));
};
const y = (db) => pad + (1 - (Math.max(-36, Math.min(18, db)) + 36) / 54) * (H - 2 * pad);
// 0 dB grid line
ctx.strokeStyle = 'rgba(91,208,230,.15)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(pad, y(0));
ctx.lineTo(W - pad, y(0));
ctx.stroke();
// the curve (canvas can't read CSS vars, so resolve --mode to a real colour)
const accent = getComputedStyle(document.body).getPropertyValue('--mode').trim() || '#3fb56b';
ctx.strokeStyle = ghost ? 'rgba(120,150,170,.45)' : accent;
ctx.lineWidth = 2;
ctx.beginPath();
for (let px = pad; px <= W - pad; px++) {
const f = fLo * Math.pow(fHi / fLo, (px - pad) / (W - 2 * pad));
const yy = y(dB(f));
if (px === pad) ctx.moveTo(px, yy);
else ctx.lineTo(px, yy);
}
ctx.stroke();
}
function drawMasterFilt() {
const c = $('#masterFiltViz');
if (!c) return;
drawFilterCurve(c, activeMasterFilt, knobValue.master[1], knobValue.master[2], 40, 18000, {
poles: 2,
ghost: activeMasterFilt === 0,
});
drawFreqCursor(c);
}
function drawSynthFilt() {
const c = $('#synthFiltViz');
if (!c) return;
// synth voice filter: cutoff = mode knob 1, res = mode knob 2, poles from SP_FILTER (21)
const cut = knobValue.mode[0],
res = knobValue.mode[1];
const poles = knobValue.synth[21] >= 0.5 ? 4 : 2; // Svf 2-pole | Moog 4-pole
const ctx = c.getContext('2d');
if (ctx) ctx.clearRect(0, 0, c.width, c.height);
// faint "pluck peak" curve: the filter-env (SP_FENV_AMT, idx 4) sweeps cutoff up
const peak = Math.min(1, cut + knobValue.synth[4] * 0.45);
drawFilterCurve(c, 1, peak, res, 40, 12000, { poles, ghost: true });
// draw the base curve on top (same canvas; drawFilterCurve clears, so layer manually)
drawFilterCurveOver(c, 1, cut, res, 40, 12000, poles);
drawFreqCursor(c);
}
// Hover read-out: a vertical line + estimated frequency at the mouse x (set by the
// mousemove handler). Same 20Hz-20kHz log axis the curves use.
function drawFreqCursor(canvas) {
const hx = canvas._hoverX;
if (hx == null) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const W = canvas.width,
H = canvas.height,
pad = 4,
fLo = 20,
fHi = 20000;
const frac = Math.max(0, Math.min(1, (hx - pad) / (W - 2 * pad)));
const f = fLo * Math.pow(fHi / fLo, frac);
ctx.strokeStyle = 'rgba(150,200,220,.55)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(hx, pad);
ctx.lineTo(hx, H - pad);
ctx.stroke();
const txt = f >= 1000 ? (f / 1000).toFixed(f >= 10000 ? 0 : 1) + ' kHz' : Math.round(f) + ' Hz';
ctx.font = '9px ui-monospace, monospace';
ctx.fillStyle = '#cfeaf2';
const tw = ctx.measureText(txt).width;
ctx.fillText(txt, hx + 5 + tw > W ? hx - 5 - tw : hx + 5, 11);
}
// draw a curve onto a canvas WITHOUT clearing (for layering base over the ghost peak)
function drawFilterCurveOver(canvas, type, fc01, q01, fmin, fmax, poles) {
const ctx = canvas.getContext('2d');
if (!ctx) return;
const W = canvas.width,
H = canvas.height,
pad = 4,
fLo = 20,
fHi = 20000;
const fc = fmin * Math.pow(fmax / fmin, fc01),
Q = 0.5 + q01 * 9.0;
const y = (db) => pad + (1 - (Math.max(-36, Math.min(18, db)) + 36) / 54) * (H - 2 * pad);
ctx.strokeStyle =
getComputedStyle(document.body).getPropertyValue('--mode').trim() || '#3fb56b';
ctx.lineWidth = 2;
ctx.beginPath();
for (let px = pad; px <= W - pad; px++) {
const f = fLo * Math.pow(fHi / fLo, (px - pad) / (W - 2 * pad));
const w = f / fc,
d = Math.sqrt((1 - w * w) * (1 - w * w) + (w / Q) * (w / Q));
let m = 1 / d;
if (poles >= 4) m *= m;
const yy = y(20 * Math.log10(Math.max(m, 1e-4)));
if (px === pad) ctx.moveTo(px, yy);
else ctx.lineTo(px, yy);
}
ctx.stroke();
}
function redrawGraphs() {
drawEnv();
drawMasterFilt();
drawSynthFilt();
}
envRedraw = redrawGraphs; // knob edits (and applyPatch) refresh ADSR + both filter curves
redrawGraphs();
// hover read-out of the estimated frequency on each filter curve
[
['#masterFiltViz', drawMasterFilt],
['#synthFiltViz', drawSynthFilt],
].forEach(([sel, fn]) => {
const c = $(sel);
if (!c) return;
c.addEventListener('mousemove', (e) => {
const r = c.getBoundingClientRect();
c._hoverX = ((e.clientX - r.left) / r.width) * c.width; // CSS px -> canvas px
fn();
});
c.addEventListener('mouseleave', () => {
c._hoverX = null;
fn();
});
});
/* ===========================================================================
WAVE / DIGITAL pod — selects the voice engine (analog vs wavetable) and the
digital params: wavetable scan position, FM amount + ratio, wavefold.
========================================================================= */
$('#waveEngineSeg').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const en = +b.dataset.e; // 0 = analog, 1 = wavetable
document
.querySelectorAll('#waveEngineSeg button')
.forEach((x) => x.classList.toggle('on', +x.dataset.e === en));
knobValue.synth[14] = en;
sendCC(CONFIG.ccSynth[14], en);
updateEngineUI();
});
// show only the controls that apply to the chosen engine
function showEl(sel, show) {
const e = $(sel);
if (e) e.style.display = show ? '' : 'none';
}
function updateEngineUI() {
const wt = knobValue.synth[14] >= 0.5; // wavetable engine?
showEl('#wtControls', wt); // table / scan / FM / fold
showEl('#oscWaveRow', !wt); // analog waveform selector
showEl('#unisonRow', !wt); // unison is analog-only
const note = $('#waveNote');
if (note)
note.textContent = wt
? 'wavetable scan (sine→bright) · FM (carrier × ratio) · wavefold · sub for body'
: 'analog: 2–4 detuned oscillators (super-saw via UNISON) + sub';
}
const waveKnobsEl = $('#waveKnobs');
if (waveKnobsEl) {
waveKnobsEl.appendChild(makeKnob('synth', 15, 'Scan')); // wavetable position
waveKnobsEl.appendChild(makeKnob('synth', 16, 'FM')); // FM depth
waveKnobsEl.appendChild(makeKnob('synth', 18, 'Fold')); // wavefold
}
$('#waveRatioSeg').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const r = +b.dataset.r; // 0..3 -> {0.5, 1, 2, 3}
document
.querySelectorAll('#waveRatioSeg button')
.forEach((x) => x.classList.toggle('on', +x.dataset.r === r));
knobValue.synth[17] = r / 3;
sendCC(CONFIG.ccSynth[17], r / 3);
});
/* wavetable bank (idx 19): 5 banks map to b/4 */
$('#waveBankSeg').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const w = +b.dataset.b; // 0..4 -> Saw / Square / Organ / Vocal / Digital
document
.querySelectorAll('#waveBankSeg button')
.forEach((x) => x.classList.toggle('on', +x.dataset.b === w));
knobValue.synth[19] = w / 4;
sendCC(CONFIG.ccSynth[19], w / 4);
});
/* ===========================================================================
MOD MATRIX pod — LFO2 + 3 routing slots (source -> destination -> amount).
========================================================================= */
const MOD_SRC = ['Off', 'LFO1', 'LFO2', 'Rnd', 'Sens', 'Vel', 'Key', 'Chaos', 'Steps']; // -> synth param * 8
const MOD_DST = ['Cutoff', 'Pitch', 'Scan', 'Drive', 'Sub', 'FM', 'Amp', 'LFO1 Hz', 'LFO2 Hz']; // -> param * 8
// hover explanations (index aligns with MOD_SRC.slice(1) and MOD_DST)
const PATCH_SRC_TIP = [
'LFO1 — first low-frequency oscillator (rate/shape above)',
'LFO2 — second LFO (its own rate/shape/depth)',
'Rnd — random / sample-and-hold wobble from the hardware RNG',
'Sens — the analog sensor input (light/pressure)',
'Vel — note velocity, per voice (MIDI notes or the sequencer)',
'Key — note pitch / key-track, per voice (centred on middle C)',
'Chaos — Lorenz attractor: smooth, deterministic-but-never-repeating drift',
'Steps — logistic-map chaos: stepped (sample & hold) with hidden structure',
];
const PATCH_DST_TIP = [
'Cutoff — filter frequency (sweeps/wah)',
'Pitch — oscillator pitch (vibrato when subtle)',
'Scan — wavetable scan position (timbre morph)',
'Drive — pre-filter saturation amount (grit)',
'Sub — sub-oscillator level',
'FM — FM amount (wavetable engine)',
'Amp — output level (tremolo)',
'LFO1 Hz — LFO1 rate (modulate one LFO with another)',
'LFO2 Hz — LFO2 rate',
];
const lfo2KnobsEl = $('#lfo2Knobs');
if (lfo2KnobsEl) {
lfo2KnobsEl.appendChild(makeKnob('synth', 25, 'LFO2 Rate'));
lfo2KnobsEl.appendChild(makeKnob('synth', 45, 'Depth')); // master depth for LFO2
}
const chaosKnobsEl = $('#chaosKnobs');
if (chaosKnobsEl) chaosKnobsEl.appendChild(makeKnob('chaos', 0, 'Speed')); // CC 18 -> Lorenz speed
const masterKnobsEl = $('#masterKnobs');
if (masterKnobsEl) {
masterKnobsEl.appendChild(makeKnob('master', 0, 'Volume')); // CC 7
masterKnobsEl.appendChild(makeKnob('master', 1, 'Cutoff')); // CC 89
masterKnobsEl.appendChild(makeKnob('master', 2, 'Res')); // CC 90
}
const masterFiltSeg = $('#masterFiltSeg');
if (masterFiltSeg)
masterFiltSeg.addEventListener('click', (e) => {
const b = e.target.closest('button');
if (b) setMasterFilt(+b.dataset.t); // CC 88
});
const genKnobsEl = $('#genKnobs');
if (genKnobsEl)
['Chord', 'Swell', 'Motion', 'Bright', 'Texture', 'Wander'].forEach((lbl, i) =>
genKnobsEl.appendChild(makeKnob('gen', i, lbl)),
); // CC 32-37
const granKnobsEl = $('#granKnobs');
if (granKnobsEl)
['Reverse', 'Width', 'Shape', 'Scale'].forEach((lbl, i) =>
granKnobsEl.appendChild(makeKnob('gran', i, lbl)),
); // CC 94-97
$('#lfo2ShapeSeg').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const w = +b.dataset.w; // SP_LFO2_SHAPE -> idx 26
document
.querySelectorAll('#lfo2ShapeSeg button')
.forEach((x) => x.classList.toggle('on', +x.dataset.w === w));
knobValue.synth[26] = w / 3;
sendCC(CONFIG.ccSynth[26], w / 3);
});
/* LFO clock-sync selectors (free Hz vs locked division) */
function wireLfoSync(sel, idx) {
$(sel).addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const s = +b.dataset.s;
document
.querySelectorAll(sel + ' button')
.forEach((x) => x.classList.toggle('on', +x.dataset.s === s));
knobValue.synth[idx] = s / 5;
sendCC(CONFIG.ccSynth[idx], s / 5);
updateLfoSyncUI();
});
}
wireLfoSync('#lfo1SyncSeg', 46);
wireLfoSync('#lfo2SyncSeg', 47);
// when an LFO is clock-synced, its free-rate knob does nothing -> dim it
function updateLfoSyncUI() {
const dim = (idx, synced) => {
const k = document.querySelector('.knob[data-bank="synth"][data-idx="' + idx + '"]');
if (k) k.classList.toggle('knob-off', synced);
};
dim(9, knobValue.synth[46] > 0.05); // LFO1 rate
dim(25, knobValue.synth[47] > 0.05); // LFO2 rate
}
updateLfoSyncUI();
/* ---- PATCHBAY: a silkscreen-on-metal patch field. Source pads (left) and
destination pads (right) are white silkscreen labels; faint guide lines show
every possible connection. Drag from a source pad to a destination pad to lay
a cable (= one of the 6 matrix slots). Many cables can share a source or a
destination; Spore sums per destination. ---- */
const NSV = 'http://www.w3.org/2000/svg';
const elNS = (n) => document.createElementNS(NSV, n);
const PATCH_SLOTS = [27, 30, 33, 36, 39, 42]; // synth idx of each slot's SRC (DST=+1, AMT=+2)
const PB_W = 300,
PB_H = 176;
const PB_SPIN = 66,
PB_DPIN = PB_W - 66; // source / dest jack centres (cable anchors)
const SRCY = [14, 35, 55, 76, 96, 117, 137, 158]; // 8 source jacks (LFO1/2/Rnd/Sens/Vel/Key/Chaos/Steps)
const DSTY = [14, 32, 50, 68, 86, 104, 122, 140, 158]; // 9 destination jacks
let patchSvg = null,
patchSel = -1,
patchKnobApply = null;
function slotGet(i) {
const b = PATCH_SLOTS[i];
return {
src: Math.round(knobValue.synth[b] * 8),
dst: Math.round(knobValue.synth[b + 1] * 8),
amt: knobValue.synth[b + 2],
};
}
function slotSet(i, src, dst, amt) {
const b = PATCH_SLOTS[i];
if (src != null) {
knobValue.synth[b] = src / 8;
sendCC(CONFIG.ccSynth[b], src / 8);
}
if (dst != null) {
knobValue.synth[b + 1] = dst / 8;
sendCC(CONFIG.ccSynth[b + 1], dst / 8);
}
if (amt != null) {
knobValue.synth[b + 2] = amt;
sendCC(CONFIG.ccSynth[b + 2], amt);
}
}
function freeSlot() {
for (let i = 0; i < 6; i++) if (slotGet(i).src === 0) return i;
return -1;
}
// find an existing cable for this exact source+destination (src is 1-based, dst 0-based)
function findSlot(src, dst) {
for (let i = 0; i < 6; i++) {
const s = slotGet(i);
if (s.src === src && s.dst === dst) return i;
}
return -1;
}
function svgPt(e) {
const r = patchSvg.getBoundingClientRect();
return {
x: ((e.clientX - r.left) / r.width) * PB_W,
y: ((e.clientY - r.top) / r.height) * PB_H,
};
}
function buildPatch() {
const host = $('#patchbay');
if (!host) return;
patchSvg = elNS('svg');
patchSvg.setAttribute('viewBox', `0 0 ${PB_W} ${PB_H}`);
patchSvg.setAttribute('class', 'patch-svg');
const cables = elNS('g');
cables.setAttribute('class', 'patch-cables');
patchSvg.appendChild(cables);
patchSvg._cables = cables;
// each source/destination is a panel jack (metal nut + hole) with a label beside it
const jack = (kind, i, cy, label) => {
const g = elNS('g');
g.setAttribute('class', 'patch-jack ' + kind);
g.dataset.kind = kind;
g.dataset.i = i;
const jx = kind === 'src' ? PB_SPIN : PB_DPIN;
const tip = elNS('title');
tip.textContent = (kind === 'src' ? PATCH_SRC_TIP : PATCH_DST_TIP)[i] || label;
const nut = elNS('circle');
nut.setAttribute('cx', jx);
nut.setAttribute('cy', cy);
nut.setAttribute('r', 6.5);
nut.setAttribute('class', 'jack-nut');
const hole = elNS('circle');
hole.setAttribute('cx', jx);
hole.setAttribute('cy', cy);
hole.setAttribute('r', 2.8);
hole.setAttribute('class', 'jack-hole');
const t = elNS('text');
t.setAttribute('y', cy + 3);
t.setAttribute('class', 'patch-silk');
t.textContent = label;
if (kind === 'src') {
t.setAttribute('x', 6);
t.setAttribute('text-anchor', 'start');
} else {
t.setAttribute('x', PB_W - 6);
t.setAttribute('text-anchor', 'end');
}
g.append(tip, nut, hole, t);
patchSvg.appendChild(g);
};
MOD_SRC.slice(1).forEach((n, i) => jack('src', i, SRCY[i], n));
MOD_DST.forEach((n, j) => jack('dst', j, DSTY[j], n));
host.appendChild(patchSvg);
// drag a wire from either jack (source or destination)
patchSvg.addEventListener('pointerdown', (e) => {
const g = e.target.closest('.patch-jack');
if (!g) {
if (patchSel !== -1) {
patchSel = -1;
renderPatch();
}
return;
} // empty space -> deselect
const startKind = g.dataset.kind,
startI = +g.dataset.i;
const ax = startKind === 'src' ? PB_SPIN : PB_DPIN;
const ay = startKind === 'src' ? SRCY[startI] : DSTY[startI];
const temp = elNS('path');
temp.setAttribute('class', 'cab-temp');
patchSvg._cables.appendChild(temp);
try {
patchSvg.setPointerCapture(e.pointerId);
} catch (_) {}
const mv = (ev) => {
const q = svgPt(ev);
temp.setAttribute('d', cablePath(ax, ay, q.x, q.y));
};
const up = (ev) => {
patchSvg.removeEventListener('pointermove', mv);
patchSvg.removeEventListener('pointerup', up);
try {
patchSvg.releasePointerCapture(ev.pointerId);
} catch (_) {}
temp.remove();
const t = document.elementFromPoint(ev.clientX, ev.clientY);
const tg = t && t.closest ? t.closest('.patch-jack') : null;
if (tg && tg.dataset.kind !== startKind) {
// connect to the opposite side
const srcI = startKind === 'src' ? startI : +tg.dataset.i;
const dstI = startKind === 'src' ? +tg.dataset.i : startI;
const dup = findSlot(srcI + 1, dstI); // already wired? don't add a duplicate
if (dup >= 0) {
patchSel = dup; // just select the existing cable (adjust its amount)
} else {
const slot = freeSlot();
if (slot >= 0) {
slotSet(slot, srcI + 1, dstI, 0.75);
patchSel = slot;
}
}
}
renderPatch();
};
patchSvg.addEventListener('pointermove', mv);
patchSvg.addEventListener('pointerup', up);
mv(e);
});
renderPatch();
}
function renderPatch() {
if (!patchSvg) return;
const g = patchSvg._cables;
g.innerHTML = '';
for (let i = 0; i < 6; i++) {
const s = slotGet(i);
if (s.src === 0) continue;
const d = cablePath(PB_SPIN, SRCY[s.src - 1], PB_DPIN, DSTY[s.dst]);
const mag = Math.abs(s.amt * 2 - 1); // bipolar amount magnitude -> brightness
const cg = elNS('g');
cg.setAttribute('class', 'patch-cable' + (i === patchSel ? ' sel' : ''));
const hit = elNS('path');
hit.setAttribute('d', d);
hit.setAttribute('class', 'cab-hit'); // wide invisible click target
const under = elNS('path');
under.setAttribute('d', d);
under.setAttribute('class', 'cab-under');
const core = elNS('path');
core.setAttribute('d', d);
core.setAttribute('class', 'cab-core');
core.style.stroke = s.amt * 2 - 1 >= 0 ? 'var(--mode)' : 'var(--blue)'; // + green / - blue
core.style.opacity = (0.28 + 0.72 * mag).toFixed(3);
core.style.strokeWidth = (1.7 + 1.7 * mag).toFixed(2);
cg.append(hit, under, core);
cg.addEventListener('pointerdown', (e) => {
e.stopPropagation();
patchSel = i;
renderPatch();
});
g.appendChild(cg);
}
patchSvg.querySelectorAll('.patch-jack').forEach((p) => {
const kind = p.dataset.kind,
i = +p.dataset.i;
let used = false;
for (let s = 0; s < 6; s++) {
const sl = slotGet(s);
if (sl.src === 0) continue;
if (kind === 'src' && sl.src - 1 === i) used = true;
if (kind === 'dst' && sl.dst === i) used = true;
}
p.classList.toggle('used', used);
});
const ins = $('#patchInspect');
if (ins) {
const ok = patchSel >= 0 && slotGet(patchSel).src > 0;
ins.hidden = !ok;
if (ok) {
const s = slotGet(patchSel);
$('#patchLabel').textContent = MOD_SRC[s.src] + ' → ' + MOD_DST[s.dst];
if (patchKnobApply) patchKnobApply();
}
}
}
/* bipolar AMOUNT knob for the currently-selected cable (value display = +/-100) */
(function buildPatchKnob() {
const host = $('#patchAmtKnob');
if (!host) return;
const k = el('div', 'knob');
const dial = el('div', 'knob-dial');
dial.appendChild(el('span', 'knob-pointer'));
const lab = el('div', 'knob-label');
lab.textContent = 'AMT';
const val = el('div', 'knob-val');
val.textContent = '+0';
k.append(dial, lab, val);
host.appendChild(k);
const cur = () => (patchSel >= 0 ? slotGet(patchSel).amt : 0.5);
const apply = () => {