Compare commits

..

5 Commits

Author SHA1 Message Date
Felix Roos 4b7ec7b403 Merge remote-tracking branch 'origin/main' into voicing-rework 2022-10-29 17:55:23 +02:00
Felix Roos d23085e553 Merge commit '5f381cf1536e3c87e16cf164e91666d8b7ec403a' into voicing-rework 2022-10-27 22:36:34 +02:00
Felix Roos d323b6843d Merge remote-tracking branch 'origin/main' into voicing-rework 2022-09-25 21:16:59 +02:00
Felix Roos b2e927f4f0 Merge branch 'main' into voicing-rework 2022-09-22 19:27:29 +02:00
Felix Roos 3a271022b0 configurable voicings 2022-09-10 22:50:03 +02:00
36 changed files with 1760 additions and 10032 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18]
node-version: [16, 17]
steps:
- uses: actions/checkout@v2
+6 -6
View File
@@ -3314,9 +3314,9 @@
}
},
"node_modules/caniuse-lite": {
"version": "1.0.30001430",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001430.tgz",
"integrity": "sha512-IB1BXTZKPDVPM7cnV4iaKaHxckvdr/3xtctB3f7Hmenx3qYBhGtTZ//7EllK66aKXW98Lx0+7Yr0kxBtIt3tzg==",
"version": "1.0.30001341",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001341.tgz",
"integrity": "sha512-2SodVrFFtvGENGCv0ChVJIDQ0KPaS1cg7/qtfMaICgeMolDdo/Z2OD32F0Aq9yl6F4YFwGPBS5AaPqNYiW4PoA==",
"funding": [
{
"type": "opencollective",
@@ -15537,9 +15537,9 @@
}
},
"caniuse-lite": {
"version": "1.0.30001430",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001430.tgz",
"integrity": "sha512-IB1BXTZKPDVPM7cnV4iaKaHxckvdr/3xtctB3f7Hmenx3qYBhGtTZ//7EllK66aKXW98Lx0+7Yr0kxBtIt3tzg=="
"version": "1.0.30001341",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001341.tgz",
"integrity": "sha512-2SodVrFFtvGENGCv0ChVJIDQ0KPaS1cg7/qtfMaICgeMolDdo/Z2OD32F0Aq9yl6F4YFwGPBS5AaPqNYiW4PoA=="
},
"caseless": {
"version": "0.12.0",
-1
View File
@@ -4,7 +4,6 @@
"private": true,
"description": "Port of tidalcycles to javascript",
"scripts": {
"pretest": "cd tutorial && npm run jsdoc-json",
"test": "vitest run --version",
"test-ui": "vitest --ui",
"test-coverage": "vitest --coverage",
+5 -12
View File
@@ -40,6 +40,11 @@ const generic_params = [
* @example
* n("0 1 2 3").s('east').osc()
*/
// TODO: nOut does not work
// TODO: notes don't work as expected
// current "workaround" for notes:
// s('superpiano').n("<c0 d0 e0 g0>"._asNumber()).osc()
// -> .n or .osc (or .superdirt) would need to convert note strings to numbers
// also see https://github.com/tidalcycles/strudel/pull/63
['f', 'n', 'The note or sample number to choose for a synth or sampleset'],
['f', 'note', 'The note or pitch to play a sound or synth with'],
@@ -95,18 +100,6 @@ const generic_params = [
'attack',
'a pattern of numbers to specify the attack time (in seconds) of an envelope applied to each sample.',
],
/**
* Select the sound bank to use. To be used together with `s`. The bank name (+ "_") will be prepended to the value of `s`.
*
* @name bank
* @param {string | Pattern} bank the name of the bank
* @example
* s("bd sd").bank('RolandTR909') // = s("RolandTR909_bd RolandTR909_sd")
*
*/
['f', 'bank', 'selects sound bank to use'],
// TODO: find out how this works?
/*
* Envelope decay time = the time it takes after the attack time to reach the sustain level.
-1
View File
@@ -21,7 +21,6 @@ import Fraction, { gcd } from './fraction.mjs';
* @example
* const line = drawLine("0 [1 2 3]", 10); // |0--123|0--123
* console.log(line);
* silence;
*/
function drawLine(pat, chars = 60) {
let cycle = 0;
+2 -3
View File
@@ -4,10 +4,10 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import controls from './controls.mjs';
export * from './controls.mjs';
export * from './euclid.mjs';
import Fraction from './fraction.mjs';
export { Fraction, controls };
export { Fraction };
export * from './hap.mjs';
export * from './pattern.mjs';
export * from './signal.mjs';
@@ -15,7 +15,6 @@ export * from './state.mjs';
export * from './timespan.mjs';
export * from './util.mjs';
export * from './speak.mjs';
export { default as drawLine } from './drawLine.mjs';
export { default as gist } from './gist.js';
// below won't work with runtime.mjs (json import fails)
/* import * as p from './package.json';
+50 -39
View File
@@ -10,7 +10,7 @@ import Hap from './hap.mjs';
import State from './state.mjs';
import { unionWithObj } from './value.mjs';
import { compose, removeUndefineds, flatten, id, listRange, curry, mod, numeralArgs, parseNumeral } from './util.mjs';
import { isNote, toMidi, compose, removeUndefineds, flatten, id, listRange, curry, mod } from './util.mjs';
import drawLine from './drawLine.mjs';
/** @class Class representing a pattern. */
@@ -32,10 +32,8 @@ export class Pattern {
* @param {Fraction | number} end to time
* @returns Hap[]
* @example
* const pattern = sequence('a', ['b', 'c'])
* const haps = pattern.queryArc(0, 1)
* console.log(haps)
* silence
* const pattern = sequence('a', ['b', 'c']);
* const haps = pattern.queryArc(0, 1);
*/
queryArc(begin, end) {
return this.query(new State(new TimeSpan(begin, end)));
@@ -65,17 +63,6 @@ export class Pattern {
return new Pattern((state) => this.query(state.withSpan(func)));
}
withQuerySpanMaybe(func) {
const pat = this;
return new Pattern((state) => {
const newState = state.withSpan(func);
if (!newState.span) {
return [];
}
return pat.query(newState);
});
}
/**
* As with {@link Pattern#withQuerySpan}, but the function is applied to both the
* begin and end time of the query timespan.
@@ -448,8 +435,34 @@ export class Pattern {
return otherPat.fmap((b) => this.fmap((a) => func(a)(b)))._TrigzeroJoin();
}
_asNumber() {
return this.fmap(parseNumeral);
_asNumber(dropfails = false, softfail = false) {
return this._withHap((hap) => {
const asNumber = Number(hap.value);
if (!isNaN(asNumber)) {
return hap.withValue(() => asNumber);
}
const specialValue = {
e: Math.E,
pi: Math.PI,
}[hap.value];
if (typeof specialValue !== 'undefined') {
return hap.withValue(() => specialValue);
}
if (isNote(hap.value)) {
// set context type to midi to let the player know its meant as midi number and not as frequency
return new Hap(hap.whole, hap.part, toMidi(hap.value), { ...hap.context, type: 'midi' });
}
if (dropfails) {
// return 'nothing'
return undefined;
}
if (softfail) {
// return original hap
return hap;
}
throw new Error('cannot parse as number: "' + hap.value + '"');
return hap;
});
}
/**
@@ -731,17 +744,12 @@ export class Pattern {
// // there is no gap.. so maybe revert to _fast?
// return this._fast(factor)
// }
// A bit fiddly, to drop zero-width queries at the start of the next cycle
const qf = function (span) {
const cycle = span.begin.sam();
const bpos = span.begin.sub(cycle).mul(factor).min(1);
const epos = span.end.sub(cycle).mul(factor).min(1);
if (bpos >= 1) {
return undefined;
}
return new TimeSpan(cycle.add(bpos), cycle.add(epos));
const begin = cycle.add(span.begin.sub(cycle).mul(factor).min(1));
const end = cycle.add(span.end.sub(cycle).mul(factor).min(1));
return new TimeSpan(begin, end);
};
// Also fiddly, to maintain the right 'whole' relative to the part
const ef = function (hap) {
const begin = hap.part.begin;
const end = hap.part.end;
@@ -757,7 +765,7 @@ export class Pattern {
);
return new Hap(newWhole, newPart, hap.value, hap.context);
};
return this.withQuerySpanMaybe(qf)._withHap(ef)._splitQueries();
return this.withQuerySpan(qf)._withHap(ef)._splitQueries();
}
// Compress each cycle into the given timespan, leaving a gap
@@ -1362,6 +1370,9 @@ function _composeOp(a, b, func) {
// Make composers
(function () {
const num = (pat) => pat._asNumber();
const numOrString = (pat) => pat._asNumber(false, true);
// pattern composers
const composers = {
set: [(a, b) => b],
@@ -1385,7 +1396,7 @@ function _composeOp(a, b, func) {
* // Behind the scenes, the notes are converted to midi numbers:
* // "48 52 55".add("<0 5 7 0>").note()
*/
add: [numeralArgs((a, b) => a + b)], // support string concatenation
add: [(a, b) => a + b, numOrString], // support string concatenation
/**
*
* Like add, but the given numbers are subtracted.
@@ -1395,7 +1406,7 @@ function _composeOp(a, b, func) {
* "0 2 4".sub("<0 1 2 3>").scale('C4 minor').note()
* // See add for more information.
*/
sub: [numeralArgs((a, b) => a - b)],
sub: [(a, b) => a - b, num],
/**
*
* Multiplies each number by the given factor.
@@ -1404,21 +1415,21 @@ function _composeOp(a, b, func) {
* @example
* "1 1.5 [1.66, <2 2.33>]".mul(150).freq()
*/
mul: [numeralArgs((a, b) => a * b)],
mul: [(a, b) => a * b, num],
/**
*
* Divides each number by the given factor.
* @name div
* @memberof Pattern
*/
div: [numeralArgs((a, b) => a / b)],
mod: [numeralArgs(mod)],
pow: [numeralArgs(Math.pow)],
_and: [numeralArgs((a, b) => a & b)],
_or: [numeralArgs((a, b) => a | b)],
_xor: [numeralArgs((a, b) => a ^ b)],
_lshift: [numeralArgs((a, b) => a << b)],
_rshift: [numeralArgs((a, b) => a >> b)],
div: [(a, b) => a / b, num],
mod: [mod, num],
pow: [Math.pow, num],
_and: [(a, b) => a & b, num],
_or: [(a, b) => a | b, num],
_xor: [(a, b) => a ^ b, num],
_lshift: [(a, b) => a << b, num],
_rshift: [(a, b) => a >> b, num],
// TODO - force numerical comparison if both look like numbers?
lt: [(a, b) => a < b],
@@ -1545,7 +1556,7 @@ export function pure(value) {
export function isPattern(thing) {
// thing?.constructor?.name !== 'Pattern' // <- this will fail when code is mangled
const is = thing instanceof Pattern || thing?._Pattern;
const is = thing instanceof Pattern || thing._Pattern;
if (!thing instanceof Pattern) {
console.warn(
`Found Pattern that fails "instanceof Pattern" check.
+1 -2
View File
@@ -238,7 +238,6 @@ export const wchoose = (...pairs) => wchooseWith(rand, ...pairs);
export const wchooseCycles = (...pairs) => _wchooseWith(rand, ...pairs).innerJoin();
// this function expects pat to be a pattern of floats...
export const perlinWith = (pat) => {
const pata = pat.fmap(Math.floor);
const patb = pat.fmap((t) => Math.floor(t) + 1);
@@ -256,7 +255,7 @@ export const perlinWith = (pat) => {
* s("bd sd,hh*4").cutoff(perlin.range(500,2000))
*
*/
export const perlin = perlinWith(time.fmap((v) => Number(v)));
export const perlin = perlinWith(time);
Pattern.prototype._degradeByWith = function (withPat, x) {
return this.fmap((a) => (_) => a).appLeft(withPat._filterValues((v) => v > x));
+10 -29
View File
@@ -47,9 +47,6 @@ import {
import { steady } from '../signal.mjs';
import controls from '../controls.mjs';
const { n } = controls;
const st = (begin, end) => new State(ts(begin, end));
const ts = (begin, end) => new TimeSpan(Fraction(begin), Fraction(end));
const hap = (whole, part, value, context = {}) => new Hap(whole, part, value, context);
@@ -140,9 +137,6 @@ describe('Pattern', () => {
it('Can make a pattern', () => {
expect(pure('hello').query(st(0.5, 2.5)).length).toBe(3);
});
it('Supports zero-width queries', () => {
expect(pure('hello').queryArc(0, 0).length).toBe(1);
});
});
describe('fmap()', () => {
it('Can add things', () => {
@@ -197,9 +191,6 @@ describe('Pattern', () => {
sequence([11, [12, 13]], [21, [22, 23]], [31, [32, 33]]),
);
});
it('can add object patterns', () => {
sameFirst(n(sequence(1, [2, 3])).add(n(10)), n(sequence(11, [12, 13])));
});
});
describe('keep()', () => {
it('can structure In()', () => {
@@ -382,10 +373,9 @@ describe('Pattern', () => {
);
});
it('copes with breaking up events across cycles', () => {
expect(pure('a').slow(2)._fastGap(2)._setContext({}).query(st(0, 2))).toStrictEqual([
hap(ts(0, 1), ts(0, 0.5), 'a'),
hap(ts(0.5, 1.5), ts(1, 1.5), 'a'),
]);
expect(pure('a').slow(2)._fastGap(2)._setContext({}).query(st(0, 2))).toStrictEqual(
[hap(ts(0, 1), ts(0, 0.5), 'a'), hap(ts(0.5, 1.5), ts(1, 1.5), 'a')]
);
});
});
describe('_compressSpan()', () => {
@@ -440,16 +430,6 @@ describe('Pattern', () => {
// mini('[c3 g3]/2 eb3') always plays [c3 eb3]
// mini('eb3 [c3 g3]/2 ') always plays [c3 g3]
});
it('Supports zero-length queries', () => {
expect(steady('a')._slow(1).queryArc(0, 0)).toStrictEqual(steady('a').queryArc(0, 0));
});
});
describe('slow()', () => {
it('Supports zero-length queries', () => {
expect(steady('a').slow(1)._setContext({}).queryArc(0, 0)).toStrictEqual(
steady('a')._setContext({}).queryArc(0, 0),
);
});
});
describe('inside', () => {
it('can rev inside a cycle', () => {
@@ -819,11 +799,10 @@ describe('Pattern', () => {
});
it('Squeezes to the correct cycle', () => {
expect(
pure(time.struct(true))
._squeezeJoin()
.queryArc(3, 4)
.map((x) => x.value),
).toStrictEqual([Fraction(3.5)]);
pure(time.struct(true))._squeezeJoin().queryArc(3,4).map(x => x.value)
).toStrictEqual(
[Fraction(3.5)]
)
});
});
describe('ply', () => {
@@ -876,7 +855,9 @@ describe('Pattern', () => {
});
describe('range', () => {
it('Can be patterned', () => {
expect(sequence(0, 0).range(sequence(0, 0.5), 1).firstCycle()).toStrictEqual(sequence(0, 0.5).firstCycle());
expect(sequence(0, 0).range(sequence(0, 0.5), 1).firstCycle()).toStrictEqual(
sequence(0, 0.5).firstCycle(),
);
});
});
describe('range2', () => {
+17 -80
View File
@@ -5,20 +5,7 @@ This program is free software: you can redistribute it and/or modify it under th
*/
import { pure } from '../pattern.mjs';
import {
isNote,
tokenizeNote,
toMidi,
fromMidi,
mod,
compose,
getFrequency,
getPlayableNoteValue,
parseNumeral,
parseFractional,
numeralArgs,
fractionalArgs,
} from '../util.mjs';
import { isNote, tokenizeNote, toMidi, fromMidi, mod, compose, getFrequency, getPlayableNoteValue } from '../util.mjs';
import { describe, it, expect } from 'vitest';
describe('isNote', () => {
@@ -105,16 +92,16 @@ describe('getFrequency', () => {
expect(getFrequency(happify(57, { type: 'midi' }))).toEqual(220);
});
it('should return frequencies unchanged', () => {
expect(getFrequency(happify(440, { type: 'frequency' }))).toEqual(440);
expect(getFrequency(happify(440, { type: 'frequency' }))).toEqual(440);
expect(getFrequency(happify(432, { type: 'frequency' }))).toEqual(432);
});
it('should turn object with a "freq" property into frequency', () => {
expect(getFrequency(happify({ freq: 220 }))).toEqual(220);
expect(getFrequency(happify({ freq: 440 }))).toEqual(440);
expect(getFrequency(happify({freq: 220}))).toEqual(220)
expect(getFrequency(happify({freq: 440}))).toEqual(440)
});
it('should throw an error when given a non-note', () => {
expect(() => getFrequency(happify('Q'))).toThrowError(`not a note or frequency: Q`);
expect(() => getFrequency(happify('Z'))).toThrowError(`not a note or frequency: Z`);
expect(() => getFrequency(happify('Q'))).toThrowError(`not a note or frequency: Q`)
expect(() => getFrequency(happify('Z'))).toThrowError(`not a note or frequency: Z`)
});
});
@@ -153,72 +140,22 @@ describe('compose', () => {
describe('getPlayableNoteValue', () => {
const happify = (val, context = {}) => pure(val).firstCycle()[0].setContext(context);
it('should return object "note" property', () => {
expect(getPlayableNoteValue(happify({ note: 'a4' }))).toEqual('a4');
expect(getPlayableNoteValue(happify({note: "a4"}))).toEqual('a4')
});
it('should return object "n" property', () => {
expect(getPlayableNoteValue(happify({ n: 'a4' }))).toEqual('a4');
expect(getPlayableNoteValue(happify({n: "a4"}))).toEqual('a4')
});
it('should return object "value" property', () => {
expect(getPlayableNoteValue(happify({ value: 'a4' }))).toEqual('a4');
expect(getPlayableNoteValue(happify({value: "a4"}))).toEqual('a4')
});
it('should turn midi into frequency', () => {
expect(getPlayableNoteValue(happify(57, { type: 'midi' }))).toEqual(220);
});
expect(getPlayableNoteValue(happify(57, {type: 'midi'}))).toEqual(220)
})
it('should return frequency value', () => {
expect(getPlayableNoteValue(happify(220, { type: 'frequency' }))).toEqual(220);
});
expect(getPlayableNoteValue(happify(220, {type: 'frequency'}))).toEqual(220)
})
it('should throw an error if value is not an object, number, or string', () => {
expect(() => getPlayableNoteValue(happify(false))).toThrowError(`not a note: false`);
expect(() => getPlayableNoteValue(happify(undefined))).toThrowError(`not a note: undefined`);
});
});
describe('parseNumeral', () => {
it('should parse numbers as is', () => {
expect(parseNumeral(4)).toBe(4);
expect(parseNumeral(0)).toBe(0);
expect(parseNumeral(20)).toBe(20);
expect(parseNumeral('20')).toBe(20);
expect(parseNumeral(1.5)).toBe(1.5);
});
it('should parse notes', () => {
expect(parseNumeral('c4')).toBe(60);
expect(parseNumeral('c#4')).toBe(61);
expect(parseNumeral('db4')).toBe(61);
});
it('should throw an error for unknown strings', () => {
expect(() => parseNumeral('xyz')).toThrowError('cannot parse as numeral: "xyz"');
});
});
describe('parseFractional', () => {
it('should parse numbers as is', () => {
expect(parseFractional(4)).toBe(4);
expect(parseFractional(0)).toBe(0);
expect(parseFractional(20)).toBe(20);
expect(parseFractional('20')).toBe(20);
expect(parseFractional(1.5)).toBe(1.5);
});
it('should parse fractional shorthands values', () => {
expect(parseFractional('w')).toBe(1);
expect(parseFractional('h')).toBe(0.5);
expect(parseFractional('q')).toBe(0.25);
expect(parseFractional('e')).toBe(0.125);
});
it('should throw an error for unknown strings', () => {
expect(() => parseFractional('xyz')).toThrowError('cannot parse as fractional: "xyz"');
});
});
describe('numeralArgs', () => {
it('should convert function arguments to numbers', () => {
const add = numeralArgs((a, b) => a + b);
expect(add('c4', 2)).toBe(62);
});
});
describe('fractionalArgs', () => {
it('should convert function arguments to numbers', () => {
const add = fractionalArgs((a, b) => a + b);
expect(add('q', 2)).toBe(2.25);
});
});
expect(() => getPlayableNoteValue(happify(false))).toThrowError(`not a note: false`)
expect(() => getPlayableNoteValue(happify(undefined))).toThrowError(`not a note: undefined`)
})
});
-5
View File
@@ -18,11 +18,6 @@ export class TimeSpan {
const end = this.end;
const end_sam = end.sam();
// Support zero-width timespans
if (begin.equals(end)) {
return([new TimeSpan(begin, end)]);
}
while (end.gt(begin)) {
// If begin and end are in the same cycle, we're done.
if (begin.sam().equals(end_sam)) {
-43
View File
@@ -130,46 +130,3 @@ export function curry(func, overload) {
}
return fn;
}
export function parseNumeral(numOrString) {
const asNumber = Number(numOrString);
if (!isNaN(asNumber)) {
return asNumber;
}
if (isNote(numOrString)) {
return toMidi(numOrString);
}
throw new Error(`cannot parse as numeral: "${numOrString}"`);
}
export function mapArgs(fn, mapFn) {
return (...args) => fn(...args.map(mapFn));
}
export function numeralArgs(fn) {
return mapArgs(fn, parseNumeral);
}
export function parseFractional(numOrString) {
const asNumber = Number(numOrString);
if (!isNaN(asNumber)) {
return asNumber;
}
const specialValue = {
pi: Math.PI,
w: 1,
h: 0.5,
q: 0.25,
e: 0.125,
s: 0.0625,
t: 1 / 3,
f: 0.2,
x: 1 / 6,
}[numOrString];
if (typeof specialValue !== 'undefined') {
return specialValue;
}
throw new Error(`cannot parse as fractional: "${numOrString}"`);
}
export const fractionalArgs = (fn) => mapArgs(fn, parseFractional);
+9 -16
View File
@@ -10,22 +10,15 @@ Either install with `npm i @strudel.cycles/embed` or just use a cdn to import th
<script src="https://unpkg.com/@strudel.cycles/embed@latest"></script>
<strudel-repl>
<!--
note(`[[e5 [b4 c5] d5 [c5 b4]]
[a4 [a4 c5] e5 [d5 c5]]
[b4 [~ c5] d5 e5]
[c5 a4 a4 ~]
[[~ d5] [~ f5] a5 [g5 f5]]
[e5 [~ c5] e5 [d5 c5]]
[b4 [b4 c5] d5 e5]
[c5 a4 a4 ~]],
[[e2 e3]*4]
[[a2 a3]*4]
[[g#2 g#3]*2 [e2 e3]*2]
[a2 a3 a2 a3 a2 a3 b1 c2]
[[d2 d3]*4]
[[c2 c3]*4]
[[b1 b2]*2 [e2 e3]*2]
[[a1 a2]*4]`).slow(16)
"a4 [a3 c3] a3 c3".color('#F9D649')
.sub("<7 12 5 12>".slow(2))
.off(1/4,x=>x.add(7).color("#FFFFFF #0C3AA1 #C63928"))
.off(1/8,x=>x.add(12).color('#215CB6'))
.slow(2)
.legato(sine.range(0.3, 2).slow(28))
.wave("sawtooth square".fast(2))
.filter('lowpass', cosine.range(500,4000).slow(16))
.pianoroll({minMidi:20,maxMidi:120,background:'#202124'})
-->
</strudel-repl>
```
+9 -16
View File
@@ -2,21 +2,14 @@
<!-- <script src="./embed.js"></script> -->
<strudel-repl>
<!--
note(`[[e5 [b4 c5] d5 [c5 b4]]
[a4 [a4 c5] e5 [d5 c5]]
[b4 [~ c5] d5 e5]
[c5 a4 a4 ~]
[[~ d5] [~ f5] a5 [g5 f5]]
[e5 [~ c5] e5 [d5 c5]]
[b4 [b4 c5] d5 e5]
[c5 a4 a4 ~]],
[[e2 e3]*4]
[[a2 a3]*4]
[[g#2 g#3]*2 [e2 e3]*2]
[a2 a3 a2 a3 a2 a3 b1 c2]
[[d2 d3]*4]
[[c2 c3]*4]
[[b1 b2]*2 [e2 e3]*2]
[[a1 a2]*4]`).slow(16)
"a4 [a3 c3] a3 c3".color('#F9D649')
.sub("<7 12 5 12>".slow(2))
.off(1/4,x=>x.add(7).color("#FFFFFF #0C3AA1 #C63928"))
.off(1/8,x=>x.add(12).color('#215CB6'))
.slow(2)
.legato(sine.range(0.3, 2).slow(28))
.wave("sawtooth square".fast(2))
.filter('lowpass', cosine.range(500,4000).slow(16))
.pianoroll({minMidi:20,maxMidi:120,background:'#202124'})
-->
</strudel-repl>
-9
View File
@@ -33,12 +33,3 @@ yields:
## Mini Notation API
See "Mini Notation" in the [Strudel Tutorial](https://strudel.tidalcycles.org/tutorial/)
## Building the Parser
The parser [krill-parser.js] is generated from [krill.pegjs](./krill.pegjs) using [peggy](https://peggyjs.org/).
To generate the parser, run
```js
npm run build:parser
```
+4 -7
View File
@@ -6,7 +6,7 @@ This program is free software: you can redistribute it and/or modify it under th
import * as krill from './krill-parser.js';
import * as strudel from '@strudel.cycles/core';
// import { addMiniLocations } from '@strudel.cycles/eval/shapeshifter.mjs';
import { addMiniLocations } from '@strudel.cycles/eval/shapeshifter.mjs';
const { pure, Pattern, Fraction, stack, slowcat, sequence, timeCat, silence, reify } = strudel;
@@ -29,10 +29,7 @@ const applyOptions = (parent) => (pat, i) => {
case 'bjorklund':
return pat.euclid(operator.arguments_.pulse, operator.arguments_.step, operator.arguments_.rotation);
case 'degradeBy':
return reify(pat)._degradeByWith(
strudel.rand.early(randOffset * _nextSeed()).segment(1),
operator.arguments_.amount,
);
return reify(pat)._degradeByWith(strudel.rand.early(randOffset * _nextSeed()).segment(1), operator.arguments_.amount);
// TODO: case 'fixed-step': "%"
}
console.warn(`operator "${operator.type_}" not implemented`);
@@ -115,9 +112,9 @@ export function patternifyAST(ast) {
return silence;
}
if (typeof ast.source_ !== 'object') {
/* if (!addMiniLocations) {
if (!addMiniLocations) {
return ast.source_;
} */
}
if (!ast.location_) {
console.warn('no location for', ast);
return ast.source_;
-2
View File
@@ -35,5 +35,3 @@ s("<bd sd> hh").osc()
```
or just [click here](http://localhost:3000/#cygiPGJkIHNkPiBoaCIpLm9zYygp)...
You can read more about [how to use Superdirt with Strudel the Tutorial](https://strudel.tidalcycles.org/tutorial/#superdirt-api)
+1 -5
View File
@@ -5,7 +5,7 @@ This program is free software: you can redistribute it and/or modify it under th
*/
import OSC from 'osc-js';
import { parseNumeral, Pattern } from '@strudel.cycles/core';
import { Pattern } from '@strudel.cycles/core';
const comm = new OSC();
comm.open();
@@ -31,10 +31,6 @@ Pattern.prototype.osc = function () {
startedAt = Date.now() - currentTime * 1000;
}
const controls = Object.assign({}, { cps, cycle, delta }, hap.value);
// make sure n and note are numbers
controls.n && (controls.n = parseNumeral(controls.n));
controls.note && (controls.note = parseNumeral(controls.note));
const keyvals = Object.entries(controls).flat();
const ts = Math.floor(startedAt + (time + latency) * 1000);
const message = new OSC.Message('/dirt/play', ...keyvals);
+2 -42
View File
@@ -1,44 +1,4 @@
# @strudel.cycles/react
This package contains react hooks and components for strudel. It is used internally by the Strudel REPL.
## Install
```js
npm i @strudel.cycles/react
```
## Usage
Here is a minimal example of how to set up a MiniRepl:
```jsx
import { evalScope } from '@strudel.cycles/eval';
import { MiniRepl } from '@strudel.cycles/react';
import controls from '@strudel.cycles/core/controls.mjs';
import { prebake } from '../repl/src/prebake.mjs';
evalScope(
controls,
import('@strudel.cycles/core'),
import('@strudel.cycles/tonal'),
import('@strudel.cycles/mini'),
import('@strudel.cycles/webaudio'),
/* probably import other strudel packages */
);
prebake();
export function Repl({ tune }) {
return <MiniRepl tune={tune} hideOutsideView={true} />;
}
```
## Development
If you change something in here and want to see the changes in the repl, make sure to run `npm run build` inside this folder!
```js
npm run dev # dev server
npm run build # build package
```
This package contains react hooks and components for strudel.
Example coming soon
+1 -1
View File
@@ -16,7 +16,7 @@ evalScope(
function App() {
return (
<div>
<MiniRepl tune={`note("c3")`} />
<MiniRepl tune={`"c3"`} />
</div>
);
}
+1
View File
@@ -1,2 +1,3 @@
import './tonal.mjs';
import './voicings.mjs';
export { addVoicings } from './voicings.mjs';
+23 -25
View File
@@ -8,29 +8,30 @@ import { Pattern as _Pattern, stack, Hap, reify } from '@strudel.cycles/core';
import _voicings from 'chord-voicings';
const { dictionaryVoicing, minTopNoteDiff, lefthand } = _voicings.default || _voicings; // parcel module resolution fuckup
const getVoicing = (chord, lastVoicing, range = ['F3', 'A4']) =>
dictionaryVoicing({
let dictionaries = {
lefthand,
};
export const addVoicings = (name, dictionary) => {
dictionaries = { ...dictionaries, [name]: dictionary };
};
const getVoicing = (chord, lastVoicing, range = ['F3', 'A4'], dictionaryName) => {
const dictionary = dictionaries[dictionaryName];
if (!dictionary) {
throw new Error(`Dictionary ${dictionaryName} not found. Try adding it with addDictionary`);
}
return dictionaryVoicing({
chord,
dictionary: lefthand,
dictionary,
range,
picker: minTopNoteDiff,
lastVoicing,
});
};
const Pattern = _Pattern;
Pattern.prototype.fmapNested = function (func) {
return new Pattern((span) =>
this.query(span)
.map((event) =>
reify(func(event))
.query(span)
.map((hap) => new Hap(event.whole, event.part, hap.value, hap.context)),
)
.flat(),
);
};
/**
* Turns chord symbols into voicings, using the smoothest voice leading possible.
* Uses [chord-voicings package](https://github.com/felixroos/chord-voicings#chord-voicings).
@@ -43,18 +44,15 @@ Pattern.prototype.fmapNested = function (func) {
* stack("<C^7 A7 Dm7 G7>".voicings(), "<C3 A2 D3 G2>").note()
*/
Pattern.prototype.voicings = function (range) {
Pattern.prototype.voicings = function (dictionaryName = 'lefthand') {
let lastVoicing;
if (!range?.length) {
// allows to pass empty array, if too lazy to specify range
range = ['F3', 'A4'];
}
return this.fmapNested((event) => {
lastVoicing = getVoicing(event.value, lastVoicing, range);
return stack(...lastVoicing)._withContext(() => ({
const range = ['F3', 'A4'];
return this.fmap((value) => {
lastVoicing = getVoicing(value, lastVoicing, range, dictionaryName);
return stack(...lastVoicing) /* ._withContext(() => ({
locations: event.context.locations || [],
}));
});
})) */;
}).outerJoin();
};
Pattern.prototype._rootNotes = function (octave = 2) {
+2 -2
View File
@@ -1,7 +1,7 @@
if (typeof AudioContext !== 'undefined') {
AudioContext.prototype.impulseResponse = function (duration, channels = 1) {
AudioContext.prototype.impulseResponse = function (duration) {
const length = this.sampleRate * duration;
const impulse = this.createBuffer(channels, length, this.sampleRate);
const impulse = this.createBuffer(2, length, this.sampleRate);
const IR = impulse.getChannelData(0);
for (let i = 0; i < length; i++) IR[i] = (2 * Math.random() - 1) * Math.pow(1 - i / length, duration);
return impulse;
+1 -15
View File
@@ -102,21 +102,7 @@ export const loadGithubSamples = async (path, nameFn) => {
*
*/
export const samples = async (sampleMap, baseUrl = sampleMap._base || '') => {
if (typeof sampleMap === 'string') {
if (sampleMap.startsWith('github:')) {
const [_, path] = sampleMap.split('github:');
sampleMap = `https://raw.githubusercontent.com/${path}/strudel.json`;
}
const base = sampleMap.split('/').slice(0, -1).join('/');
return fetch(sampleMap)
.then((res) => res.json())
.then((json) => samples(json, baseUrl || json._base || base))
.catch((error) => {
console.error(error);
throw new Error(`error loading "${sampleMap}"`);
});
}
export const samples = (sampleMap, baseUrl = sampleMap._base || '') => {
sampleCache.current = {
...sampleCache.current,
...Object.fromEntries(
+14 -24
View File
@@ -100,8 +100,12 @@ const getSoundfontKey = (s) => {
const getSampleBufferSource = async (s, n, note, speed) => {
let transpose = 0;
let midi = typeof note === 'string' ? toMidi(note) : note || 36;
transpose = midi - 36; // C3 is middle C
let midi;
if (note !== undefined) {
midi = typeof note === 'string' ? toMidi(note) : note;
transpose = midi - 36; // C3 is middle C
}
const ac = getAudioContext();
// is sample from loaded samples(..)
@@ -124,6 +128,9 @@ const getSampleBufferSource = async (s, n, note, speed) => {
if (Array.isArray(bank)) {
sampleUrl = bank[n % bank.length];
} else {
if (!note) {
throw new Error('no note(...) set for sound', s);
}
const midiDiff = (noteA) => toMidi(noteA) - midi;
// object format will expect keys as notes
const closest = Object.keys(bank)
@@ -189,8 +196,7 @@ function gainNode(value) {
node.gain.value = value;
return node;
}
const cutGroupSources = [];
const cutGroupEnvelopes = [];
const cutGroups = [];
let delays = {};
function getDelay(orbit, delaytime, delayfeedback, t) {
@@ -247,7 +253,6 @@ export const webaudioOutput = async (hap, deadline, hapDuration) => {
let {
freq,
s,
bank,
sf,
clip = 0, // if 1, samples will be cut off when the hap ends
n = 0,
@@ -283,9 +288,6 @@ export const webaudioOutput = async (hap, deadline, hapDuration) => {
gain *= velocity; // legacy fix for velocity
// the chain will hold all audio nodes that connect to each other
const chain = [];
if (bank && s) {
s = `${bank}_${s}`;
}
if (typeof s === 'string') {
[s, n] = splitSN(s, n);
}
@@ -369,26 +371,14 @@ export const webaudioOutput = async (hap, deadline, hapDuration) => {
t += nudge;
bufferSource.start(t, offset);
if (cut !== undefined) {
cutGroups[cut]?.stop(t); // fade out?
cutGroups[cut] = bufferSource;
}
chain.push(bufferSource);
bufferSource.stop(t + duration + release);
const adsr = getADSR(attack, decay, sustain, release, 1, t, t + duration);
chain.push(adsr);
if (cut !== undefined) {
const cutSource = cutGroupSources[cut];
const cutEnvelope = cutGroupEnvelopes[cut];
const fadeTime = 0.001;
if (cutEnvelope) {
// cutEnvelope.gain.cancelAndHoldAtTime(t);
cutEnvelope.gain.cancelScheduledValues(t);
cutEnvelope.gain.linearRampToValueAtTime(0, t + fadeTime);
// cutEnvelope.gain.exponentialRampToValueAtTime(0.0001, t + fadeTime);
}
if (cutSource) {
cutSource.stop(t + fadeTime);
}
cutGroupSources[cut] = bufferSource;
cutGroupEnvelopes[cut] = adsr;
}
}
// gain stage
+5 -17
View File
@@ -22,9 +22,8 @@ class CoarseProcessor extends AudioWorkletProcessor {
this.notStarted = false;
output[0][0] = input[0][0];
for (let n = 1; n < blockSize; n++) {
for (let o = 0; o < output.length; o++) {
output[o][n] = n % coarse == 0 ? input[0][n] : output[o][n - 1];
}
if (n % coarse == 0) output[0][n] = input[0][n];
else output[0][n] = output[0][n - 1];
}
}
return this.notStarted || hasInput;
@@ -53,19 +52,11 @@ class CrushProcessor extends AudioWorkletProcessor {
this.notStarted = false;
if (crush.length === 1) {
const x = Math.pow(2, crush[0] - 1);
for (let n = 0; n < blockSize; n++) {
const value = Math.round(input[0][n] * x) / x;
for (let o = 0; o < output.length; o++) {
output[o][n] = value;
}
}
for (let n = 0; n < blockSize; n++) output[0][n] = Math.round(input[0][n] * x) / x;
} else {
for (let n = 0; n < blockSize; n++) {
let x = Math.pow(2, crush[n] - 1);
const value = Math.round(input[0][n] * x) / x;
for (let o = 0; o < output.length; o++) {
output[o][n] = value;
}
output[0][n] = Math.round(input[0][n] * x) / x;
}
}
}
@@ -95,10 +86,7 @@ class ShapeProcessor extends AudioWorkletProcessor {
if (hasInput) {
this.notStarted = false;
for (let n = 0; n < blockSize; n++) {
const value = ((1 + shape) * input[0][n]) / (1 + shape * Math.abs(input[0][n]));
for (let o = 0; o < output.length; o++) {
output[o][n] = value;
}
output[0][n] = ((1 + shape) * input[0][n]) / (1 + shape * Math.abs(input[0][n]));
}
}
return this.notStarted || hasInput;
-33
View File
@@ -1,33 +0,0 @@
{
"piano": {
"A0": "A0v8.mp3",
"C1": "C1v8.mp3",
"Ds1": "Ds1v8.mp3",
"Fs1": "Fs1v8.mp3",
"A1": "A1v8.mp3",
"C2": "C2v8.mp3",
"Ds2": "Ds2v8.mp3",
"Fs2": "Fs2v8.mp3",
"A2": "A2v8.mp3",
"C3": "C3v8.mp3",
"Ds3": "Ds3v8.mp3",
"Fs3": "Fs3v8.mp3",
"A3": "A3v8.mp3",
"C4": "C4v8.mp3",
"Ds4": "Ds4v8.mp3",
"Fs4": "Fs4v8.mp3",
"A4": "A4v8.mp3",
"C5": "C5v8.mp3",
"Fs5": "Fs5v8.mp3",
"A5": "A5v8.mp3",
"C6": "C6v8.mp3",
"Ds6": "Ds6v8.mp3",
"Fs6": "Fs6v8.mp3",
"A6": "A6v8.mp3",
"C7": "C7v8.mp3",
"Ds7": "Ds7v8.mp3",
"Fs7": "Fs7v8.mp3",
"A7": "A7v8.mp3",
"C8": "C8v8.mp3"
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -4,6 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import controls from '@strudel.cycles/core/controls.mjs';
import { evalScope, evaluate } from '@strudel.cycles/eval';
import { CodeMirror, cx, flash, useHighlighting, useRepl, useWebMidi } from '@strudel.cycles/react';
import { cleanupDraw, cleanupUi, Tone } from '@strudel.cycles/tone';
@@ -14,7 +15,6 @@ import * as tunes from './tunes.mjs';
import { prebake } from './prebake.mjs';
import * as WebDirt from 'WebDirt';
import { resetLoadedSamples, getAudioContext } from '@strudel.cycles/webaudio';
import { controls } from '@strudel.cycles/core';
import { createClient } from '@supabase/supabase-js';
import { nanoid } from 'nanoid';
@@ -26,7 +26,7 @@ const supabase = createClient(
evalScope(
Tone,
controls, // sadly, this cannot be exported from core direclty
controls,
{ WebDirt },
import('@strudel.cycles/core'),
import('@strudel.cycles/tone'),
+41 -8
View File
@@ -2,16 +2,49 @@ import { Pattern, toMidi } from '@strudel.cycles/core';
import { samples } from '@strudel.cycles/webaudio';
export async function prebake({ isMock = false, baseDir = '.' } = {}) {
if (!isMock) {
samples(
{
piano: {
A0: 'A0v8.mp3',
C1: 'C1v8.mp3',
Ds1: 'Ds1v8.mp3',
Fs1: 'Fs1v8.mp3',
A1: 'A1v8.mp3',
C2: 'C2v8.mp3',
Ds2: 'Ds2v8.mp3',
Fs2: 'Fs2v8.mp3',
A2: 'A2v8.mp3',
C3: 'C3v8.mp3',
Ds3: 'Ds3v8.mp3',
Fs3: 'Fs3v8.mp3',
A3: 'A3v8.mp3',
C4: 'C4v8.mp3',
Ds4: 'Ds4v8.mp3',
Fs4: 'Fs4v8.mp3',
A4: 'A4v8.mp3',
C5: 'C5v8.mp3',
Ds4: 'Ds4v8.mp3',
Fs5: 'Fs5v8.mp3',
A5: 'A5v8.mp3',
C6: 'C6v8.mp3',
Ds6: 'Ds6v8.mp3',
Fs6: 'Fs6v8.mp3',
A6: 'A6v8.mp3',
C7: 'C7v8.mp3',
Ds7: 'Ds7v8.mp3',
Fs7: 'Fs7v8.mp3',
A7: 'A7v8.mp3',
C8: 'C8v8.mp3',
},
},
// https://archive.org/details/SalamanderGrandPianoV3
// License: CC-by http://creativecommons.org/licenses/by/3.0/ Author: Alexander Holm
samples('piano.json', `${baseDir}/piano/`);
// https://github.com/sgossner/VCSL/
// https://api.github.com/repositories/126427031/contents/
// LICENSE: CC0 general-purpose
samples('vcsl.json', 'github:sgossner/VCSL/master/');
samples('tidal-drum-machines.json', 'github:ritchse/tidal-drum-machines/main/machines/');
samples('EmuSP12.json', `${baseDir}/EmuSP12/`);
`${baseDir}/piano/`,
);
if (!isMock) {
await fetch('EmuSP12.json')
.then((res) => res.json())
.then((json) => samples(json, `${baseDir}/EmuSP12/`));
}
}
+1 -3
View File
@@ -83,9 +83,7 @@ const toneHelpersMocked = {
highpass: mockNode,
};
strudel.Pattern.prototype.osc = function () {
return this;
};
// tone mock
strudel.Pattern.prototype.tone = function () {
return this;
};
File diff suppressed because it is too large Load Diff
+9 -6
View File
@@ -4,7 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
export const tetrisMini = `note(\`[[e5 [b4 c5] d5 [c5 b4]]
export const tetrisMini = `\`[[e5 [b4 c5] d5 [c5 b4]]
[a4 [a4 c5] e5 [d5 c5]]
[b4 [~ c5] d5 e5]
[c5 a4 a4 ~]
@@ -19,7 +19,7 @@ export const tetrisMini = `note(\`[[e5 [b4 c5] d5 [c5 b4]]
[[d2 d3]*4]
[[c2 c3]*4]
[[b1 b2]*2 [e2 e3]*2]
[[a1 a2]*4]\`).slow(16)
[[a1 a2]*4]\`.slow(16)
`;
export const swimming = `stack(
@@ -80,7 +80,7 @@ export const swimming = `stack(
"[F2 A2 Bb2 B2]",
"[G2 C2 F2 F2]"
)
).note().slow(51);
).slow(51);
`;
export const giantSteps = `stack(
@@ -105,7 +105,7 @@ export const giantSteps = `stack(
"[Eb2 Bb2] [A2 D2] [G2 D2] [C#2 F#2]",
"[B2 F#2] [F2 Bb2] [Eb2 Bb3] [C#2 F#2]"
)
).slow(20).note()`;
).slow(20)`;
export const giantStepsReggae = `stack(
// melody
@@ -132,7 +132,7 @@ export const giantStepsReggae = `stack(
"[B2 F#2] [F2 Bb2] [Eb2 Bb2] [C#2 F#2]"
)
.struct("x ~".fast(4*8))
).slow(25).note()`;
).slow(25)`;
export const zeldasRescue = `stack(
// melody
@@ -511,7 +511,7 @@ stack(
f3!2 e3!2 ab3!2 ~!2
>\`
.legato(.5)
).fast(2).note()`;
).fast(2) // .note().piano()`;
/*
// TODO: does not work on linux (at least for me..)
@@ -554,6 +554,7 @@ stack(
"<D2 A2 G2 F2>".euclidLegato(6,8,1).note().s('bass').clip(1).gain(.8)
)
.slow(6)
.pianoroll({minMidi:20,maxMidi:120,background:'transparent'})
`;
@@ -700,6 +701,7 @@ stack(
.echoWith(4,.125,(x,n)=>x.gain(.15*1/(n+1))) // echo notes
//.hush()
)
.slow(3/2)`;
export const swimmingWithSoundfonts = `stack(
@@ -812,6 +814,7 @@ x=>x.add(7).color('steelblue')
//.hcutoff(400)
.clip(1)
.stack(s("bd:1*2,~ sd:0,[~ hh:0]*2"))
.pianoroll({vertical:1})`;
export const bossaRandom = `const chords = "<Am7 Am7 Dm7 E7>"
File diff suppressed because it is too large Load Diff
-15
View File
@@ -1,15 +0,0 @@
import { queryCode } from '../../repl/src/runtime.mjs';
import { describe, it } from 'vitest';
import doc from '../../doc.json';
describe('runs examples', () => {
const { docs } = doc;
docs.forEach(async (doc) => {
doc.examples?.forEach((example, i) => {
it(`example "${doc.name}" example index ${i}`, async ({ expect }) => {
const haps = await queryCode(example, 4);
expect(haps).toMatchSnapshot();
});
});
});
});