-
Notifications
You must be signed in to change notification settings - Fork 1
/
Cisp.py
executable file
·2530 lines (2099 loc) · 76.3 KB
/
Cisp.py
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
#!/usr/bin/python
# 29-03-2024
import math
import operator as op
import re
import os
import random
import functools
import sys
import getopt
import string
from time import sleep
from time import time
import uuid
from string import Template
# TODO
# bug: latch cannot do zero times an element ?
# adding streams to an already ongoing process.
# eval should remember if a list is generated from numbers (typed list), when a list is nested it should still know its origin
# a new st.write variant could be st.append: it adds a single value to a table. past values can simply be reached through the normal streams
# with the table as parameter.
# (~ append tab1 (rv 0 100)) would add a random value between 0 100 to a table
# /usr/local/bin/chuck --srate:44100 --out:4 --chugin-path:/Users/casperschipper/Library/Application\ Support/ChucK/ChuGins --loop /Users/casperschipper/Google\ Drive/ChucK/tools/Tools.ck
# being able to bind a midicontroller to a stream-synth / note generator
# something like:
# (attach mySynth (key 60))
# mySynth only takes of or on
# (attach mySynth (key 60) (controller 1))
# (attach mySynth keyboard)
# a key produces (pitch, noteOn | noteOff )
# a midi controller produces (controller, value)
# how to parse context:
# a ( b ) -> A ( B )
# c ( b ) -> C ( B' ) B' is different since a is a different context to c
# synth should be stream out of higher order.
# right now, all synths takes values and times in between.
# what if we make a synth/event gen that takes events as the arg.
# a streamsynth that triggers the events.
# synth that produces events so we can trigger other streams with it.
# event streams in scheme?
Symbol = str # A Scheme Symbol is implemented as a Python str
List = list # A Scheme List is implemented as a Python list
# A Scheme Number is implemented as a Python int or float
Number = (int, float)
# usage: FileIO( inputFile, outputFile)
class FileIO(object):
"File input output module"
def __init__(self, fileInName, fileOutName):
self.inFile = open(fileInName, "r")
self.outFile = open(fileOutName, "w")
unique_filename = "tmp"
self.cleanFile(unique_filename)
self.processInfile()
os.remove(unique_filename)
print("the file", unique_filename, "was deleted.")
def cleanFile(self, unique_filename):
self.cleanFile = open(unique_filename, "w")
data = ""
for line in self.inFile:
data += line
print("remove comments", self.remove_comments(data))
self.cleanFile.write(self.remove_comments(data))
self.cleanFile.close()
self.inFile = open(unique_filename, "r")
def remove_comments(self, string):
"remove comments & multi-line comments"
pattern = r"(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*$)"
# pattern = r"(/\*.*?\*/|//[^\r\n]*$)"
# first group captures quoted strings (double or single)
# second group captures comments (//single-line or /* multi-line */)
regex = re.compile(pattern, re.MULTILINE | re.DOTALL)
def _replacer(match):
# if the 2nd group (capturing comments) is not None,
# it means we have captured a non-quoted (real) comment string.
if match.group(2) is not None:
return "" # so we will return empty to remove the comment
else: # otherwise, we will return the 1st group
return match.group(1) # captured quoted-string
return regex.sub(_replacer, string)
def writeLine(self, line):
self.outFile.write(line)
def processInfile(self):
"Stack all the lines together, process each line"
fullLine = ""
nOpen, nClosed, thisLineCount = 0, 0, 0
# making sure we parse a full S-expression
for line in self.inFile:
nOpen += self.countOpen(line)
nClosed += self.countClosed(line)
thisLineCount = nOpen - nClosed
if nOpen > 0:
if thisLineCount != 0:
fullLine += line.replace("\n", "")
else:
fullLine += line.replace("\n", "")
self.parseLine(fullLine)
fullLine = ""
nOpen, nClosed, thisLineCount = 0, 0, 0
self.outFile.write('\n<<<"shred id: ",me.id()>>>;')
# add an end event
self.outFile.write(
"\nEvent end;\n(new ShredEventStack).push(end);\nend => now;"
)
self.outFile.close()
def parseLine(self, string):
parser = Cisp(string)
result = parser.result()
# print 'result:'
# print (result)
self.writeLine(result)
def countOpen(self, string):
count = 0
for x in string:
if x == "(":
count += 1
return count
def countClosed(self, string):
count = 0
for x in string:
if x == ")":
count += 1
return count
def isComplete(self, string):
"returns true if the line is balanced"
level = 0
flag = 0
for x in string:
if x == "(":
flag = True # there is at least one parenthesis
level = level + 1
elif x == ")":
level = level - 1
return (level == 0) and flag
def isIncomplete(self, string):
level = 0
# class EndEvent(object):
# "This is used at the end of a shred, to be able to stop it. not in use currently"
# def __init__(self,identifier):
# self.identifier = identifier
# def __repr__(self):
# # we return the name, so we can stop it later
# print "script is named: "+self.identifier;
# return "Event theEnd @=> st.events["+self.identifier+"];\ntheEnd => now;\n"
class UniqueName(object):
"creates unique names with a prefix, used for temp functions"
def __init__(self):
self.prefixDict = {}
self.creation = str(int(time()))
def thisShred(self):
return "shred-" + self.creation
def name(self, prefix):
"returns a unique name based on a prefix, if used before adds _2 _3 etc.."
if prefix in self.prefixDict.keys():
self.prefixDict[prefix] += 1
return prefix + "_" + str(self.prefixDict[prefix])
else:
self.prefixDict[prefix] = 1
return prefix + "_1"
unique = UniqueName()
class Cisp(object):
"This is the main class, it takes a text file input and translates it to ChucK+Tools.ck family of objects"
def __init__(self, text):
# TODO REMOVE
# lex the text, convert S-expressions to python lists
self.parsedText = self.parse(text)
# clean all the string stuff, combine paths with space inside
self.parsedText = StringParser(self.parsedText).parse()
# print "self.parsedText",self.parsedText
# evaluate the python lists to chuck code
self.evaluatedText = eval(self.parsedText)
def result(self):
return self.evaluatedText
def tokenize(self, chars):
"Convert a string of characters into a list of tokens."
return chars.replace("(", " ( ").replace(")", " ) ").split()
def parse(self, program):
"Read a Cisp expression from a string."
return self.read_from_tokens(self.tokenize(program))
def read_from_tokens(self, tokens):
"Read an expression from a sequence of tokens."
if len(tokens) == 0:
raise SyntaxError("unexpected EOF while reading")
token = tokens.pop(0)
if "(" == token:
L = []
while tokens[0] != ")":
L.append(self.read_from_tokens(tokens))
tokens.pop(0) # pop off ')'
return L
elif ")" == token:
raise SyntaxError("unexpected )")
else:
return self.atom(token)
def atom(self, token):
"Numbers become numbers; every other token is a symbol."
try:
return int(token)
except ValueError:
try:
return float(token)
except ValueError:
return self.Symbol(token)
def Symbol(self, token):
"does something with a token"
return token
# Env = dict # An environment is a mapping of {variable: value}
class StringParser:
def __init__(self, seq):
self.lst = seq
def nextToken(self):
if self.lst:
# print "debug: self.lsg",self.lst
return self.lst.pop(0)
return False
def parse(self):
"This ugly beast takes care of file strings and comments"
result = []
# print '1. parse is called', self.lst
item = self.nextToken()
while (
item is not False
): # first item passed, is not because of 0 should be parsed
# print "2. ok first step is ok"
if type(item) == type(
[]
): # if it is a list, parse it first than add to list
# print "3. item is list, so call a new one", item
parser = StringParser(item)
result = result + [parser.parse()]
elif type(item) == type(""): # if the item is a string
# print "4. item is a string", item
if item[0] == '"':
# print "5. oooh, the first character is a quotation", item
combined = item # start a combined
# print "6. combined =", combined
item = self.nextToken() # move on to next
if item is False:
# this is really silly coding.. :-/
result = result + [combined]
while item is not False: # if there is one
# print item, "7. item not false"
if type(item) == type(""):
combined = combined + " " + item
if item[-1] == '"': # we reached the end
# print "8. we reached the end", item
# store the combined result
result = result + [combined]
# print result
break
else:
print("ERROR unexpected string break")
# print "9. next token"
item = self.nextToken() # get next token
# print "while finished NEED TO FIX HERE", result
break
else: # it is just a string not a special one
# print "10. not a special string", item
result = result + [item]
# print "11. this is the result", result
else: # it is not a string, but a number
# print "11b. a it is a number"
result = result + [item]
item = self.nextToken() # get the next token
# print "12. return result", result
return result
class Env(dict):
"An environment: a dict of {'var':val} pairs, with an outer Env."
def __init__(self, parms=(), args=(), outer=None):
self.update(zip(parms, args))
self.outer = outer
def find(self, var):
"Find the innermost Env where var appears. otherwise show what went wrong"
try:
return self if (var in self) else self.outer.find(var)
except AttributeError:
print("value:" + var + " not found.")
class StreamFuncDef(object):
"A definition of a stream function, this will combine input streams into some output stream"
def __init__(self, lexedCispDefinitionList, environment, depth):
self.defList = lexedCispDefinitionList
self.env = environment
self.depth = depth
parsed = self.parse()
self.result = parsed
def __repr__(self):
return self.result
def __str__(self):
return self.__repr__()
def makeFunction(self, functionName, arguments, body):
"make a chuck Stream function, only stream arguments allowed"
if arguments == None:
arguments = []
# add Stream type before all values. Join with ',' .
arguments = ",".join(["Stream " + x for x in arguments])
return (
"fun Stream "
+ functionName
+ " ("
+ arguments
+ ") {\n"
+ "return "
+ body
+ ";\n}\n"
)
def parse(self):
x = self.defList
env = self.env
if len(x) > 3:
(_, var, arg, body) = x # _ = 'fun'
functionDiscr = {var: {"name": var, "args": len(arg)}}
env.update(functionDiscr)
localEnv = Env((), (), env)
for item in arg:
# parameter stored in a local env, to not polute global env
localEnv.update({item: {"name": item}})
env[var]["args"] = len(arg) # store the number of args in env
body = eval(body, localEnv)
else: # no arguments, only name and body
(_, var, body) = x
functionDiscr = {var: {"name": var, "args": 0, "isFunction": True}}
env.update(functionDiscr)
arg = None
body = eval(body, env)
return self.makeFunction(var, arg, body)
# A couple of helper functions
def makeNewBus(busName, body):
"Make a Chuck Stream Bus, a bus is a shared stream. When a caller gets a new value it updates the state inside"
return "\nst.bus(" + body + ',"' + busName + '")'
def returnOldBus(busName):
"Return a new value"
return '\nst.bus("' + busName + '")'
def anyIn(seq1, seq2):
"return true of any item in seq is in seq2"
for item in seq1:
if item in seq2:
return True
return False
class StreamCall(object):
"this tranlates a function call"
def __init__(self, name, arguments, environment, depth):
self.cispname = name
self.name = eval(name, environment, depth) # evaluate the name
# this is needed to move from (seq... ) to st.seq(.. ).
self.arguments = arguments # including the keyed args
self.env = environment
self.depth = depth # depth is used for pretty formatting
self.splitKeyed() # split : notation named arguments. For example (seq 10 20 holdMode:true)
# will result in st.seq([10,20]).holdMode(true)
self.checkArgs() # checks number and correctness of ars
self.evaluateArgs() # evaluate arguments
def __str__(self):
return self.__repr__()
def __repr__(self):
"this is the central construction of the function call"
return self.name + "(" + self.printArguments() + ")" + self.setters()
def evaluateArgs(self):
"this evaluates the arguments"
self.arguments = [eval(exp, self.env, self.depth + 1) for exp in self.arguments]
def checkArgs(self):
"retrieve the number of args expected"
numOfArgs = (self.env.find(self.cispname)[self.cispname]).get("args")
if not numOfArgs:
numOfArgs = "inf"
if type(numOfArgs) == type(1):
numOfArgs = [numOfArgs]
# print('it is now this:'+ str(numOfArgs))
if not "inf" in numOfArgs and not len(self.arguments) in numOfArgs:
raise Exception(
"function:"
+ self.name
+ " has "
+ str(len(self.arguments))
+ " args, expects: "
+ str(numOfArgs)
+ "\n"
+ "argumnets were:"
+ str(self.arguments)
+ "\n"
)
def splitKeyed(self):
"Strip the keyed arguments (:key values) from the arguments list"
def snext(iterator):
# safe next, returns false instead of raising error
return next(iterator, False)
def isKey(string):
# returns key if starts with ':'
if isinstance(string, str):
if string[0] == ":":
return string[1:]
return False
self.extra = {}
normalArgs = []
iterator = iter(self.arguments)
item = snext(iterator)
isKeyedArg = False
while item is not False:
key = isKey(item)
if key:
# move to next arg
item = snext(iterator)
# add the arg to the key, evaluate the value of the key.
self.extra[key] = eval(item, self.env, self.depth)
# move forward and loop on
item = snext(iterator)
else:
# normal args
normalArgs.append(item)
item = snext(iterator)
self.arguments = normalArgs
def printArguments(self):
# this joins the (evaluated) arguments, separated by a comma.
return ",".join(self.arguments)
def setters(self):
# there must be some way of telling to the outside world that this should be treaded as list thing when embedded in an SEQ.
return "".join(
[
"." + str(key) + "(" + str(value) + ")"
for key, value in self.extra.items()
]
)
# note the ; at the end, not be embedded in other expresssions
class SingleStatement(StreamCall):
def __repr__(self):
return self.name + "(" + self.printArguments() + ")" + self.setters() + ";\n\n"
class Cloner(StreamCall):
# this should clone a segment of code n times
def __init__(self, name, arguments, environment, depth):
self.cispname = name
self.name = eval(name, environment, depth) # evaluate the name
# this is needed to move from seq() to st.seq.
# pop the number of times from the arguments
self.numberOfClones = arguments.pop()
self.arguments = arguments # including the keyed args
self.env = environment # a bit nasty to do it like this but okay
self.depth = depth # depth is mainly used for pretty formatting
self.splitKeyed() # split : notation named arguments. For example (seq 10 20 holdMode:true)
# will result in st.seq([10,20]).holdMode(true)
self.checkArgs() # checks number and correctness of ars
self.evaluateArgs() # evaluate arguments
def __str__(self):
return self.__repr__()
def __repr__(self):
"this is the central construction of the function call"
code_shred = self.printArguments()
string = ""
for i in range(0, self.numberOfClones):
string = string + code_shred.replace("shred_1", "shred_" + str(i + 2))
return string
# # NOT USED
# class ListStream(StreamCall):
# def printArguments(self):
# "Explicit list definition"
# args = ','.join(self.arguments)
# return '[' + mixedTypeListFix( args ) + ']'
class ListStreamCall(StreamCall):
"this should be used for Seq, Series and Choice"
def evaluateArgs(self):
"this avaluates the arguments"
self.depth = 0
self.arguments = [eval(exp, self.env, self.depth + 1) for exp in self.arguments]
def printArguments(self):
"checks if holdmode true, adds that to the end of the arguments, after the list"
if self.arguments[-1] == "true":
self.arguments = self.arguments[:-1]
holdMode = ",true"
else:
holdMode = ""
if self.checkIfArgsIsArrayPointer():
return ",".join(mixedTypeListFix(self.arguments)) + holdMode
return "[" + ",".join(mixedTypeListFix(self.arguments)) + "]" + holdMode
def checkIfArgsIsArrayPointer(self):
"check arguments, only True with single argument"
if len(self.arguments) == 1:
return True
return False
class ListListStreamCall(StreamCall):
"this is used for weights"
def evaluateArgs(self):
self.depth = 0
self.arguments = [eval(exp, self.env, self.depth + 1) for exp in self.arguments]
if matchStrings(self.arguments, "st"):
self.name = eval("stream-weights")
class BusCall(StreamCall):
"This should do something based on the number of arguments"
def __str__(self):
return self.__repr__()
def __repr__(self):
"this is the central construction of the function call"
return self.name + "(" + self.printArguments() + ")" + self.setters()
def evaluateArgs(self):
"this avaluates the arguments"
self.arguments = [eval(exp, self.env, self.depth + 1) for exp in self.arguments]
class ArrayGen(StreamCall):
def printArguments(self):
return ",".join(self.arguments)
class PanSynth(StreamCall):
def __repr__(self):
sparkName = unique.name("shred")
amp, timer, panner = self.arguments
chuckCode = (
"""
fun void """
+ sparkName
+ """() {
"""
+ self.name
+ """ s;
s.init("""
+ amp
+ "\n,"
+ timer
+ "\n,"
+ panner
+ """\n);
day => now;
}
spork ~ """
+ sparkName
+ """();
"""
) # creates a function sparkname and immediately execute
return chuckCode
class WriteSchedule(StreamCall):
"A function that calls a non-standard synth"
def __repr__(self):
print("self.name WRITESCHEDULE = ", self.name)
# generate a name, construct a shred, spork it.
sparkName = unique.name("shred")
amp, timer = self.arguments
chuckCode = (
"""
fun void """
+ sparkName
+ """() {
"""
+ self.name
+ """ s;
// shred to write value to table (st.write), amp is ignored
s.init("""
+ amp
+ "\n,"
+ timer
+ """\n\n);
day => now;
}
spork ~ """
+ sparkName
+ """();
"""
) # immediately execute
return chuckCode
class EventGenerator(StreamCall):
"An event generator"
def deferedParsFormatted(self):
# print ("self.defered dict",self.defered)
return "".join(
[
's.addDefered("' + key + '",' + value + ");\n"
for key, value in self.defered.items()
]
)
def extraParsFormatted(self):
"this formats the extra parameters"
# print "self.extra dict",self.extra
return "".join(
[
's.addPar("' + key + '",' + value + ");\n"
for key, value in self.extra.items()
]
)
def splitKeyed(self):
# print "something is ok"
"Specially adjusted for once per event stream. Strip the keyed arguments (:key values) from the arguments list"
def snext(iterator):
# safe next, returns false instead of raising error
return next(iterator, False)
def isKey(string):
# returns key if starts with ':'
if isinstance(string, str):
if string[0] == ":":
return string[1:]
return False
def isDefer(string):
# returns key if defer ;
if isinstance(string, str):
if string[0] == ";":
return string[1:]
return False
self.extra = {}
self.defered = (
{}
) # this contains all the defered streams, evaluated once per event
normalArgs = []
iterator = iter(self.arguments)
item = snext(iterator)
isKeyedArg = False
while item is not False:
key = isKey(item)
defer = isDefer(item)
if key:
# move to next arg
item = snext(iterator)
# add the arg to the key, evaluate the value of the key.
self.extra[key] = eval(item, self.env, self.depth)
# move forward and loop on
item = snext(iterator)
elif defer:
# move to next arg
item = snext(iterator)
# add the arg to the key, evaluate the value of the key.
self.defered[defer] = eval(item, self.env, self.depth)
# move forward and loop on
item = snext(iterator)
else:
# normal args
normalArgs.append(item)
item = snext(iterator)
self.arguments = normalArgs
class DirectSynth(EventGenerator):
"A function that calls a non-standard synth"
# translator of names:
def __repr__(self):
# generate a name, lookup synth name, construct a Synth shred, spork it.
sparkName = unique.name("shred")
print("self.arguments")
amp, timer = self.arguments
panUnit = pancontrol = ""
if "pan" in self.extra.keys():
panUnit = "Pan4 p => dac;"
pancontrol = "p.pan(" + self.extra["pan"] + ");"
elif "chan" in self.extra.keys():
panUnit = "dac.chan(" + self.extra["chan"] + " $ int);\n"
else:
panUnit = panUnit + "dac;\n"
chuckCode = (
"""
fun void """
+ sparkName
+ """() {
"""
+ self.name
+ """ s => Safe safe =>"""
+ panUnit
+ self.deferedParsFormatted()
+ """\n
s.init("""
+ amp
+ "\n,"
+ timer
+ """\n\n);
"""
+ pancontrol
+ """
day => now;
}
spork ~ """
+ sparkName
+ """();
"""
) # creates a function sparkname and immediately execute
return chuckCode
def checkArgs(self):
if len(self.arguments) != 2:
print(
"error, stepgen wrong number of args (should be 2): "
+ len(self.arguments)
)
return False
return True
class ChannelSynth(EventGenerator):
"A function that calls a non-standard synth"
# translator of names:
def __repr__(self):
# generate a name, lookup synth name, construct a Synth shred, spork it.
sparkName = unique.name("shred")
print("self.arguments", self.arguments)
value, dura, amp, channel = self.arguments
chuckCode = (
"""
fun void """
+ sparkName
+ """() {
"""
+ self.name
+ """ s ;"""
+ self.deferedParsFormatted()
+ """\n
s.init("""
+ value
+ "\n,"
+ dura
+ "\n,"
+ amp
+ "\n,"
+ channel
+ """\n\n);
day => now;
}
spork ~ """
+ sparkName
+ """();
"""
) # creates a function sparkname and immediately execute
return chuckCode
def checkArgs(self):
if len(self.arguments) != 4:
print(
"error, ChannelSynth wrong number of args (should be 4): "
+ str(len(self.arguments))
)
return False
return True
class FBSynth(DirectSynth):
"A function that calls a non-standard synth, with feedback loop"
# translator of names:
def __repr__(self):
# generate a name, lookup synth name, construct a Synth shred, spork it.
sparkName = unique.name("shred")
schedule = ""
if len(self.arguments) == 5:
amp, timer, pan, freq, fb = self.arguments
else:
amp, timer, pan, freq, fb, schedule = self.arguments
schedule = "," + schedule
chuckCode = (
"""
fun void """
+ sparkName
+ """() {
"""
+ self.name
+ """ s => Safe safe => dac;
s.init("""
+ amp
+ ","
+ timer
+ ","
+ pan
+ ","
+ freq
+ ","
+ fb
+ schedule
+ """\n\n);
day => now;
}
spork ~ """
+ sparkName
+ """();
"""
) # creates a function sparkname and immediately execute
return chuckCode
def checkArgs(self):
if not (len(self.arguments) in [5, 6]):
print(
"error, wrong number of args (should be 5 or 6, amp time pan freq fb): ",
str(len(self.arguments)),
)
return False
return True
class NodeSynth(DirectSynth):
"A bunch of Chaos.13 like node"
# translator of names:
def __repr__(self):
# generate a name, lookup synth name, construct a Synth shred, spork it.
sparkName = unique.name("shred")
if len(self.arguments) == 10:
size, amp, pan, out, dur, top, timer, record, inp, fund = self.arguments
else:
raise ("node error")
chuckCode = (
"""
fun void """
+ sparkName
+ """() {
"""
+ self.name
+ """ s => Safe safe => dac;
s.init("""
+ size
+ ","
+ amp
+ ","
+ pan
+ ","
+ out
+ ","
+ dur
+ ","
+ top
+ ","
+ timer
+ ","
+ record
+ ","
+ inp
+ ","
+ fund
+ """);