Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
L-System in SuperCollider
// Instrument
(
SynthDef(\sine, {
arg freq = 440, amp = 0.5;
Out.ar(0, SinOsc.ar(freq, 0.0, amp * EnvGen.kr(Env.perc(0.01, 0.25), doneAction: 2)) ! 2);
}).add;
)
// Basic Stochastic L-System
(
l = {
arg iterations = 2;
// define your l system
var axiom = "N";
var variables = "N";
var constants = "+-[]<>";
var rules = Dictionary.new();
// accepts both strings and arrays
// if array, it a random entry
rules.put($N, [
"N[<++++N<+++N]N>" // dom 7 chord
]);
// iterate
iterations.do({
|i|
var output = "";
axiom.do({
|c, i|
if (variables.includes(c), {
if (rules.at(c).isKindOf(String), {
output = output ++ rules.at(c)
}, {
output = output ++ rules.at(c).choose
})
});
if (constants.includes(c), {
output = output ++ c
});
});
axiom = output;
});
axiom;
}
)
// Play the song
(
var song = l.value(5);
var cursor = 0.0;
var stack = List.new();
var midi = 60;
var noteLen = 0.125;
stack.add(midi);
song.do({
arg c, i;
switch (c,
$N, {
var f = midi.midicps;
SystemClock.sched(cursor, {
Synth(\sine, [\freq, f, \amp, 0.2 ])
});
cursor = cursor + noteLen;
},
$+, { midi = midi + 1 },
$-, { midi = midi - 1 },
$[, { stack.add(midi) },
$], { midi = stack.pop() },
$>, { cursor = cursor + noteLen; },
$<, { cursor = cursor - noteLen; },
)
});
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment