Debian Codegraph @

examples/book/digital-artists/chapter10/Listing10.5.ck

raw
1 // Listing 10.5 Using a custom Event subclass, with polymorphism
2 class TheEvent extends Event // (1) Declares Event subclass with extra instance variables.
3 {
4 int note; // (2) Integer note instance variable.
5 float velocity; // (3)Float velocity instance variable.
6 }
7
8 TheEvent evnt, evnt2; // (4) Declares two new TheEvent objects.
9
10 // patch
11 NRev globalReverb => dac; // (5) Declares a global reverb for use by all.
12 .1 => globalReverb.mix;
13
14 // instrument function to spork
15 fun void poly( StkInstrument instr, TheEvent e, string s )
16 { // (6) Declares an event-waiting, instrument-playing function.
17 // connect to output
18 instr => globalReverb; // (7) Connects the instrument to your global reverb.
19 // hang out waiting to receive an event to play
20 while( true ) // (8) Infinite loop.
21 {
22 // wait
23 e => now; // (9) Waits for event to be signaled.
24 // play
25 e.note => Std.mtof => instr.freq; // (10 When event comes, sets note frequency
26 e.velocity => instr.noteOn; // (11) ...and fires instrument with velocity.
27 }
28 }
29
30 // spork a few polys, listening on "evnt"
31 spork ~ poly( new StifKarp, evnt, "StifKarp" ); // (12) Sporks an evnt-waiting function with a StifKarp instrument...
32 spork ~ poly( new Mandolin, evnt, "Mandolin" ); // (13) and another with a Mandolin instrument...
33 spork ~ poly( new Wurley, evnt, "Wurley" ); // (14) ...and yet another with an FM Wurley instrument.
34
35 // spork one poly listening on "evnt2"
36 spork ~ poly( new Rhodey, evnt2, "Rhodey" ); // (15) Sporks an evnt2-waiting function with a Rhodey instrument.
37
38 [60,62,64,67,69,72,74,76,79] @=> int notes[]; // (16) Notes scale for your gamelan (a scale is called a laya).
39
40 // play forever
41 while( true )
42 { // (17) Infinite loop.
43 // fire the next signal, on a dice roll
44 Math.random2(1,6) => int dice; // (18) Dice roll.
45 if (dice != 1)
46 { // (19) Five times out of 6, pick a note from the laya.
47 // pick a random note from our array
48 notes[Math.random2(0,notes.cap()-1)] => evnt.note;
49 Math.random2f( .2, .9 ) => evnt.velocity; // (20) Random velocity.
50
51 // send the signal to only one instrument
52 evnt.signal(); // (21) Signal event (one of StifKarp, Mandolin, Wurley)...
53
54 // and advance time
55 0.25 :: second => now;
56 }
57 else
58 { // (22) ...otherwise, pick a lower laya note and signal evnt2 (Rhodey)...
59
60 // play a lower notes on evnt2, and all of the evnt instruments
61 notes[Math.random2(0,notes.cap()-1)] - 24 => evnt2.note;
62 notes[0] - 12 => evnt.note;
63 1.0 => evnt2.velocity;
64
65 // on all instrument shreds
66 evnt.broadcast(); // (23) ...and broadcast to all evnt listener instruments.
67 evnt2.signal();
68
69 // and wait longer
70 second => now;
71 }
72 }
73