Skip to content

Commit

Permalink
add section about modules + implement exportModule
Browse files Browse the repository at this point in the history
  • Loading branch information
felixroos committed Jun 27, 2024
1 parent ac9824d commit aa78c4e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
12 changes: 11 additions & 1 deletion packages/core/src/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ let dfs = (node, fn, visited = []) => {
return node;
};

let modules = new Map(); // module registry
export let modules = new Map(); // module registry

// user facing function to create modules
export function module(name, fn) {
Expand All @@ -74,6 +74,16 @@ Node.prototype.resolveModules = function () {
return resolveModules(this);
};

// converts a registered module into a json string
export function exportModule(name) {
const mod = modules.get(name);
const inputs = Array.from({ length: mod.length }, (_, i) =>
node(`$INPUT${i}`)
);
const exported = mod(...inputs);
return JSON.stringify(exported, null, 2);
}

// returns true if the given node forms a cycle with "me" (or is me)
function loopsToMe(node, me) {
if (node === me) {
Expand Down
27 changes: 27 additions & 0 deletions website/src/pages/learn.astro
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,33 @@ saw(midifreq().fork(8)) // 8 saw voices
.out();`
client:only="solid"
/>
<h2>Modules</h2>
The graph representation of the previous patch is very much cable salad at
this point. To improve things, you can define modules like this:
<MiniRepl
code=`let synth = module("synth", (freq, gate) => {
let env = gate.adsr(0.01, 0.4, 0.7, 0.1);
return saw(freq).mul(env)
.filter( env.range(0.2, 0.8).mul(env) );
});
let freq = impulse(4).seq(55,110,220,330)
let gate = impulse(4).perc(.2)
synth(freq, gate)
.add((x) => x.delay(0.2).mul(0.4)) // feedback delay
.out()`
client:only="solid"
/>
<Box>
<p>
Note that in the graph above, the "synth" is a single node, hiding its
internal complexity.
</p>
<p>
Defining modules is a more advanced feature and requires you to know
how JS functions are written.
</p>
</Box>
</main>
</body>
</html>

0 comments on commit aa78c4e

Please sign in to comment.