Compare commits

..

52 Commits

Author SHA1 Message Date
Tijmen Zwaan 4b82e01b69 Split pattern.mjs into multiple files 2026-12-04 08:09:19 +01:00
Tijmen Zwaan 5603c58a9a Remove outdated snapshots 2026-12-04 04:02:26 +01:00
tzwaan 7a1075b746 Merge pull request 'Fix scheduler comments' (#2225) from fix-scheduler-comments into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2225
2026-12-04 03:51:06 +01:00
Tijmen Zwaan 34b7a81c8b Fix scheduler comments 2026-12-04 03:49:40 +01:00
tzwaan b30e3ad88f Merge pull request 'Fix Longnames in Jsdocs and document more functions' (#2220) from Orasund/strudel:fix-longnames-in-jsdoc into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2220
2026-12-04 03:47:59 +01:00
Orasund 70b44f6694 add tests for pick 2026-12-04 02:24:02 +01:00
Orasund fdc5db6b9b Merge branch 'main' into fix-longnames-in-jsdoc 2026-12-04 02:00:23 +01:00
Orasund b49981aea6 apply suggestions 2026-12-04 01:59:26 +01:00
tzwaan 0c38bfaf99 Merge pull request 'Propagate exceptions in test and fix some bugs' (#2224) from propagate-exceptions-in-tests into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2224
2026-12-04 00:26:00 +01:00
Tijmen Zwaan d6ce044ccb rename controls.testRun to controls.propagateExceptions 2026-12-03 23:38:51 +01:00
Tijmen Zwaan 255314f7fa Fix Hap filterHaps example 2026-12-03 23:30:53 +01:00
Tijmen Zwaan acf4628a16 Fix getCurrentKeyboardState if window is not defined (e.g. in tests) 2026-12-03 23:23:54 +01:00
Tijmen Zwaan 2a35745f73 Allow exceptions to propagate in testRuns 2026-12-03 23:23:20 +01:00
tzwaan 787f44bb38 Merge pull request 'Add secondsPer signal' (#2221) from seconds-per into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2221
2026-12-03 21:05:06 +01:00
Orasund dc1fe808c0 fix pages 2026-12-03 18:40:11 +01:00
Orasund a61418c54c apply suggestions 2026-12-03 17:58:49 +01:00
alex 2feba92516 merge 2026-12-03 16:45:32 +00:00
Orasund 2b001170de Merge branch 'main' into fix-longnames-in-jsdoc 2026-12-03 17:42:57 +01:00
Alex McLean fe06a1e59e Merge pull request 'Fix fm synth' (#2070) from wrightwriter/strudel:fm-fix into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2070
2026-12-03 17:39:19 +01:00
Alex McLean a4b83a364b Merge branch 'main' into fm-fix 2026-12-03 17:33:42 +01:00
Alex McLean 1d8d0dae8c Merge pull request 'goabd synth (goa trance kick)' (#2084) from pulu/strudel:goabd into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2084
2026-12-03 17:21:57 +01:00
Alex McLean d3a6cef369 Merge pull request 'Update undocumented.mjs script' (#2172) from aschultz/strudel-dev:users/aschultz/docs into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2172
2026-12-03 17:03:09 +01:00
Alex McLean d0de54a880 Merge branch 'main' into users/aschultz/docs 2026-12-03 17:02:10 +01:00
Alex McLean d1a4c3c60e Merge branch 'main' into goabd 2026-12-03 16:59:32 +01:00
miranda 118de38551 implement goabd synth 2026-12-03 17:52:24 +02:00
Alex McLean 8bde1314c5 Merge pull request 'cleanup: Remove unrelated npmjs mondo dependency' (#1925) from robojumper/strudel:cleanup/unneeded-mondo-dependency into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/1925
2026-12-03 15:38:22 +01:00
Alex McLean f13dbe00e1 Merge branch 'main' into cleanup/unneeded-mondo-dependency 2026-12-03 15:34:26 +01:00
Alex McLean 68598a674b Merge pull request 'Doc fixes from #1270 by @matthewkaney' (#2223) from pr-1270-doc into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2223
2026-12-03 12:39:21 +01:00
alex db2835c5cb delint 2026-12-03 11:36:33 +00:00
alex f92d6a0a03 doc fixes from #1270 by @matthewkaney 2026-12-03 11:33:30 +00:00
Alex McLean 31730842a7 Merge pull request 'Update AGENTS.md - discourage LLMs from accessing codeberg.org' (#2222) from yaxu-patch-2 into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2222
2026-12-03 10:57:10 +01:00
Orasund b1b026b56c add snapshot for new test of beat 2026-12-03 05:16:43 +01:00
Orasund 49926243f6 codeformat 2026-12-03 05:10:52 +01:00
Orasund b298ac7b53 fix regression test for beat 2026-12-03 05:10:16 +01:00
Tijmen Zwaan cd7c88e768 Add secondsPer signal 2026-12-03 05:03:17 +01:00
Orasund 4694c59d74 add __beat back in 2026-12-02 21:30:39 +01:00
Orasund 9e00181020 fix tests 2026-12-02 21:27:07 +01:00
Orasund ad98f1050d enable jsdoc/require-description again 2026-12-02 20:59:14 +01:00
Orasund e1e156296a formatting 2026-12-02 20:30:32 +01:00
Orasund 4db94e163c document beat 2026-12-02 20:30:04 +01:00
Orasund 438eb553bd add beat 2026-12-02 19:28:32 +01:00
Orasund 379c075d56 Merge branch 'main' into fix-longnames-in-jsdoc 2026-12-02 06:28:21 +01:00
Orasund 6e550f5a6c Add some more definitions 2026-12-01 16:06:05 +01:00
Orasund 96f8c545ae Add @global annotations 2026-12-01 10:31:29 +01:00
Orasund 08e9e3893e document more functions 2026-11-29 22:56:22 +01:00
Orasund 9e5e172931 fix more longnames 2026-11-26 17:45:15 +01:00
Orasund 1f5b8d6bcc Fix JsDoc Longnames 2026-11-26 11:56:58 +01:00
aschultz 5f88fab5d0 Formatting 2026-11-04 16:58:18 -08:00
aschultz 207fa00eac Update undocumented script to use latest ECMA version, generate Posix paths for the keys even on Windows, and skip processing .json files. 2026-11-04 16:53:45 -08:00
wright 88b7d14487 Fix fm synth 2026-06-16 22:40:19 +03:00
wright 3ac25f7960 Add ctrl-shift-z as shortcut for redo 2026-06-15 20:15:59 +03:00
robojumper 8b3ae4c514 Remove unrelated npmjs mondo dependency 2026-01-17 16:19:21 +01:00
72 changed files with 5217 additions and 3809 deletions
+4 -4
View File
@@ -1,22 +1,22 @@
import { queryCode, testCycles } from '../test/runtime.mjs';
import * as tunes from '../website/src/repl/tunes.mjs';
import { describe, bench } from 'vitest';
import { calculateSteps } from '../packages/core/index.mjs';
import { setCalculateSteps } from '../packages/core/index.mjs';
const tuneKeys = Object.keys(tunes);
describe('renders tunes', () => {
tuneKeys.forEach((key) => {
describe(key, () => {
calculateSteps(true);
setCalculateSteps(true);
bench(`+steps`, async () => {
await queryCode(tunes[key], testCycles[key] || 1);
});
calculateSteps(false);
setCalculateSteps(false);
bench(`-steps`, async () => {
await queryCode(tunes[key], testCycles[key] || 1);
});
calculateSteps(true);
setCalculateSteps(true);
});
});
});
+14 -2
View File
@@ -95,6 +95,7 @@ export default [
},
},
jsdoc({
files: ['packages/**/*.{js,mjs}'],
config: 'flat/recommended-error',
rules: {
'jsdoc/no-undefined-types': [
@@ -111,13 +112,18 @@ export default [
comment:
'JsdocBlock:has(JsdocTag[tag="memberof"]:not([name=/\\.prototype(?:\\s|$)/]):not([description=/\\.prototype(?:\\s|$)/]))',
context: 'any',
message: "Use '@memberof <Name>.prototype'. Without, it's considered a static function.",
message: "Use '@memberof <Name>.prototype' instead.",
},
{
context: 'FunctionDeclaration',
comment: 'JsdocBlock:not(:has(JsdocTag[tag=/^(global|memberof)$/]))',
message: 'JSDoc block should be explicitly labeled as @global or @memberof.',
},
],
},
],
'jsdoc/require-description': 'error',
'jsdoc/no-defaults': 0, //removes defaults with not alternative
'jsdoc/no-defaults': 0, //removes defaults with no alternative
'jsdoc/require-jsdoc': 0,
'jsdoc/tag-lines': 0,
'jsdoc/require-returns-description': 0,
@@ -129,4 +135,10 @@ export default [
'jsdoc/reject-function-type': 0,
},
}),
jsdoc({
files: ['packages/core/**/*.{js,mjs}', 'packages/pattern/**/*.{js,mjs}'],
rules: {
'jsdoc/require-jsdoc': ['warn', { publicOnly: {}, enableFixer: false }],
},
}),
];
+17 -9
View File
@@ -1,16 +1,19 @@
import { readFile } from 'node:fs/promises';
import { dirname, resolve } from 'path';
import { dirname, resolve, win32, posix } from 'path';
import { fileURLToPath } from 'url';
import { parse } from 'acorn';
import dependencyTree from 'dependency-tree';
import { platform } from 'node:process';
const __dirname = dirname(fileURLToPath(import.meta.url));
const packageRoot = resolve(__dirname, '..');
function getExports(code) {
// parse it with acorn
let ast;
try {
ast = parse(code, {
ecmaVersion: 11,
ecmaVersion: 'latest',
sourceType: 'module',
});
} catch (err) {
@@ -64,21 +67,26 @@ async function getUndocumented(path, docs) {
}
}
function getPackageRelativePosixPath(path) {
path = path.replace(packageRoot, '');
if (platform === 'win32') {
path = path.replaceAll(win32.sep, posix.sep);
}
return path;
}
// read doc.json file
const { docs } = JSON.parse(await readFile(resolve(__dirname, '..', 'doc.json'), 'utf8'));
const excludedFileTypes = /\.json$/;
const paths = dependencyTree.toList({
filename: 'index.mjs',
// filename: 'packages/core/index.mjs',
directory: resolve(__dirname),
filter: (path) => !path.includes('node_modules'),
directory: packageRoot,
filter: (path) => !path.includes('node_modules') && !excludedFileTypes.test(path),
});
// const paths = ['../packages/core/pattern.mjs', '../packages/core/hap.mjs'].map((rel) => resolve(__dirname, rel));
const undocumented = Object.fromEntries(
await Promise.all(
paths.map(async (path) => [path.replace(resolve(__dirname, '..'), ''), await getUndocumented(path, docs)]),
),
await Promise.all(paths.map(async (path) => [getPackageRelativePosixPath(path), await getUndocumented(path, docs)])),
);
console.log(JSON.stringify(undocumented, null, 2));
+6 -1
View File
@@ -1,5 +1,5 @@
import { closeBrackets } from '@codemirror/autocomplete';
import { indentWithTab } from '@codemirror/commands';
import { indentWithTab, toggleLineComment, redo } from '@codemirror/commands';
import { javascript, javascriptLanguage } from '@codemirror/lang-javascript';
import { bracketMatching, defaultHighlightStyle, syntaxHighlighting } from '@codemirror/language';
import { Compartment, EditorState, Prec } from '@codemirror/state';
@@ -112,6 +112,10 @@ export function initEditor({ initialCode = '', onChange, onEvaluate, onStop, roo
key: 'Alt-Enter',
run: () => onEvaluate?.(),
},
{
key: 'Ctrl-Shift-z',
run: redo,
},
{
key: 'Ctrl-.',
run: () => onStop?.(),
@@ -400,6 +404,7 @@ function s4() {
* Overrides the css of highlighted events. Make sure to use single quotes!
* @name markcss
* @tags visualization
* @memberof Pattern.prototype
* @example
* note("c a f e")
* .markcss('text-decoration:underline')
File diff suppressed because it is too large Load Diff
+22
View File
@@ -13,6 +13,28 @@ import {
setClockTime,
} from './schedulerState.mjs';
/**
* Creates a new Repl
* @global
* @param {object} options
* @param {*} options.onSchedule
* @param {*} options.defaultOutput
* @param {*} options.onEvalError
* @param {*} options.beforeEval
* @param {*} options.beforeStart
* @param {*} options.afterEval
* @param {*} options.getTime
* @param {*} options.transpiler
* @param {*} options.onToggle
* @param {*} options.editPattern
* @param {*} options.onUpdateState
* @param {*} options.sync = false
* @param {*} options.setInterval
* @param {*} options.clearInterval
* @param {*} options.id
* @param {*} options.mondo = false
* @returns {object}
*/
export function repl({
onSchedule,
defaultOutput,
+45
View File
@@ -12,6 +12,7 @@ let isStarted;
/**
* Get the current cycle time as a number
* @global
* @name getTime
* @tags internals
* @returns {number}
@@ -23,6 +24,12 @@ export function getTime() {
return time();
}
/**
* define how the cycle time should be computed
* @global
* @param {function():number} func
* @tags internals
*/
export function setTime(func) {
time = func;
}
@@ -30,6 +37,7 @@ export function setTime(func) {
let clockTime;
/**
* Get the current clock time in seconds (onSchedule time)
* @global
* @name getClockTime
* @tags internals
* @returns {number}
@@ -41,16 +49,28 @@ export function getClockTime() {
return clockTime();
}
/**
* define how the clock time should be computed
* @global
* @param {function():number} func
*/
export function setClockTime(func) {
clockTime = func;
}
/**
* define how Cycles per seconds are computed
* @global
* @tags internals
* @param {function():number} func
*/
export function setCpsFunc(func) {
cpsFunc = func;
}
/**
* Get the current cycles per second
* @global
* @name getCps
* @tags internals
* @returns {number}
@@ -59,26 +79,51 @@ export function getCps() {
return cpsFunc?.();
}
/**
* Set the currently running pattern
* @param {Pattern} pat
*/
export function setPattern(pat) {
pattern = pat;
}
/**
* Get the currently running pattern
* @returns {Pattern}
*/
export function getPattern() {
return pattern;
}
/**
* Set the function that applies a function for a given time and cps
* @param {function(Pattern,number,number)} func
*/
export function setScheduleFunc(func) {
scheduleFunc = func;
}
/**
* Gets the function that applies a function for a given time and cps
* @returns {function(Pattern,number,number)} taking a Pattern, the current time and cps as inputs
*/
export function getScheduleFunc() {
return scheduleFunc;
}
/**
* start/stop the scheduler
* @param {boolean | undefined} val
*/
export function setIsStarted(val) {
isStarted = !!val;
}
/**
* Has the scheduler started?
In the repl, this returns true only after the full pattern code has successfully executed without errors, including any prebake files, or if the scheduler was already running from a previous pattern update.
* @returns {boolean}
*/
export function getIsStarted() {
return isStarted;
}
+13
View File
@@ -1,6 +1,19 @@
// will move to https://github.com/felixroos/zyklus
// TODO: started flag
/**
* Creates a Web Audio Clock
* @global
* @param {Function} getTime
* @param {Function} callback
* @param {number} [duration]
* @param {number} [interval]
* @param {number} [overlap]
* @param {Function} [setInterval]
* @param {Function} [clearInterval]
* @param {boolean} round
* @returns {object}
*/
function createClock(
getTime,
callback, // called slightly before each cycle
+1
View File
@@ -308,6 +308,7 @@ Pattern.prototype.punchcard = function (options) {
* @name wordfall
* @tags visualization
* @returns {Pattern}
* @memberof Pattern.prototype
*/
Pattern.prototype.wordfall = function (options) {
return this.punchcard({ vertical: 1, labels: 1, stroke: 0, fillActive: 1, active: 'white', ...options });
+6 -2
View File
@@ -113,6 +113,7 @@ function githubPath(base, subpath = '') {
/**
* configures the default midimap, which is used when no "midimap" port is set
* @global
* @param {*} mapping
* @tags external_io, midi
* @example
@@ -128,6 +129,7 @@ let loadCache = {};
/**
* Adds midimaps to the registry. Inside each midimap, control names (e.g. lpf) are mapped to cc numbers.
* @global
* @param {string | object} map
* @tags external_io, midi
* @example
@@ -484,6 +486,7 @@ Pattern.prototype.midi = function (midiport, options = {}) {
/**
* Initialize a midi input device
* @global
* @param {string} input
* @returns {MidiInput}
*/
@@ -526,9 +529,10 @@ const midiInputs = {};
* The output is a function that accepts a midi cc value to query as well as (optionally) a midi channel
*
* @name midin
* @global
* @tags external_io, midi
* @param {string | number} input MIDI device name or index defaulting to 0
* @returns {function(number, number=): Pattern} A function from (cc, channel?) to a pattern.
* @returns {Promise<function(number, number=): Pattern>} A function from (cc, channel?) to a pattern.
* When queried, the pattern will produces the most recently received midi value (normalized to 0 to 1)
* that came through that cc number (and channel, if provided)
* @example
@@ -558,7 +562,7 @@ export async function midin(input) {
* @name midikeys
* @tags external_io, midi
* @param {string | number} input MIDI device name or index defaulting to 0
* @returns {function((number | Pattern)=): Pattern} A function that produces a pattern.
* @returns {Promise<function((number | Pattern)=): Pattern>} A function that produces a pattern.
* When queried, the pattern will produces the most recently played midi notes and velocities,
* lasting for the specified duration
* @example
+2
View File
@@ -8,6 +8,7 @@ import { Input, Output } from 'webmidi';
/**
* Get a string listing device names for error messages.
* @global
* @param {Input[] | Output[]} devices
* @returns {string}
*/
@@ -18,6 +19,7 @@ export function getMidiDeviceNamesString(devices) {
/**
* Look up a device by index or name. Otherwise return a default device, or fail if none are connected.
*
* @global
* @param {string | number} indexOrName
* @param {Input[] | Output[]} devices
* @returns {Input | Output | undefined}
+4 -4
View File
@@ -1,10 +1,10 @@
import { describe, bench } from 'vitest';
import { calculateSteps } from '@strudel/pattern';
import { setCalculateSteps } from '@strudel/pattern';
import { mini } from '../index.mjs';
describe('mini', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -13,7 +13,7 @@ describe('mini', () => {
{ time: 1000 },
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -21,5 +21,5 @@ describe('mini', () => {
},
{ time: 1000 },
);
calculateSteps(true);
setCalculateSteps(true);
});
-1
View File
@@ -37,7 +37,6 @@
"mondolang": "workspace:*"
},
"devDependencies": {
"mondo": "*",
"vite": "^6.0.11",
"vitest": "^3.0.4"
},
+15 -15
View File
@@ -5,7 +5,7 @@ import { signal } from '@strudel/core';
/**
* The accelerometer's x-axis value ranges from 0 to 1.
* @name accelerationX
* @returns {Pattern}
* @type {Pattern}
* @synonyms accX
* @tags external_io
* @example
@@ -16,7 +16,7 @@ import { signal } from '@strudel/core';
/**
* The accelerometer's y-axis value ranges from 0 to 1.
* @name accelerationY
* @returns {Pattern}
* @type {Pattern}
* @synonyms accY
* @tags external_io
* @example
@@ -27,7 +27,7 @@ import { signal } from '@strudel/core';
/**
* The accelerometer's z-axis value ranges from 0 to 1.
* @name accelerationZ
* @returns {Pattern}
* @type {Pattern}
* @synonyms accZ
* @tags external_io
* @example
@@ -38,7 +38,7 @@ import { signal } from '@strudel/core';
/**
* The device's gravity x-axis value ranges from 0 to 1.
* @name gravityX
* @returns {Pattern}
* @type {Pattern}
* @synonyms gravX
* @tags external_io
* @example
@@ -49,7 +49,7 @@ import { signal } from '@strudel/core';
/**
* The device's gravity y-axis value ranges from 0 to 1.
* @name gravityY
* @returns {Pattern}
* @type {Pattern}
* @synonyms gravY
* @tags external_io
* @example
@@ -60,7 +60,7 @@ import { signal } from '@strudel/core';
/**
* The device's gravity z-axis value ranges from 0 to 1.
* @name gravityZ
* @returns {Pattern}
* @type {Pattern}
* @synonyms gravZ
* @tags external_io
* @example
@@ -71,7 +71,7 @@ import { signal } from '@strudel/core';
/**
* The device's rotation around the alpha-axis value ranges from 0 to 1.
* @name rotationAlpha
* @returns {Pattern}
* @type {Pattern}
* @synonyms rotA, rotZ, rotationZ
* @tags external_io
* @example
@@ -82,7 +82,7 @@ import { signal } from '@strudel/core';
/**
* The device's rotation around the beta-axis value ranges from 0 to 1.
* @name rotationBeta
* @returns {Pattern}
* @type {Pattern}
* @synonyms rotB, rotX, rotationX
* @tags external_io
* @example
@@ -93,7 +93,7 @@ import { signal } from '@strudel/core';
/**
* The device's rotation around the gamma-axis value ranges from 0 to 1.
* @name rotationGamma
* @returns {Pattern}
* @type {Pattern}
* @synonyms rotG, rotY, rotationY
* @tags external_io
* @example
@@ -104,7 +104,7 @@ import { signal } from '@strudel/core';
/**
* The device's orientation alpha value ranges from 0 to 1.
* @name orientationAlpha
* @returns {Pattern}
* @type {Pattern}
* @synonyms oriA, oriZ, orientationZ
* @tags external_io
* @example
@@ -115,7 +115,7 @@ import { signal } from '@strudel/core';
/**
* The device's orientation beta value ranges from 0 to 1.
* @name orientationBeta
* @returns {Pattern}
* @type {Pattern}
* @synonyms oriB, oriX, orientationX
* @tags external_io
* @example
@@ -126,7 +126,7 @@ import { signal } from '@strudel/core';
/**
* The device's orientation gamma value ranges from 0 to 1.
* @name orientationGamma
* @returns {Pattern}
* @type {Pattern}
* @synonyms oriG, oriY, orientationY
* @tags external_io
* @example
@@ -137,7 +137,7 @@ import { signal } from '@strudel/core';
/**
* The device's absolute orientation alpha value ranges from 0 to 1.
* @name absoluteOrientationAlpha
* @returns {Pattern}
* @type {Pattern}
* @synonyms absOriA, absOriZ, absoluteOrientationZ
* @tags external_io
* @example
@@ -148,7 +148,7 @@ import { signal } from '@strudel/core';
/**
* The device's absolute orientation beta value ranges from 0 to 1.
* @name absoluteOrientationBeta
* @returns {Pattern}
* @type {Pattern}
* @synonyms absOriB, absOriX, absoluteOrientationX
* @tags external_io
* @example
@@ -159,7 +159,7 @@ import { signal } from '@strudel/core';
/**
* The device's absolute orientation gamma value ranges from 0 to 1.
* @name absoluteOrientationGamma
* @returns {Pattern}
* @type {Pattern}
* @synonyms absOriG, absOriY, absoluteOrientationY
* @tags external_io
* @example
+6 -6
View File
@@ -1,11 +1,11 @@
import { describe, bench } from 'vitest';
import { calculateSteps, sequence, stack } from '../index.mjs';
import { setCalculateSteps, sequence, stack } from '../index.mjs';
const pat64 = sequence(...Array(64).keys());
describe('steps', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -14,7 +14,7 @@ describe('steps', () => {
{ time: 1000 },
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -25,7 +25,7 @@ describe('steps', () => {
});
describe('stack', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -34,7 +34,7 @@ describe('stack', () => {
{ time: 1000 },
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -43,4 +43,4 @@ describe('stack', () => {
{ time: 1000 },
);
});
calculateSteps(true);
setCalculateSteps(true);
+6 -6
View File
@@ -1,13 +1,13 @@
import { describe, bench } from 'vitest';
import { calculateSteps, rand, useRNG } from '../index.mjs';
import { setCalculateSteps, rand, useRNG } from '../index.mjs';
const testingResolution = 128;
const _generateRandomPattern = () => rand.iter(testingResolution).fast(testingResolution).firstCycle();
describe('old random', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -22,7 +22,7 @@ describe('old random', () => {
},
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -39,11 +39,11 @@ describe('old random', () => {
});
describe('random', () => {
calculateSteps(true);
setCalculateSteps(true);
bench('+tactus', _generateRandomPattern, { time: 1000 });
calculateSteps(false);
setCalculateSteps(false);
bench('-tactus', _generateRandomPattern, { time: 1000 });
});
calculateSteps(true);
setCalculateSteps(true);
+2 -1
View File
@@ -15,10 +15,11 @@ import Fraction, { gcd } from './fraction.mjs';
* - "-" hold previous value
* - "." silence
*
* @tags visualization
* @tags internal, visualization
* @param {Pattern} pat the pattern to use
* @param {number} chars max number of characters (approximately)
* @returns {string}
* @global
* @example
* const line = drawLine("0 [1 2 3]", 10); // |0--123|0--123
* console.log(line);
+5 -2
View File
@@ -10,9 +10,12 @@ https://rohandrape.net/?t=hmt
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 { timeCat, register, silence, stack, pure, _morph } from './pattern.mjs';
import { silence } from './pattern-atoms.mjs';
import { register } from './register.mjs';
import { timeCat } from './pattern-stepwise.mjs';
import { _morph } from './pattern-structural-temporal.mjs';
import { rotate, flatten, splitAt, zipWith } from './util.mjs';
import Fraction, { lcm } from './fraction.mjs';
import Fraction from './fraction.mjs';
const left = function (n, x) {
const [ons, offs] = n;
+2 -3
View File
@@ -32,9 +32,8 @@ export class Hap {
*
* @example
* // Keep only haps whose full `whole` timespan is at least half a cycle long
* s("bd*8")
* .slow(2)
* .filterHaps((hap) => hap.whole !== undefined && hap.whole.span.duration() >= 0.5);
* s("bd, sd*2, hh*4")
* .filterHaps((hap) => hap.whole !== undefined && hap.whole.duration >= 0.5);
*
* @example
* // Keep only haps that begin within the first half of a cycle
+3 -1
View File
@@ -4,7 +4,9 @@ Copyright (C) 2025 Strudel contributors - see <https://codeberg.org/uzu/strudel/
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 { register, reify, Pattern } from './pattern.mjs';
import { Pattern } from './pattern.mjs';
import { reify } from './pattern-atoms.mjs';
import { register } from './register.mjs';
let timelines = {};
+11
View File
@@ -12,6 +12,17 @@ export * from './hap.mjs';
export * from './impure.mjs';
export * from './logger.mjs';
export * from './pattern.mjs';
export * from './register.mjs';
export * from './pattern-composers.mjs';
export * from './pattern-combiners.mjs';
export * from './pattern-chords.mjs';
export * from './pattern-structural-temporal.mjs';
export * from './pattern-numerical.mjs';
export * from './pattern-atoms.mjs';
export * from './pattern-multi.mjs';
export * from './pattern-misc.mjs';
export * from './pattern-stepwise.mjs';
export * from './pattern-deprecated.mjs';
export * from './pick.mjs';
export * from './signal.mjs';
export * from './state.mjs';
+6
View File
@@ -4,6 +4,12 @@ let debounce = 1000,
lastMessage,
lastTime;
/**
* Logs an error to the system and/or Strudel REPL console.
* @global
* @param {*} e
* @param {string} origin
*/
export function errorLogger(e, origin = 'cyclist') {
if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {
console.error(e);
+81
View File
@@ -0,0 +1,81 @@
/*
pattern-atoms.mjs - The most basic pattern construction functions
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-atoms.mjs>
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 Hap from './hap.mjs';
import Fraction from './fraction.mjs';
import { Pattern, isPattern } from './pattern.mjs';
/**
* Does absolutely nothing, but with a given metrical 'steps'
* @name gap
* @tags generators
* @param {number} steps
* @returns {Pattern}
* @example
* gap(3) // "~@3"
*/
export const gap = (steps) => new Pattern(() => [], steps);
/**
* Does absolutely nothing..
* @name silence
* @tags generators
* @example
* silence // "~"
*/
export const silence = gap(1);
/**
* Like silence, but with a 'steps' (relative duration) of 0
* @name nothing
* @tags generators
* @example
* nothing
*/
export const nothing = gap(0);
/**
* A discrete value that repeats once per cycle.
*
* @global
* @param {number} value
* @tags generators
* @returns {Pattern}
* @example
* pure('e4') // "e4"
* @noAutocomplete
*/
export function pure(value) {
function query(state) {
return state.span.spanCycles.map((subspan) => new Hap(Fraction(subspan.begin).wholeCycle(), subspan, value));
}
const result = new Pattern(query, 1);
result.__pure = value;
return result;
}
let stringParser;
// parser is expected to turn a string into a pattern
// if set, the reify function will parse all strings with it
// intended to use with mini to automatically interpret all strings as mini notation
export const setStringParser = (parser) => (stringParser = parser);
/**
* Turns something into a pattern via pure(), unless it's already a pattern. If a string parser is set via {@link setStringParser}, that is used to reify strings.
* @param {*} thing
* @returns {Pattern}
*/
export function reify(thing) {
// Turns something into a pattern, unless it's already a pattern
if (isPattern(thing)) {
return thing;
}
if (stringParser && typeof thing === 'string') {
return stringParser(thing);
}
return pure(thing);
}
+70
View File
@@ -0,0 +1,70 @@
/*
pattern-chords.mjs - Functions related to chords/patterns of lists/lists of patterns
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-chords.mjs>
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 Hap from './hap.mjs';
import { Pattern } from './pattern.mjs';
import { reify } from './pattern-atoms.mjs';
import { register } from './register.mjs';
import { _mod } from './util.mjs';
//////////////////////////////////////////////////////////////////////
// functions relating to chords/patterns of lists/lists of patterns
// returns Array<Hap[]> where each list of haps satisfies eq
function groupHapsBy(eq, haps) {
let groups = [];
haps.forEach((hap) => {
const match = groups.findIndex(([other]) => eq(hap, other));
if (match === -1) {
groups.push([hap]);
} else {
groups[match].push(hap);
}
});
return groups;
}
// congruent haps = haps with equal spans
const congruent = (a, b) => a.spanEquals(b);
// Pattern<Hap<T>> -> Pattern<Hap<T[]>>
// returned pattern contains arrays of congruent haps
Pattern.prototype.collect = function () {
return this.withHaps((haps) =>
groupHapsBy(congruent, haps).map((_haps) => new Hap(_haps[0].whole, _haps[0].part, _haps, {})),
);
};
/**
* Selects indices in in stacked notes.
* @tags temporal
* @name arpWith
* @memberof Pattern.prototype
* @example
* note("<[c,eb,g]!2 [c,f,ab] [d,f,ab]>")
* .arpWith(haps => haps[2])
* */
export const arpWith = register('arpWith', (func, pat) => {
return pat
.collect()
.fmap((v) => reify(func(v)))
.innerJoin()
.withHap((h) => new Hap(h.whole, h.part, h.value.value, h.combineContext(h.value)));
});
/**
* Selects indices in in stacked notes.
* @tags temporal
* @name arp
* @memberof Pattern.prototype
* @example
* note("<[c,eb,g]!2 [c,f,ab] [d,f,ab]>")
* .arp("0 [0,2] 1 [0,2]")
* */
export const arp = register(
'arp',
(indices, pat) => pat.arpWith((haps) => reify(indices).fmap((i) => haps[_mod(i, haps.length)])),
false,
);
+263
View File
@@ -0,0 +1,263 @@
/*
pattern-combiners.mjs - Functions that combine multiple patterns into a single pattern
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-combiners.mjs>
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 Fraction, { lcm } from './fraction.mjs';
import { getCalculateSteps, Pattern } from './pattern.mjs';
import { reify, silence, pure } from './pattern-atoms.mjs';
import { _mod, flatten, curry } from './util.mjs';
import { errorLogger } from './logger.mjs';
/**
* The given items are played at the same time at the same length.
*
* @param {...any} pats
* @tags combiners
* @returns {Pattern}
* @name stack
* @memberof Pattern.prototype
* @synonyms polyrhythm, pr
* @example
* stack("g3", "b3", ["e4", "d4"]).note()
* // "g3,b3,[e4 d4]".note()
*
* @example
* // As a chained function:
* s("hh*4").stack(
* note("c4(5,8)")
* )
*/
export function stack(...pats) {
// Array test here is to avoid infinite recursions..
pats = pats.map((pat) => (Array.isArray(pat) ? sequence(...pat) : reify(pat)));
const query = (state) =>
flatten(
pats.map((pat) => {
if (state.controls.propagateExceptions) {
// In tests, we want exceptions to propagate to actually catch problems
// and to see the proper stack trace in the test result.
return pat.query(state);
} else {
try {
// An error occurring in one part of the stack should not break
// playback of the other parts of the stack.
return pat.query(state);
} catch (e) {
errorLogger(e);
return [];
}
}
}),
);
const result = new Pattern(query);
if (getCalculateSteps()) {
result._steps = lcm(...pats.map((pat) => pat._steps));
}
return result;
}
// aliases
export const polyrhythm = stack;
export const pr = stack;
/**
* Layers the result of the given function(s). Like `superimpose`, but without the original pattern:
* @param {...any} funcs
* @name layer
* @tags combiners
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* "<0 2 4 6 ~ 4 ~ 2 0!3 ~!5>*8"
* .layer(x=>x.add("0,2"))
* .scale('C minor').note()
*/
Pattern.prototype.layer = function (...funcs) {
return stack(...funcs.map((func) => func(this)));
};
/**
* Superimposes the result of the given function(s) on top of the original pattern:
* @param {...any} funcs
* @name superimpose
* @tags combiners
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* "<0 2 4 6 ~ 4 ~ 2 0!3 ~!5>*8"
* .superimpose(x=>x.add(2))
* .scale('C minor').note()
*/
Pattern.prototype.superimpose = function (...funcs) {
return this.stack(...funcs.map((func) => func(this)));
};
/**
* Takes a list of patterns, and returns a pattern of lists.
* @global
* @param {Pattern[]} pats
* @returns {Pattern}
* @tags temporal
*/
export function sequenceP(pats) {
let result = pure([]);
for (const pat of pats) {
result = result.bind((list) => pat.fmap((v) => list.concat([v])));
}
return result;
}
export function sequence(...pats) {
return fastcat(...pats);
}
/** Like **cat**, but the items are crammed into one cycle.
* @tags combiners
* @synonyms fastcat, sequence
* @example
* seq("e5", "b4", ["d5", "c5"]).note()
* // "e5 b4 [d5 c5]".note()
*
* @example
* // As a chained function:
* s("hh*4").seq(
* note("c4(5,8)")
* )
*/
export function seq(...pats) {
return fastcat(...pats);
}
/**
* Concatenation: combines a list of patterns, switching between them successively, one per cycle.
*
* @param {...any} pats
* @tags combiners
* @returns {Pattern}
* @synonyms cat
* @example
* slowcat("e5", "b4", ["d5", "c5"])
*
*/
export function slowcat(...pats) {
// Array test here is to avoid infinite recursions..
pats = pats.map((pat) => (Array.isArray(pat) ? fastcat(...pat) : reify(pat)));
if (!pats.length) {
return silence;
} else if (pats.length == 1) {
return pats[0];
}
const query = function (state) {
const span = state.span;
const pat_n = _mod(span.begin.sam(), pats.length);
const pat = pats[pat_n];
// A bit of maths to make sure that cycles from constituent patterns aren't skipped.
// For example if three patterns are slowcat-ed, the fourth cycle of the result should
// be the second (rather than fourth) cycle from the first pattern.
const offset = span.begin.floor().sub(span.begin.div(pats.length).floor());
return pat.withHapTime((t) => t.add(offset)).query(state.setSpan(span.withTime((t) => t.sub(offset))));
};
const steps = getCalculateSteps() ? lcm(...pats.map((x) => x._steps)) : undefined;
return new Pattern(query).splitQueries().setSteps(steps);
} /** Concatenation: combines a list of patterns, switching between them successively, one per cycle. Unlike slowcat, this version will skip cycles.
* @global
* @tags combiners
* @param {...any} pats The items to concatenate
* @returns {Pattern}
*/
export function slowcatPrime(...pats) {
if (!pats.length) {
return silence;
}
pats = pats.map(reify);
const query = function (state) {
const pat_n = _mod(Math.floor(state.span.begin), pats.length);
const pat = pats[pat_n];
return pat.query(state);
};
return new Pattern(query).splitQueries();
}
/** The given items are con**cat**enated, where each one takes one cycle.
*
* @tags combiners
* @param {...any} pats The items to concatenate
* @synonyms slowcat
* @returns {Pattern}
* @example
* cat("e5", "b4", ["d5", "c5"]).note()
* // "<e5 b4 [d5 c5]>".note()
*
* @example
* // As a chained function:
* s("hh*4").cat(
* note("c4(5,8)")
* )
*/
export function cat(...pats) {
return slowcat(...pats);
}
/**
* Similarly to `arrange`, allows you to arrange multiple patterns together over multiple cycles.
* Unlike `arrange`, you specify a start and stop time for each pattern rather than duration, which
* means that patterns can overlap.
* @param {...any} parts
* @tags combiners
* @returns {Pattern}
* @example
* seqPLoop(
* [0, 2, "bd(3,8)"],
* [1, 3, "cp(3,8)"]
* ).sound()
*/
export function seqPLoop(...parts) {
let total = Fraction(0);
const pats = [];
for (let part of parts) {
if (part.length == 2) {
part.unshift(total);
}
total = part[1];
}
return stack(
...parts.map(([start, stop, pat]) =>
pure(reify(pat)).compress(Fraction(start).div(total), Fraction(stop).div(total)),
),
)
.slow(total)
.innerJoin(); // or resetJoin or restartJoin ??
}
export function fastcat(...pats) {
let result = slowcat(...pats);
if (pats.length > 1) {
result = result._fast(pats.length);
result._steps = pats.length;
}
if (pats.length == 1 && pats[0].__steps_source) {
pats._steps = pats[0]._steps;
}
return result;
}
/**
* Turns a list of patterns into a single pattern which outputs list-values
*
* @param {Pattern[]} pats
* @name parray
* @tags combiners
* @returns {Pattern}
*/
export const parray = (pats) => {
const pack = (...xs) => xs;
let acc = pure(curry(pack, null, pats.length));
for (const p of pats) acc = acc.appBoth(reify(p));
return acc;
};
+518
View File
@@ -0,0 +1,518 @@
/*
pattern-composers.mjs - Pattern composer functions with multiple alignments
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-composers.mjs>
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 { isFraction } from './fraction.mjs';
import { Pattern } from './pattern.mjs';
import { reify } from './pattern-atoms.mjs';
import { sequence } from './pattern-combiners.mjs';
import { numeralArgs, _mod, curry } from './util.mjs';
import { unionWithObj } from './value.mjs';
//////////////////////////////////////////////////////////////////////
// compose matrix functions
const ALIGNMENTS = {
in(self, other, func) {
return self.fmap(func).appLeft(reify(other));
},
out(self, other, func) {
return self.fmap(func).appRight(reify(other));
},
mix(self, other, func) {
return self.fmap(func).appBoth(reify(other));
},
squeeze(self, other, func) {
const otherPat = reify(other);
return self.fmap((a) => otherPat.fmap((b) => func(a)(b))).squeezeJoin();
},
squeezeOut(self, other, func) {
const otherPat = reify(other);
return otherPat.fmap((a) => self.fmap((b) => func(b)(a))).squeezeJoin();
},
reset(self, other, func) {
const otherPat = reify(other);
return otherPat.fmap((b) => self.fmap((a) => func(a)(b))).resetJoin();
},
restart(self, other, func) {
const otherPat = reify(other);
return otherPat.fmap((b) => self.fmap((a) => func(a)(b))).restartJoin();
},
poly(self, other, func) {
const otherPat = reify(other);
return self.fmap((b) => otherPat.fmap((a) => func(a)(b))).polyJoin();
},
};
let DEFAULT_ALIGNMENT = 'in';
const ALIGNMENT_KEYS = Object.keys(ALIGNMENTS).map((how) => how.toLowerCase());
/**
* Sets the default method of combining events from two patterns (aka [alignment](https://strudel.cc/technical-manual/alignment/)) in Strudel.
* The default method is 'in', meaning that patterns to the left will (typically) dictate the event timings when combined with patterns to the right.
* By changing alignment to 'out', the opposite will happen. With 'mix', they will combine their event timings.
*
* Note that we say the _default_ method, because alignments can also be set explicitly with calls like
* 'add.mix', 'set.squeeze', etc.
*
* @param {string} alignment Default join method to use. Options: 'in', 'out', 'mix', 'squeeze', 'squeezeout', 'reset', 'restart', 'poly'
* @tags combiners
* @example
* setDefaultJoin('mix') // also try 'in', 'out', 'squeeze', etc.
* s("saw").vel("1 0.5").note("F A C E").delay("0 0.2 0.3")
*/
export const setDefaultJoin = (alignment) => {
alignment = alignment?.toLowerCase();
if (DEFAULT_ALIGNMENT !== alignment && ALIGNMENT_KEYS.includes(alignment)) {
DEFAULT_ALIGNMENT = alignment;
setupAlignments();
}
};
// pattern composers
const COMPOSERS = {
/**
* When called on a pattern `a`, with a input pattern `b` (`a.set(b)`),
* combines `a` and `b` such that anything defined in `b`
* and anything defined in `a` that is *not* defined in `b`
* will be in the resulting pattern.
*
* The structure is maintained from `a`,
* because the default pattern alignment is `in`,
* see the section on `Pattern Alignment`
* in the technical manual in the docs
*
* This is the inverse of `keep`
*
* See examples below
* @name set
* @param {Pattern} a
* @param {Pattern} b
* @returns {Pattern}
* @memberof Pattern.prototype
* @tags internals, combiners
* @example
* // because input pattern has `s` set,
* // it overrides the "sine" declared earlier
* note("c a f e").s("sine").set(s("triangle"))
*/
set: [(a, b) => b],
/**
* When called on a pattern `a`, with a input pattern `b` (`a.keep(b)`),
* combines `a` and `b` such that anything defined in `a`,
* and anything defined in `b` that is *not* defined in `a`
* will be in the resulting pattern
*
* The structure is maintained from `a`,
* because the default pattern alignment is `in`,
* see the section on `Pattern Alignment`
* in the technical manual in the docs
*
* This is the inverse of `set`
*
* See examples below
* @name keep
* @param {Pattern} a
* @memberof Pattern.prototype
* @returns {Pattern}
* @tags internals, combiners
* @example
* // notes, already defined, will stay "c a f e",
* // while "s", not defined, will be set to "piano"
* note("c a f e").keep(note("e f a c").s("piano"))
*/
keep: [(a) => a],
keepif: [(a, b) => (b ? a : undefined)],
// numerical functions
/**
*
* Assumes a pattern of numbers. Adds the given number to each item in the pattern.
* @name add
* @memberof Pattern.prototype
* @tags math
* @example
* // Here, the triad 0, 2, 4 is shifted by different amounts
* n("0 2 4".add("<0 3 4 0>")).scale("C:major")
* // Without add, the equivalent would be:
* // n("<[0 2 4] [3 5 7] [4 6 8] [0 2 4]>").scale("C:major")
* @example
* // You can also use add with notes:
* note("c3 e3 g3".add("<0 5 7 0>"))
* // Behind the scenes, the notes are converted to midi numbers:
* // note("48 52 55".add("<0 5 7 0>"))
*/
add: [numeralArgs((a, b) => a + b)], // support string concatenation
/**
*
* Like add, but the given numbers are subtracted.
* @name sub
* @memberof Pattern.prototype
* @tags math
* @example
* n("0 2 4".sub("<0 1 2 3>")).scale("C4:minor")
* // See add for more information.
*/
sub: [numeralArgs((a, b) => a - b)],
/**
*
* Multiplies each number by the given factor.
* @name mul
* @memberof Pattern.prototype
* @tags math
* @example
* "<1 1.5 [1.66, <2 2.33>]>*4".mul(150).freq()
*/
mul: [numeralArgs((a, b) => a * b)],
/**
*
* Divides each number by the given factor.
* @name div
* @memberof Pattern.prototype
* @tags math
*/
div: [numeralArgs((a, b) => a / b)],
/**
*
* Divides each number by the given factor and returns the remainder
* @name mod
* @memberof Pattern.prototype
* @tags math
*/
mod: [numeralArgs(_mod)],
/**
*
* Raises each number to the power of the given factor
* @name pow
* @memberof Pattern.prototype
* @tags math
*/
pow: [numeralArgs(Math.pow)],
/**
*
* Performs a bitwise `and` on each number and the given factor
* @name band
* @memberof Pattern.prototype
* @tags math
*/
band: [numeralArgs((a, b) => a & b)],
/**
*
* Performs a bitwise `or` on each number and the given factor
* @name bor
* @memberof Pattern.prototype
* @tags math
*/
bor: [numeralArgs((a, b) => a | b)],
/**
*
* Performs a bitwise `xor` on each number and the given factor
* @name bxor
* @memberof Pattern.prototype
* @tags math
*/
bxor: [numeralArgs((a, b) => a ^ b)],
/**
*
* Performs a bitwise `left shift` on each number by the given factor
* @name blshift
* @memberof Pattern.prototype
* @tags math
*/
blshift: [numeralArgs((a, b) => a << b)],
/**
*
* Performs a bitwise `right shift` on each number by the given factor
* @name brshift
* @memberof Pattern.prototype
* @tags math
*/
brshift: [numeralArgs((a, b) => a >> b)],
// TODO - force numerical comparison if both look like numbers?
/**
* performs a < b
* @name lt
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
lt: [(a, b) => a < b],
/**
* performs a > b
* @name gt
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
gt: [(a, b) => a > b],
/**
* performs a <= b
* @name lte
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
lte: [(a, b) => a <= b],
/**
* performs a >= b
* @name gte
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
gte: [(a, b) => a >= b],
/**
* performs a == b
* @name eq
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
eq: [(a, b) => a == b],
/**
* performs a === b (strictly equal)
* @name eqt
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
eqt: [(a, b) => a === b],
/**
* performs a != b
* @name ne
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
ne: [(a, b) => a != b],
/**
* performs a !== b (strictly not equal)
* @name net
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
net: [(a, b) => a !== b],
/**
* performs a && b
* @name and
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
and: [(a, b) => a && b],
/**
* performs a || b
* @name or
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
or: [(a, b) => a || b],
// bitwise ops
func: [(a, b) => b(a)],
};
const setupAlignments = () => {
// generate methods to do what and how
for (const [what, [op, preprocess]] of Object.entries(COMPOSERS)) {
// make plain version, e.g. pat._add(value) adds that plain value
// to all the values in pat
Pattern.prototype['_' + what] = function (value) {
return this.fmap((x) => op(x, value));
};
// make patternified monster version
Object.defineProperty(Pattern.prototype, what, {
// Set to configurable so we can update if the default alignment changes
configurable: true,
// a getter that returns a function, so 'pat' can be
// accessed by closures that are methods of that function..
get: function () {
const pat = this;
// wrap the 'in' function as default behaviour
const wrapper = (...other) => pat[what][DEFAULT_ALIGNMENT](...other);
// add methods to that function for each behaviour
for (const [alignment, alignmentFunc] of Object.entries(ALIGNMENTS)) {
wrapper[alignment.toLowerCase()] = function (...other) {
var howpat = pat;
other = sequence(other);
if (preprocess) {
howpat = preprocess(howpat);
other = preprocess(other);
}
var result;
// hack to remove undefs when doing 'keepif'
if (what === 'keepif') {
// avoid union, as we want to throw away the value of 'b' completely
result = alignmentFunc(howpat, other, (a) => (b) => op(a, b));
result = result.removeUndefineds();
} else {
result = alignmentFunc(howpat, other, (a) => (b) => _composeOp(a, b, op));
}
return result;
};
}
wrapper.squeezein = wrapper.squeeze;
return wrapper;
},
});
}
};
function _nonArrayObject(x) {
return !Array.isArray(x) && typeof x === 'object' && !isFraction(x);
}
function _composeOp(a, b, func) {
if (_nonArrayObject(a) || _nonArrayObject(b)) {
if (!_nonArrayObject(a)) {
a = { value: a };
}
if (!_nonArrayObject(b)) {
b = { value: b };
}
return unionWithObj(a, b, func);
}
return func(a, b);
}
// Make composers
setupAlignments();
// Default op to 'set', e.g. pat.squeeze(pat2) = pat.set.squeeze(pat2)
for (const alignment of ALIGNMENT_KEYS) {
Pattern.prototype[alignment] = function (...args) {
return this.set[alignment](args);
};
}
// binary composers
/**
* Applies the given structure to the pattern:
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* note("c,eb,g")
* .struct("x ~ x ~ ~ x ~ x ~ ~ ~ x ~ x ~ ~")
* .slow(2)
*/
Pattern.prototype.struct = function (...args) {
return this.keepif.out(...args);
};
Pattern.prototype.structAll = function (...args) {
return this.keep.out(...args);
};
/**
* Returns silence when mask is 0 or "~"
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* note("c [eb,g] d [eb,g]").mask("<1 [0 1]>")
*/
Pattern.prototype.mask = function (...args) {
return this.keepif.in(...args);
};
Pattern.prototype.maskAll = function (...args) {
return this.keep.in(...args);
};
/**
* Resets the pattern to the start of the cycle for each onset of the reset pattern.
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* s("[<bd lt> sd]*2, hh*8").reset("<x@3 x(5,8)>")
*/
Pattern.prototype.reset = function (...args) {
return this.keepif.reset(...args);
};
Pattern.prototype.resetAll = function (...args) {
return this.keep.reset(...args);
};
/**
* Restarts the pattern for each onset of the restart pattern.
* While reset will only reset the current cycle, restart will start from cycle 0.
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* s("[<bd lt> sd]*2, hh*8").restart("<x@3 x(5,8)>")
*/
Pattern.prototype.restart = function (...args) {
return this.keepif.restart(...args);
};
Pattern.prototype.restartAll = function (...args) {
return this.keep.restart(...args);
};
export const mask = curry((a, b) => reify(b).mask(a));
export const struct = curry((a, b) => reify(b).struct(a));
export const superimpose = curry((a, b) => reify(b).superimpose(...a));
export const withValue = curry((a, b) => reify(b).withValue(a));
export const bind = curry((a, b) => reify(b).bind(a));
export const innerBind = curry((a, b) => reify(b).innerBind(a));
export const outerBind = curry((a, b) => reify(b).outerBind(a));
export const squeezeBind = curry((a, b) => reify(b).squeezeBind(a));
export const stepBind = curry((a, b) => reify(b).stepBind(a));
export const polyBind = curry((a, b) => reify(b).polyBind(a));
// operators
export const set = curry((a, b) => reify(b).set(a));
export const keep = curry((a, b) => reify(b).keep(a));
export const keepif = curry((a, b) => reify(b).keepif(a));
export const add = curry((a, b) => reify(b).add(a));
export const sub = curry((a, b) => reify(b).sub(a));
export const mul = curry((a, b) => reify(b).mul(a));
export const div = curry((a, b) => reify(b).div(a));
export const mod = curry((a, b) => reify(b).mod(a));
export const pow = curry((a, b) => reify(b).pow(a));
export const band = curry((a, b) => reify(b).band(a));
export const bor = curry((a, b) => reify(b).bor(a));
export const bxor = curry((a, b) => reify(b).bxor(a));
export const blshift = curry((a, b) => reify(b).blshift(a));
export const brshift = curry((a, b) => reify(b).brshift(a));
export const lt = curry((a, b) => reify(b).lt(a));
export const gt = curry((a, b) => reify(b).gt(a));
export const lte = curry((a, b) => reify(b).lte(a));
export const gte = curry((a, b) => reify(b).gte(a));
export const eq = curry((a, b) => reify(b).eq(a));
export const eqt = curry((a, b) => reify(b).eqt(a));
export const ne = curry((a, b) => reify(b).ne(a));
export const net = curry((a, b) => reify(b).net(a));
export const and = curry((a, b) => reify(b).and(a));
export const or = curry((a, b) => reify(b).or(a));
export const func = curry((a, b) => reify(b).func(a));
+63
View File
@@ -0,0 +1,63 @@
/*
pattern-deprecated.mjs - Deprecated pattern functions for backwards compatibility
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-deprecated.mjs>
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 { Pattern } from './pattern.mjs';
import { register } from './register.mjs';
import {
zip,
stepalt,
stepcat,
shrinklist,
shrink,
expand,
extend,
tour,
contract,
drop,
take,
pace,
polymeter,
} from './pattern-stepwise.mjs';
/**
* Plays the pattern at the given cycles per minute.
* @tags temporal
* @deprecated
* @name cpm
* @memberof Pattern.prototype
* @example
* s("<bd sd>,hh*2").cpm(90) // = 90 bpm
*/
// this is redefined in repl.mjs, using the current cps as divisor
export const cpm = register('cpm', function (cpm, pat) {
return pat._fast(cpm / 60 / 1);
});
// Deprecated stepwise aliases
export const s_cat = stepcat;
export const s_alt = stepalt;
export const s_polymeter = polymeter;
Pattern.prototype.s_polymeter = Pattern.prototype.polymeter;
export const s_taper = shrink;
Pattern.prototype.s_taper = Pattern.prototype.shrink;
export const s_taperlist = shrinklist;
Pattern.prototype.s_taperlist = Pattern.prototype.shrinklist;
export const s_add = take;
Pattern.prototype.s_add = Pattern.prototype.take;
export const s_sub = drop;
Pattern.prototype.s_sub = Pattern.prototype.drop;
export const s_expand = expand;
Pattern.prototype.s_expand = Pattern.prototype.expand;
export const s_extend = extend;
Pattern.prototype.s_extend = Pattern.prototype.extend;
export const s_contract = contract;
Pattern.prototype.s_contract = Pattern.prototype.contract;
export const s_tour = tour;
Pattern.prototype.s_tour = Pattern.prototype.tour;
export const s_zip = zip;
Pattern.prototype.s_zip = Pattern.prototype.zip;
export const steps = pace;
Pattern.prototype.steps = Pattern.prototype.pace;
+195
View File
@@ -0,0 +1,195 @@
/*
pattern-misc.mjs - Miscellaneous pattern functions that should probably be moved to a different package
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-misc.mjs>
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 { Pattern } from './pattern.mjs';
import { pure, reify } from './pattern-atoms.mjs';
import { parray } from './pattern-combiners.mjs';
import { curry } from './util.mjs';
// These functions are related to superdough / kabelsalat / or general IO (e.g. sliders)
// This entire file should probably not live in the Pattern package,
// but move either to core or superdough.
/** exposes a custom value at query time. basically allows mutating state without evaluation
* @param {function():Pattern} accessor
* @returns {Pattern}
* @tags internals
*/
export const ref = (accessor) =>
pure(1)
.withValue(() => reify(accessor()))
.innerJoin();
const _ensureListPattern = (list) => {
if (Array.isArray(list)) {
return parray(list);
}
return reify(list);
};
/**
* Scale the magnitude of the harmonics of one of the core synths ('sine', 'tri', 'saw', ..)
*
* Can also be used to create a new synth via `s('user').partials(...)`
*
* @name partials
* @tags superdough
* @param {number[] | Pattern} list [0, 1] magnitudes for partials. 0th entry is the fundamental harmonic (i.e. DC offset is skipped)
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* s("user").seg(16).n(irand(8)).scale("A:major")
* .partials([1, 0, 1, 0, 0, 1])
* @example
* s("saw").seg(8).n(irand(12)).scale("G#:minor")
* .partials(binaryL(irand(256).add("1")))
*/
Pattern.prototype.partials = function (list) {
return this.withValue((v) => (l) => ({ ...v, partials: l })).appLeft(_ensureListPattern(list));
};
// Also create a top-level function
export const partials = (list) => {
return _ensureListPattern(list).as('partials');
};
/**
* Rotates the harmonics of one of the core synths ('sine', 'tri', 'saw', 'user', ..) by a list of phases
*
* @name phases
* @tags superdough
* @param {number[] | Pattern} list of [0, 1) phases for partials. 0th entry is the fundamental phase (i.e. DC offset is skipped)
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* // Phase cancellation
* s("saw").seg(8).n(irand(12)).scale("G#1:minor")
* .partials(partials([1, 1, 1]))
* .superimpose(x => x.phases([0.5, 0.5, 0.5]))
*/
Pattern.prototype.phases = function (list) {
return this.withValue((v) => (l) => ({ ...v, phases: l })).appLeft(_ensureListPattern(list));
};
// Also create a top-level function
export const phases = (list) => {
return _ensureListPattern(list).as('phases');
};
/**
* Establishes an FX chain. Can be called by chaining .FX(fx1).FX(fx2)..
* calls and/or in a single .FX(fx1, fx2, ..) call. The fx1, .. are _patterns_ which
* establish the controls of the given effect. See examples.
* @param {...any} effects
* @name FX
* @tags superdough
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* $: s("[sbd <hh [bd | lt | oh]>]*4").dec(.4)
* .FX(
* phaser(0.5).gain(2),
* bpf(800),
* distort(1.3),
* room(0.2),
* delay(0.5).gain(1.25),
* distort(0.3),
* ).fxr(1.7) // sets release time of effects (like delay)
* @example
* $: s("saw").fm(0.5)
* .delay(0.3) // outer effects are applied *last*
* .FX(coarse(4)) // first coarse
* .FX(lpf(500).lpe(4).lpa(1).lpd(2)) // then lpf
* .FX(distort(1)) // then distort
*/
Pattern.prototype.FX = function (...effects) {
effects = effects.map(reify);
return this.withValue((v) => (vEff) => {
const currFX = v.FX ?? [];
return { ...v, FX: currFX.concat(vEff) };
}).appLeft(parray(effects));
};
const _asArrayPattern = (pats) => {
const pack = (...xs) => xs;
let acc = pure(curry(pack, null, pats.length));
for (const p of pats) acc = acc.appLeft(p);
return acc;
};
/**
* Produces a [Kabelsalat](https://kabel.salat.dev/) modular sound engine.
* This can be used as either an effect (by including `audioin()` at the beginning
* of your kabel expression) or as a sound source (via any expression which doesn't
* start with `audioin()`).
*
* Some helpers you have available to you:
* * Strudel mini notation works fine in K(..) via "" or ``
* * More complex Strudel expressions (like "0 1 2".fast(4) or irand(24)) can be
* written by wrapping them in `S(..)` inside your Kabel code
* * We expose Strudel's note frequency under `sFreq` and Strudel's gate
* information under `sGate`
* * You can use more complex multi-line expressions (like `let x = a; let y = b; x.lpf(y);`)
* by wrapping them inside a function in K (see example).
*
* @name K
* @tags generators, superdough
* @param {KabelsalatExpression | Function} expr Kabelsalat graph definition
* @memberof Pattern.prototype
* @returns {Pattern}
*
* @example
* note("A c e".fast(4)).transpose("<0 2 4 6 8>")
* .scale("F:minor").transpose("12")
* .s("saw")
* .K(
* // audioin().mul(sGate.adsr(0.001, 0.3, 0, 0.2)) // as effect
* saw(saw(sFreq / "2!3 16").mul(8).add(sFreq).lag("0!3 0.1")).mul(0.3) // as source
* .mul(sGate.adsr(0, 0.15, 0.5, "0.1!3 1"))
* .lpf(sGate.adsr(0, 0.2, 0.3, 0.2).mul(1).add(0))
* .add(x => x.delay(S("0.3 0.2".fast(2))).mul(0.7))
* .add(x => x.delay("0.03 [0.08 0.01] 0.01 0.013").mul(0.77)).mul(0.7)
* .add(x => x.delay(.13).mul(0.7))
* .out()
* )
*
* @example
* n("<0 1 <2 3 2 4>>*16")
* .scale("G#2:minor").sometimes(x => x.transpose("12 | 24"))
* .K(() => {
* const att = S(rand.range(0, 0.05))
* const dec = S(rand.range(0.05, 0.2))
* let f = n(sFreq);
* const mod = sine(f).mul("0.1 | 0.2 | 0.3")
* .add("[[1.5 1] | 1 | 2 | 4 | [6 4@3]]*2")
* saw(f.mul(mod))
* .mul(sGate.ad(att, dec))
* .add(x => x.delay(0.4).mul(0.3))
* .out()
* }).fxr(1).room(0.3)
*/
/**
* Creates a worklet effect. Typically derived by writing K(...) in the REPL which will parse
* Kabelsalat code.
*
* @name worklet
* @param {string} src Source code of the worklet update function
* @param {...number | ...Pattern} inputs Worklet inputs
* @memberof Pattern.prototype
* @returns {Pattern}
* @noAutocomplete
*/
Pattern.prototype.worklet = function (src, ...inputs) {
inputs = inputs.map(reify);
return this.outerBind((v) => {
return _asArrayPattern(inputs).withValue((vInput) => {
const currInputs = v.workletInputs ?? [];
return { ...v, workletSrc: src, workletInputs: currInputs.concat(vInput) };
});
});
};
export const worklet = (...args) => pure({}).worklet(...args);
+32
View File
@@ -0,0 +1,32 @@
/*
pattern-multi.mjs - Assignment of multi-pattern functions to the pattern prototype
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-multi.mjs>
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 { Pattern } from './pattern.mjs';
import { slowcat, fastcat, cat, sequence, seq, stack } from './pattern-combiners.mjs';
import { stackLeft, stackRight, stackCenter, stackCentre, stackRepeat } from './pattern-stepwise.mjs';
// These are all top-level functions that combine an arbitrary number of patterns.
// Here we construct the Pattern member versions so they can be chained with other functions.
const multiPatternFunctions = {
stack,
stackLeft,
stackRight,
stackCenter,
stackCentre,
stackRepeat,
sequence,
seq,
cat,
fastcat,
slowcat,
};
for (const [name, func] of Object.entries(multiPatternFunctions)) {
Pattern.prototype[name] = function (...pats) {
return func(this, ...pats);
};
}
+145
View File
@@ -0,0 +1,145 @@
/*
pattern-numerical.mjs - Numerical pattern functions
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-numerical.mjs>
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 { register } from './register.mjs';
//////////////////////////////////////////////////////////////////////
// Numerical transformations
/**
* Assumes a numerical pattern. Returns a new pattern with all values rounded
* to the nearest integer.
* @name round
* @tags math
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* n("0.5 1.5 2.5".round()).scale("C:major")
*/
export const round = register('round', function (pat) {
return pat.asNumber().fmap((v) => Math.round(v));
});
/**
* Assumes a numerical pattern. Returns a new pattern with all values set to
* their mathematical floor. E.g. `3.7` replaced with to `3`, and `-4.2`
* replaced with `-5`.
* @name floor
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* note("42 42.1 42.5 43".floor())
*/
export const floor = register('floor', function (pat) {
return pat.asNumber().fmap((v) => Math.floor(v));
});
export const log2 = register('log2', (pat) => pat.asNumber().fmap((v) => Math.log2(v)));
/**
* Assumes a numerical pattern. Returns a new pattern with all values set to
* their mathematical ceiling. E.g. `3.2` replaced with `4`, and `-4.2`
* replaced with `-4`.
* @name ceil
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* note("42 42.1 42.5 43".ceil())
*/
export const ceil = register('ceil', function (pat) {
return pat.asNumber().fmap((v) => Math.ceil(v));
});
/**
* Assumes a numerical pattern, containing unipolar values in the range 0 ..
* 1. Returns a new pattern with values scaled to the bipolar range -1 .. 1
* @tags math
* @returns {Pattern}
* @noAutocomplete
* @memberof Pattern.prototype
*/
export const toBipolar = register('toBipolar', function (pat) {
return pat.fmap((x) => x * 2 - 1);
});
/**
* Assumes a numerical pattern, containing bipolar values in the range -1 .. 1
* Returns a new pattern with values scaled to the unipolar range 0 .. 1
* @tags math
* @returns {Pattern}
* @noAutocomplete
* @memberof Pattern.prototype
*/
export const fromBipolar = register('fromBipolar', function (pat) {
return pat.fmap((x) => (x + 1) / 2);
});
/**
* Assumes a numerical pattern, containing unipolar values in the range 0 .. 1.
* Returns a new pattern with values scaled to the given min/max range.
* Most useful in combination with continuous patterns.
* @name range
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* s("[bd sd]*2,hh*8")
* .cutoff(sine.range(500,4000))
*/
export const range = register('range', function (min, max, pat) {
return pat.mul(max - min).add(min);
});
/**
* Assumes a numerical pattern, containing unipolar values in the range 0 .. 1
* Returns a new pattern with values scaled to the given min/max range,
* following an exponential curve.
* @name rangex
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* s("[bd sd]*2,hh*8")
* .cutoff(sine.rangex(500,4000))
*/
export const rangex = register('rangex', function (min, max, pat) {
return pat._range(Math.log(min), Math.log(max)).fmap(Math.exp);
});
/**
* Assumes a numerical pattern, containing bipolar values in the range -1 .. 1
* Returns a new pattern with values scaled to the given min/max range.
* @name range2
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* s("[bd sd]*2,hh*8")
* .cutoff(sine2.range2(500,4000))
*/
export const range2 = register('range2', function (min, max, pat) {
return pat.fromBipolar()._range(min, max);
});
/**
* Allows dividing numbers via list notation using ":".
* Returns a new pattern with just numbers.
* @name ratio
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* ratio("1, 5:4, 3:2").mul(110)
* .freq().s("piano")
*/
export const ratio = register('ratio', (pat) =>
pat.fmap((v) => {
if (!Array.isArray(v)) {
return v;
}
return v.slice(1).reduce((acc, n) => acc / n, v[0]);
}),
);
+729
View File
@@ -0,0 +1,729 @@
/*
pattern-stepwise.mjs - Stepwise pattern functions
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-stepwise.mjs>
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 Fraction, { lcm } from './fraction.mjs';
import TimeSpan from './timespan.mjs';
import Hap from './hap.mjs';
import { flatten, uniqsortr, pairs, removeUndefineds } from './util.mjs';
import { Pattern, getCalculateSteps } from './pattern.mjs';
import { reify, gap, silence, nothing } from './pattern-atoms.mjs';
import { register } from './register.mjs';
import { fastcat, slowcat, stack, sequence } from './pattern-combiners.mjs';
// Like register, but defaults to stepJoin
export function stepRegister(name, func, patternify = true, preserveSteps = false, join = (x) => x.stepJoin()) {
return register(name, func, patternify, preserveSteps, join);
}
//////////////////////////////////////////////////////////////////////
// Stepwise functions
Pattern.prototype.stepJoin = function () {
const pp = this;
const first_t = stepcat(..._retime(_slices(pp.queryArc(0, 1))))._steps;
const q = function (state) {
const shifted = pp.early(state.span.begin.sam());
const haps = shifted.query(state.setSpan(new TimeSpan(Fraction(0), Fraction(1))));
const pat = stepcat(..._retime(_slices(haps)));
return pat.query(state);
};
return new Pattern(q, first_t);
};
Pattern.prototype.stepBind = function (func) {
return this.fmap(func).stepJoin();
};
export function _retime(timedHaps) {
const occupied_perc = timedHaps.filter((t, pat) => pat.hasSteps).reduce((a, b) => a.add(b), Fraction(0));
const occupied_steps = removeUndefineds(timedHaps.map((t, pat) => pat._steps)).reduce(
(a, b) => a.add(b),
Fraction(0),
);
const total_steps = occupied_perc.eq(0) ? undefined : occupied_steps.div(occupied_perc);
function adjust(dur, pat) {
if (pat._steps === undefined) {
return [dur.mulmaybe(total_steps), pat];
}
return [pat._steps, pat];
}
return timedHaps.map((x) => adjust(...x));
}
export function _slices(haps) {
// slices evs = map (\s -> ((snd s - fst s), stack $ map value $ fit s evs))
// $ pairs $ sort $ nubOrd $ 0:1:concatMap (\ev -> start (part ev):stop (part ev):[]) evs
const breakpoints = flatten(haps.map((hap) => [hap.part.begin, hap.part.end]));
const unique = uniqsortr([Fraction(0), Fraction(1), ...breakpoints]);
const slicespans = pairs(unique);
return slicespans.map((s) => [
s[1].sub(s[0]),
stack(..._fitslice(new TimeSpan(...s), haps).map((x) => x.value.withHap((h) => h.setContext(h.combineContext(x))))),
]);
}
export function _fitslice(span, haps) {
return removeUndefineds(haps.map((hap) => _match(span, hap)));
}
export function _match(span, hap_p) {
const subspan = span.intersection(hap_p.part);
if (subspan == undefined) {
return undefined;
}
return new Hap(hap_p.whole, subspan, hap_p.value, hap_p.context);
}
function _sequenceCount(x) {
if (Array.isArray(x)) {
if (x.length == 0) {
return [silence, 0];
}
if (x.length == 1) {
return _sequenceCount(x[0]);
}
return [fastcat(...x.map((a) => _sequenceCount(a)[0])), x.length];
}
return [reify(x), 1];
}
export function _polymeterListSteps(steps, ...args) {
const seqs = args.map((a) => _sequenceCount(a));
if (seqs.length == 0) {
return silence;
}
if (steps == 0) {
steps = seqs[0][1];
}
const pats = [];
for (const seq of seqs) {
if (seq[1] == 0) {
continue;
}
if (steps == seq[1]) {
pats.push(seq[0]);
} else {
pats.push(seq[0]._fast(Fraction(steps).div(Fraction(seq[1]))));
}
}
return stack(...pats);
}
/**
* *Experimental*
*
* Aligns the steps of the patterns, creating polymeters. The patterns are repeated until they all fit the cycle. For example, in the below the first pattern is repeated twice, and the second is repeated three times, to fit the lowest common multiple of six steps.
* @param {...any} args
* @tags stepwise
* @synonyms pm
* @returns {Pattern}
* @example
* // The same as note("{c eb g, c2 g2}%6")
* polymeter("c eb g", "c2 g2").note()
*
*/
export function polymeter(...args) {
if (Array.isArray(args[0])) {
// Support old behaviour
return _polymeterListSteps(0, ...args);
}
// TODO currently ignoring arguments without steps...
args = args.filter((arg) => arg.hasSteps);
if (args.length == 0) {
return silence;
}
const steps = lcm(...args.map((x) => x._steps));
if (steps.eq(Fraction(0))) {
return nothing;
}
const result = stack(...args.map((x) => x.pace(steps)));
result._steps = steps;
return result;
}
export const pm = polymeter;
/** 'Concatenates' patterns like `fastcat`, but proportional to a number of steps per cycle.
* The steps can either be inferred from the pattern, or provided as a [length, pattern] pair.
* Has the alias `timecat`.
* @global
* @param {...any} timepats
* @name stepcat
* @tags stepwise
* @synonyms timeCat, timecat
* @returns {Pattern}
* @example
* stepcat([3,"e3"],[1, "g3"]).note()
* // the same as "e3@3 g3".note()
* @example
* stepcat("bd sd cp","hh hh").sound()
* // the same as "bd sd cp hh hh".sound()
*/
export function stepcat(...timepats) {
if (timepats.length === 0) {
return nothing;
}
const findsteps = (x) => (Array.isArray(x) ? x : [x._steps ?? 1, x]);
timepats = timepats.map(findsteps);
if (timepats.find((x) => x[0] === undefined)) {
const times = timepats.map((a) => a[0]).filter((x) => x !== undefined);
if (times.length === 0) {
return fastcat(...timepats.map((x) => x[1]));
}
if (times.length === timepats.length) {
return nothing;
}
const avg = times.reduce((a, b) => a.add(b), Fraction(0)).div(times.length);
for (let timepat of timepats) {
if (timepat[0] === undefined) {
timepat[0] = avg;
}
}
}
if (timepats.length == 1) {
const result = reify(timepats[0][1]);
return result.withSteps((_) => timepats[0][0]);
}
const total = timepats.map((a) => a[0]).reduce((a, b) => a.add(b), Fraction(0));
let begin = Fraction(0);
const pats = [];
for (const [time, pat] of timepats) {
if (Fraction(time).eq(0)) {
continue;
}
const end = begin.add(time);
pats.push(reify(pat)._compress(begin.div(total), end.div(total)));
begin = end;
}
const result = stack(...pats);
result._steps = total;
return result;
}
// Aliases for `stepcat`
export const timecat = stepcat;
export const timeCat = stepcat;
/**
* Allows to arrange multiple patterns together over multiple cycles.
* Takes a variable number of arrays with two elements specifying the number of cycles and the pattern to use.
*
* @global
* @param {...any} sections
* @tags combiners
* @returns {Pattern}
* @example
* arrange(
* [4, "<c a f e>(3,8)"],
* [2, "<g a>(5,8)"]
* ).note()
*/
export function arrange(...sections) {
const total = sections.reduce((sum, [cycles]) => sum + cycles, 0);
sections = sections.map(([cycles, section]) => [cycles, section.fast(cycles)]);
return stepcat(...sections).slow(total);
}
function _stackWith(func, pats) {
pats = pats.map((pat) => (Array.isArray(pat) ? sequence(...pat) : reify(pat)));
if (pats.length === 0) {
return silence;
}
if (pats.length === 1) {
return pats[0];
}
const [left, ...right] = pats.map((pat) => pat._steps);
const steps = getCalculateSteps() ? left.maximum(...right) : undefined;
return stack(...func(steps, pats));
}
/**
* The input patterns are aligned to the left, with silence padded to the shorter pattern(s) in the final steps if there's a stepcount disparity. See also `stackRight` and `stackCenter/stackCentre`
*
* @param {...any} pats
* @name stackLeft
* @tags temporal, stepwise, combiners
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackLeft("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackLeft("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackLeft(...pats) {
return _stackWith(
(steps, pats) => pats.map((pat) => (pat._steps.eq(steps) ? pat : stepcat(pat, gap(steps.sub(pat._steps))))),
pats,
);
}
/**
* The input patterns are aligned to the right, with silence padded to the shorter pattern(s) in the initial steps if there's a stepcount disparity. See also `stackLeft` and `stackCenter/stackCentre`
*
* @param {...any} pats
* @name stackRight
* @tags temporal, stepwise, combiners
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackRight("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackRight("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackRight(...pats) {
return _stackWith(
(steps, pats) => pats.map((pat) => (pat._steps.eq(steps) ? pat : stepcat(gap(steps.sub(pat._steps)), pat))),
pats,
);
}
/**
* The input patterns are aligned to the right, with silence padded to the shorter pattern(s) in the initial steps if there's a stepcount disparity. See also `stackLeft` and `stackRight`
* @param {...any} pats
* @name stackCenter
* @tags temporal, stepwise, combiners
* @synonyms stackCentre
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackCenter("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackCenter("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackCenter(...pats) {
return _stackWith(
(steps, pats) =>
pats.map((pat) => {
if (pat._steps.eq(steps)) {
return pat;
}
const g = gap(steps.sub(pat._steps).div(2));
return stepcat(g, pat, g);
}),
pats,
);
}
export function stackCentre(...pats) {
return stackCenter(...pats);
}
/**
* Shorthand for `pm(patterns).pace(m)` where m is the max step count in the input patterns
* @param {...any} pats
* @name stackRepeat
* @tags temporal, stepwise, combiners
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackRepeat("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackRepeat("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackRepeat(...pats) {
return stackBy(reify('repeat'), ...pats);
}
export function stackBy(by, ...pats) {
const [left, ...right] = pats.map((pat) => pat._steps);
const steps = left.maximum(...right);
const lookup = {
centre: stackCentre,
left: stackLeft,
right: stackRight,
expand: stack,
repeat: (...args) => polymeter(...args).steps(steps),
};
return by
.inhabit(lookup)
.fmap((func) => func(...pats))
.innerJoin()
.setSteps(steps);
}
/**
* *Experimental*
*
* Speeds a pattern up or down, to fit to the given number of steps per cycle.
* @tags stepwise
* @name pace
* @memberof Pattern.prototype
* @example
* sound("bd sd cp").pace(4)
* // The same as sound("{bd sd cp}%4") or sound("<bd sd cp>*4")
*/
export const pace = register('pace', function (targetSteps, pat) {
if (pat._steps === undefined) {
return pat;
}
if (pat._steps.eq(Fraction(0))) {
// avoid divide by zero..
return nothing;
}
return pat._fast(Fraction(targetSteps).div(pat._steps)).setSteps(targetSteps);
});
/**
* *Experimental*
*
* Concatenates patterns stepwise, according to an inferred 'steps per cycle'.
* Similar to `stepcat`, but if an argument is a list, the whole pattern will alternate between the elements in the list.
*
* @global
* @param {...any} groups
* @tags stepwise
* @returns {Pattern}
* @example
* stepalt(["bd cp", "mt"], "bd").sound()
* // The same as "bd cp bd mt bd".sound()
*/
export function stepalt(...groups) {
groups = groups.map((a) => (Array.isArray(a) ? a.map(reify) : [reify(a)]));
const cycles = lcm(...groups.map((x) => Fraction(x.length)));
let result = [];
for (let cycle = 0; cycle < cycles; ++cycle) {
result.push(...groups.map((x) => (x.length == 0 ? silence : x[cycle % x.length])));
}
result = result.filter((x) => x.hasSteps && x._steps > 0);
const steps = result.reduce((a, b) => a.add(b._steps), Fraction(0));
result = stepcat(...result);
result._steps = steps;
return result;
}
/**
* *Experimental*
*
* Takes the given number of steps from a pattern (dropping the rest).
* A positive number will take steps from the start of a pattern, and a negative number from the end.
* @tags stepwise
* @name take
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* "bd cp ht mt".take("2").sound()
* // The same as "bd cp".sound()
* @example
* "bd cp ht mt".take("1 2 3").sound()
* // The same as "bd bd cp bd cp ht".sound()
* @example
* "bd cp ht mt".take("-1 -2 -3").sound()
* // The same as "mt ht mt cp ht mt".sound()
*/
export const take = stepRegister('take', function (i, pat) {
if (!pat.hasSteps) {
return nothing;
}
if (pat._steps.lte(0)) {
return nothing;
}
i = Fraction(i);
if (i.eq(0)) {
return nothing;
}
const flip = i < 0;
if (flip) {
i = i.abs();
}
const frac = i.div(pat._steps);
if (frac.lte(0)) {
return nothing;
}
if (frac.gte(1)) {
return pat;
}
if (flip) {
return pat.zoom(Fraction(1).sub(frac), 1);
}
return pat.zoom(0, frac);
});
/**
* *Experimental*
*
* Drops the given number of steps from a pattern.
* A positive number will drop steps from the start of a pattern, and a negative number from the end.
* @name drop
* @tags stepwise
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* "tha dhi thom nam".drop("1").sound().bank("mridangam")
* @example
* "tha dhi thom nam".drop("-1").sound().bank("mridangam")
* @example
* "tha dhi thom nam".drop("0 1 2 3").sound().bank("mridangam")
* @example
* "tha dhi thom nam".drop("0 -1 -2 -3").sound().bank("mridangam")
*/
export const drop = stepRegister('drop', function (i, pat) {
if (!pat.hasSteps) {
return nothing;
}
i = Fraction(i);
if (i.lt(0)) {
return pat.take(pat._steps.add(i));
}
return pat.take(Fraction(0).sub(pat._steps.sub(i)));
});
/**
* *Experimental*
*
* `extend` is similar to `fast` in that it increases its density, but it also increases the step count
* accordingly. So `stepcat("a b".extend(2), "c d")` would be the same as `"a b a b c d"`, whereas
* `stepcat("a b".fast(2), "c d")` would be the same as `"[a b] [a b] c d"`.
* @name extend
* @tags stepwise
* @memberof Pattern.prototype
* @example
* stepcat(
* sound("bd bd - <cp hh>").extend(2),
* sound("bd - sd -")
* ).pace(8)
*/
export const extend = stepRegister('extend', function (factor, pat) {
return pat.fast(factor).expand(factor);
});
/**
* *Experimental*
*
* `replicate` is similar to `extend`, except that `replicate` will "replicate" the thing being extended. This will only differ from `extend` when the input pattern differs from cycle to cycle.
*
* @tags stepwise
* @memberof Pattern.prototype
* @example
* stepcat(
* sound("bd bd - <cp hh>").replicate(2),
* sound("bd - sd -")
* ).pace(8)
*/
export const replicate = stepRegister('replicate', function (factor, pat) {
return pat.repeatCycles(factor).fast(factor).expand(factor);
});
/**
* *Experimental*
*
* Expands the step size of the pattern by the given factor.
* @name expand
* @tags stepwise
* @memberof Pattern.prototype
* @example
* sound("tha dhi thom nam").bank("mridangam").expand("3 2 1 1 2 3").pace(8)
*/
export const expand = stepRegister('expand', function (factor, pat) {
return pat.withSteps((t) => t.mul(Fraction(factor)));
});
/**
* *Experimental*
*
* Contracts the step size of the pattern by the given factor. See also `expand`.
* @tags stepwise
* @name contract
* @memberof Pattern.prototype
* @example
* sound("tha dhi thom nam").bank("mridangam").contract("3 2 1 1 2 3").pace(8)
*/
export const contract = stepRegister('contract', function (factor, pat) {
return pat.withSteps((t) => t.div(Fraction(factor)));
});
Pattern.prototype.shrinklist = function (amount) {
const pat = this;
if (!pat.hasSteps) {
return [pat];
}
let [amountv, times] = Array.isArray(amount) ? amount : [amount, pat._steps];
amountv = Fraction(amountv);
if (times === 0 || amountv === 0) {
return [pat];
}
const fromstart = amountv > 0;
const ranges = [];
if (fromstart) {
const seg = Fraction(1).div(pat._steps).mul(amountv);
for (let i = 0; i < times; ++i) {
const s = seg.mul(i);
if (s.gt(1)) {
break;
}
ranges.push([s, 1]);
}
} else {
amountv = Fraction(0).sub(amountv);
const seg = Fraction(1).div(pat._steps).mul(amountv);
for (let i = 0; i < times; ++i) {
const e = Fraction(1).sub(seg.mul(i));
if (e.lt(0)) {
break;
}
ranges.push([Fraction(0), e]);
}
}
return ranges.map((x) => pat.zoom(...x));
};
export const shrinklist = (amount, pat) => pat.shrinklist(amount);
Pattern.prototype.growlist = function (amount) {
return this.shrinklist(amount).reverse();
};
export const growlist = (amount, pat) => pat.growlist(amount);
/**
* *Experimental*
*
* Progressively shrinks the pattern by 'n' steps until there's nothing left, or if a second value is given (using mininotation list syntax with `:`),
* that number of times.
* A positive number will progressively drop steps from the start of a pattern, and a negative number from the end.
* @tags stepwise
* @returns {Pattern}
* @name shrink
* @memberof Pattern.prototype
* @example
* "tha dhi thom nam".shrink("1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".shrink("-1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".shrink("1 -1").sound().bank("mridangam").pace(4)
* @example
* note("0 1 2 3 4 5 6 7".scale("C:ritusen")).sound("folkharp")
* .shrink("1 -1").pace(8)
*
*/
export const shrink = register(
'shrink',
function (amount, pat) {
if (!pat.hasSteps) {
return nothing;
}
const list = pat.shrinklist(amount);
const result = stepcat(...list);
// TODO is this calculation needed?
result._steps = list.reduce((a, b) => a.add(b._steps), Fraction(0));
return result;
},
true,
false,
(x) => x.stepJoin(),
);
/**
* *Experimental*
*
* Progressively grows the pattern by 'n' steps until the full pattern is played, or if a second value is given (using mininotation list syntax with `:`),
* that number of times.
* A positive number will progressively grow steps from the start of a pattern, and a negative number from the end.
* @tags stepwise
* @returns {Pattern}
* @name grow
* @memberof Pattern.prototype
* @example
* "tha dhi thom nam".grow("1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".grow("-1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".grow("1 -1").sound().bank("mridangam").pace(4)
* @example
* note("0 1 2 3 4 5 6 7".scale("C:ritusen")).sound("folkharp")
* .grow("1 -1").pace(8)
*/
export const grow = register(
'grow',
function (amount, pat) {
if (!pat.hasSteps) {
return nothing;
}
const list = pat.shrinklist(Fraction(0).sub(amount));
list.reverse();
const result = stepcat(...list);
// TODO is this calculation needed?
result._steps = list.reduce((a, b) => a.add(b._steps), Fraction(0));
return result;
},
true,
false,
(x) => x.stepJoin(),
);
/**
* *Experimental*
*
* Inserts a pattern into a list of patterns. On the first repetition it will be inserted at the end of the list, then moved backwards through the list
* on successive repetitions. The patterns are added together stepwise, with all repetitions taking place over a single cycle. Using `pace` to set the
* number of steps per cycle is therefore usually recommended.
*
* @param {Pattern} pat
* @param {...any} many
* @tags stepwise
* @returns {Pattern}
* @name tour
* @memberof Pattern.prototype
* @example
* "[c g]".tour("e f", "e f g", "g f e c").note()
* .sound("folkharp")
* .pace(8)
*/
export const tour = function (pat, ...many) {
return pat.tour(...many);
};
Pattern.prototype.tour = function (...many) {
return stepcat(
...[].concat(
...many.map((x, i) => [...many.slice(0, many.length - i), this, ...many.slice(many.length - i)]),
this,
...many,
),
);
};
/**
* *Experimental*
*
* 'zips' together the steps of the provided patterns. This can create a long repetition, taking place over a single, dense cycle.
* Using `pace` to set the number of steps per cycle is therefore usually recommended.
*
* @param {...any} pats
* @global
* @tags stepwise
* @returns {Pattern}
* @example
* zip("e f", "e f g", "g [f e] a f4 c").note()
* .sound("folkharp")
* .pace(8)
*/
export const zip = function (...pats) {
pats = pats.filter((pat) => pat.hasSteps);
const zipped = slowcat(...pats.map((pat) => pat._slow(pat._steps)));
const steps = lcm(...pats.map((x) => x._steps));
return zipped._fast(steps).setSteps(steps);
};
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+45 -25
View File
@@ -4,7 +4,9 @@ Copyright (C) 2024 Strudel contributors - see <https://codeberg.org/uzu/strudel/
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 { Pattern, reify, silence, register } from './pattern.mjs';
import { Pattern } from './pattern.mjs';
import { reify, silence } from './pattern-atoms.mjs';
import { register } from './register.mjs';
import { _mod, clamp, objectMap } from './util.mjs';
@@ -26,12 +28,22 @@ const _pick = function (lookup, pat, modulo = true) {
});
};
export const pick = function (lookup, pat) {
// backward compatibility - the args used to be flipped
if (Array.isArray(pat)) {
[pat, lookup] = [lookup, pat];
}
return __pick(lookup, pat);
};
/** * Picks patterns (or plain values) either from a list (by index) or a lookup table (by name).
* Similar to `inhabit`, but maintains the structure of the original patterns.
* The lookup can also be a pattern of objects, such as a pattern of controls, in which case each of its events is used as the lookup table.
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @name pick
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* note("<0 1 2!2 3>".pick(["g a", "e f", "f g f g" , "g c d"]))
@@ -46,15 +58,6 @@ const _pick = function (lookup, pat, modulo = true) {
* const pat = sound("bd cp").speed("<2 3>")
* pat.fast("speed".pick(pat))
*/
export const pick = function (lookup, pat) {
// backward compatibility - the args used to be flipped
if (Array.isArray(pat)) {
[pat, lookup] = [lookup, pat];
}
return __pick(lookup, pat);
};
const __pick = register('pick', function (lookup, pat) {
return _pick(lookup, pat, false).innerJoin();
});
@@ -66,9 +69,10 @@ const __pick = register('pick', function (lookup, pat) {
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @name pickmod
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickmod = register('pickmod', function (lookup, pat) {
return _pick(lookup, pat, true).innerJoin();
});
@@ -78,6 +82,8 @@ export const pickmod = register('pickmod', function (lookup, pat) {
* @param {Pattern} pat
* @param {Pattern} lookup a pattern of indices or names
* @param {Function[] | object} lookup the array or lookup object of functions from which to pull
* @name pickF
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("bd [rim hh]").pickF("<0 1 2>", [rev,jux(rev),fast(2)])
@@ -98,6 +104,8 @@ export const pickF = register('pickF', function (pickPattern, lookup, pat) {
* @param {Pattern} pat
* @param {Pattern} lookup a pattern of indices or names
* @param {Function[] | object} lookup the array or lookup object of functions from which to pull
* @name pickmodF
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickmodF = register('pickmodF', function (pickPattern, lookup, pat) {
@@ -108,6 +116,7 @@ export const pickmodF = register('pickmodF', function (pickPattern, lookup, pat)
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* note("<0*4 1 2*2 3*3>".pickOut(["g a", "e f", "f g f g" , "g c d"]))
@@ -121,6 +130,7 @@ export const pickOut = register('pickOut', function (lookup, pat) {
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickmodOut = register('pickmodOut', function (lookup, pat) {
@@ -131,26 +141,30 @@ export const pickmodOut = register('pickmodOut', function (lookup, pat) {
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @name pickRestart
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickRestart = register('pickRestart', function (lookup, pat) {
return _pick(lookup, pat, false).restartJoin();
});
/** * The same as `pickRestart`, but if you pick a number greater than the size of the list,
* it wraps around, rather than sticking at the maximum value.
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @returns {Pattern}
* @example
* "<a@2 b@2 c@2 d@2>".pickRestart({
a: n("0 1 2 0"),
b: n("2 3 4 ~"),
c: n("[4 5] [4 3] 2 0"),
d: n("0 -3 0 ~")
}).scale("C:major").s("piano")
*/
/** The same as `pickRestart`, but if you pick a number greater than the size of the list,
* it wraps around, rather than sticking at the maximum value.
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @name pickmodRestart
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* "<a@2 b@2 c@2 d@2>".pickRestart({
a: n("0 1 2 0"),
b: n("2 3 4 ~"),
c: n("[4 5] [4 3] 2 0"),
d: n("0 -3 0 ~")
}).scale("C:major").s("piano")
*/
export const pickmodRestart = register('pickmodRestart', function (lookup, pat) {
return _pick(lookup, pat, true).restartJoin();
});
@@ -159,6 +173,8 @@ export const pickmodRestart = register('pickmodRestart', function (lookup, pat)
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @name pickReset
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickReset = register('pickReset', function (lookup, pat) {
@@ -170,6 +186,8 @@ export const pickReset = register('pickReset', function (lookup, pat) {
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @name pickmodReset
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickmodReset = register('pickmodReset', function (lookup, pat) {
@@ -183,6 +201,7 @@ export const pickmodReset = register('pickmodReset', function (lookup, pat) {
* @synonyms pickSqueeze
* @param {Pattern} pat
* @param {*} xs
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* let a = s("bd(3,8)")
@@ -206,6 +225,7 @@ export const { inhabit, pickSqueeze } = register(['inhabit', 'pickSqueeze'], fun
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @memberof Pattern.prototype
* @returns {Pattern}
*/
+118
View File
@@ -0,0 +1,118 @@
import { isPattern, Pattern } from './pattern.mjs';
import { reify } from './pattern-atoms.mjs';
import { sequence } from './pattern-combiners.mjs';
import { curry } from './util.mjs';
export const strudelScope = {};
/**
* Registers a new pattern method. The method is added to the Pattern class + the standalone function is returned from register.
*
* @tags functional
* @param {string | string[]} name name of the function, or an array of names to be used as synonyms
* @param {Function} func function with 1 or more params, where last is the current pattern
* @param {boolean} [patternify=false] defaults to true; if set to false, you will have more control over the arguments to `func` as they will be
* in their raw form and it will be up to you to patternify them and/or query them for values
* @param {boolean} [preserveSteps=false]
* @param {function(Pattern):Pattern} [join=(x) => x.innerJoin()]
* @returns {object}
* @example
* const vlpf = register('vlpf', (freq, pat) => {
* return pat.fmap((v) => ({...v, cutoff: freq * (v.velocity ?? 1) }));
* })
* s("saw").seg(8).velocity(rand).vlpf(800)
*
*/
export function register(name, func, patternify = true, preserveSteps = false, join = (x) => x.innerJoin()) {
if (isPattern(name)) {
throw new Error(
'Name argument for register is a pattern, try using single quotes (\'name\') instead of double quotes ("name")',
);
}
if (Array.isArray(name)) {
const result = {};
for (const name_item of name) {
result[name_item] = register(name_item, func, patternify, preserveSteps, join);
}
return result;
}
const arity = func.length;
var pfunc; // the patternified function
if (patternify) {
pfunc = function (...args) {
args = args.map(reify);
const pat = args[args.length - 1];
let result;
if (arity === 1) {
result = func(pat);
} else {
const firstArgs = args.slice(0, -1);
if (firstArgs.every((arg) => arg.__pure != undefined)) {
const pureArgs = firstArgs.map((arg) => arg.__pure);
const pureLocs = firstArgs.filter((arg) => arg.__pure_loc).map((arg) => arg.__pure_loc);
result = func(...pureArgs, pat);
result = result.withContext((context) => {
const locations = (context.locations || []).concat(pureLocs);
return { ...context, locations };
});
} else {
const [left, ...right] = firstArgs;
let mapFn = (...args) => {
return func(...args, pat);
};
mapFn = curry(mapFn, null, arity - 1);
result = join(right.reduce((acc, p) => acc.appLeft(p), left.fmap(mapFn)));
}
}
if (preserveSteps) {
result._steps = pat._steps;
}
return result;
};
} else {
pfunc = function (...args) {
args = args.map(reify);
const result = func(...args);
if (preserveSteps) {
result._steps = args[args.length - 1]._steps;
}
return result;
};
}
Pattern.prototype[name] = function (...args) {
// For methods that take a single argument (plus 'this'), allow
// multiple arguments but sequence them
if (arity === 2 && args.length !== 1) {
args = [sequence(...args)];
} else if (arity !== args.length + 1) {
throw new Error(`.${name}() expects ${arity - 1} inputs but got ${args.length}.`);
}
args = args.map(reify);
return pfunc(...args, this);
};
if (arity > 1) {
// There are patternified args, so lets make an unpatternified
// version, prefixed by '_'
Pattern.prototype['_' + name] = function (...args) {
const result = func(...args, this);
if (preserveSteps) {
result.setSteps(this._steps);
}
return result;
};
}
// toplevel functions get curried as well as patternified
// because pfunc uses spread args, we need to state the arity explicitly!
const curried = curry(pfunc, null, arity);
strudelScope[name] = curried;
return curried;
}
+137 -35
View File
@@ -4,21 +4,31 @@ Copyright (C) 2024 Strudel contributors - see <https://codeberg.org/uzu/strudel/
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 { Hap } from './hap.mjs';
import { Pattern, fastcat, pure, register, reify, silence, stack, sequenceP, isPattern } from './pattern.mjs';
import { _mod, noteToMidi } from './util.mjs';
import Fraction from './fraction.mjs';
import TimeSpan from './timespan.mjs';
import { Hap } from './hap.mjs';
import { Pattern, isPattern } from './pattern.mjs';
import { pure, reify, silence } from './pattern-atoms.mjs';
import { fastcat, stack, sequence, sequenceP } from './pattern-combiners.mjs';
import { register } from './register.mjs';
import { _mod, noteToMidi } from './util.mjs';
import { id, keyAlias, getCurrentKeyboardState } from './util.mjs';
import TimeSpan from './timespan.mjs';
/**
* A `signal` consisting of a constant value. Similar to `pure`, except that function
* creates a pattern with one event per cycle, whereas 'steady' patterns don't have
* an discrete structure.
*
* @param {*} value The constant value of the resulting pattern
* @returns {Pattern}
*/
export function steady(value) {
// A continuous value
return new Pattern((state) => [new Hap(undefined, state.span, value)]);
}
/**
* Creates a signal given by the input function
* Creates a "signal", an unstructured pattern consisting of a single value that changes over time.
*
* @name signal
* @param {*} func
@@ -205,27 +215,6 @@ export const itri2 = fastcat(isaw2, saw2);
*/
export const time = signal(id);
/**
* The mouse's x position value ranges from 0 to 1.
* @name mousex
* @synonyms mouseX
* @returns {Pattern}
* @tags external_io
* @example
* n(mousex.segment(4).range(0,7)).scale("C:minor")
*
*/
/**
* The mouse's y position value ranges from 0 to 1.
* @name mousey
* @synonyms mouseY
* @returns {Pattern}
* @tags external_io
* @example
* n(mousey.segment(4).range(0,7)).scale("C:minor")
*
*/
let _mouseY = 0,
_mouseX = 0;
if (typeof window !== 'undefined') {
@@ -236,8 +225,29 @@ if (typeof window !== 'undefined') {
});
}
/**
* The mouse's y position value ranges from 0 to 1.
* @name mousey
* @synonyms mouseY
* @type {Pattern}
* @tags external_io
* @example
* n(mousey.segment(4).range(0,7)).scale("C:minor")
*
*/
export const mousey = signal(() => _mouseY);
export const mouseY = signal(() => _mouseY);
/**
* The mouse's x position value ranges from 0 to 1.
* @name mousex
* @synonyms mouseX
* @type {Pattern}
* @tags external_io
* @example
* n(mousex.segment(4).range(0,7)).scale("C:minor")
*
*/
export const mousex = signal(() => _mouseX);
export const mouseX = signal(() => _mouseX);
@@ -506,6 +516,7 @@ export const withSeed = (func, pat) => {
* @name seed
* @tags math
* @param {number} n A new seed. Can be any number.
* @memberof Pattern.prototype
* @example
* $: s("hh*4").degrade();
* $: s("bd*4").degrade().seed(1); // Will degrade different events from the hi-hat
@@ -628,12 +639,19 @@ export const chooseInWith = (pat, xs) => {
*/
export const choose = (...xs) => chooseWith(rand, xs);
/**
* As with {choose}, but the structure comes from the chosen values, rather
* than the pattern you're using to choose with.
* @param {...any} xs
* @returns {Pattern} - a continuous pattern.
*/
export const chooseIn = (...xs) => chooseInWith(rand, xs);
/**
* Chooses from the given list of values (or patterns of values), according
* to the pattern that the method is called on. The pattern should be in
* the range 0 .. 1.
* @name choose
* @tags temporal
* @param {...any} xs
* @memberof Pattern.prototype
@@ -646,6 +664,7 @@ Pattern.prototype.choose = function (...xs) {
/**
* As with choose, but the pattern that this method is called on should be
* in the range -1 .. 1
* @name choose2
* @tags temporal
* @param {...any} xs
* @memberof Pattern.prototype
@@ -779,12 +798,10 @@ export const perlin = signal((t, controls) => _perlin(t, controls.randSeed));
export const berlin = signal((t, controls) => _berlin(t, controls.randSeed));
/**
* `degradeByWith` is like `degradeBy`, but with control over the random or other signal used to filter out the events.
*
* `degradeByWith` is like `degradeBy`, but with control over the signal used to degrade the pattern.
* It removes events from a pattern given a signal of numbers and a cutoff value for interpreting that pattern as true or false.
* `degradeBy(x)` is essentially `degradeByWith(rand, x)`
*
* This allows you to do things other than with `rand`, see examples below
*
* @name degradeByWith
* @param {Pattern|number} test
* @param {Pattern|number} testAgainst
@@ -1048,7 +1065,6 @@ export const never = register('never', function (_, pat) {
});
/**
*
* Shorthand for `.sometimesBy(1, fn)` (always calls fn)
*
* @tags temporal
@@ -1062,13 +1078,19 @@ export const always = register('always', function (func, pat) {
return func(pat);
});
//keyname: string | Array<string>
//keyname reference: https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values
/**
* checks if a key is down
* @param {string | Array<string>} keyname reference: https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values
* @returns {boolean}
*/
export function _keyDown(keyname) {
if (Array.isArray(keyname) === false) {
keyname = [keyname];
}
const keyState = getCurrentKeyboardState();
if (keyState === undefined) {
return false;
}
return keyname.every((x) => {
const keyName = keyAlias.get(x) ?? x;
return keyState[keyName];
@@ -1104,7 +1126,6 @@ export const whenKey = register('whenKey', function (input, func, pat) {
* @example
* keyDown("Control:j").pick([s("bd(5,8)"), s("cp(3,8)")])
*/
export const keyDown = register('keyDown', function (pat) {
return pat.fmap(_keyDown);
});
@@ -1117,6 +1138,7 @@ export const keyDown = register('keyDown', function (pat) {
* See also its reciprocal, `per`, also known as `perCycle`.
*
* @tags temporal
* @type {Pattern}
* @example
* // Shorter events are lower in pitch
* sound("saw saw [saw saw] saw")
@@ -1129,14 +1151,34 @@ export const cyclesPer = new Pattern(function (state) {
return [new Hap(undefined, state.span, state.span.duration)];
});
/**
* A pattern measuring the duration of events, in seconds per event.
* `secondsPer` doesn't have structure itself, but takes structue, and therefore
* event durations, from the pattern that it is combined with.
* For example `secondsPer.struct("1 1 [1 1] 1")` with `cps = 1` would give the same as `"0.25 0.25 [0.125 0.125] 0.25"`.
*
* @tags temporal
* @synonyms sper
* @example
* note("f a [c d] e")
* .dec(secondsPer.mul(1))
*/
export const secondsPer = new Pattern(function (state) {
return [new Hap(undefined, state.span, state.span.duration.div(state.controls?._cps ?? 0.5))];
});
export const sper = secondsPer;
/**
* A pattern measuring the 'shortness' of events, or in other words, the duration of pattern events,
* in events per cycle. `per` doesn't have structure itself, but takes structure, and therefore
* event durations, from the pattern that it is combined with.
* For example `per.struct("1 1 [1 1] 1")` would give the same as `"4 4 [8 8] 4"`.
* See also its reciprocal, `cyclesPer`.
* @global
* @tags temporal
* @synonyms perCycle
* @type {Pattern}
* @example
* // Shorter events are more distorted
* n("0 0*2 0 0*2 0 [0 0 0]@2").sound("bd")
@@ -1154,6 +1196,7 @@ export const perCycle = per;
* returned value increases by one. `perx.struct("1 1 [1 [1 1]] 1")` would therefore be
* the same as `"3 3 [4 [5 5]] 3"`.
* @tags temporal
* @type {Pattern}
*/
export const perx = new Pattern(function (state) {
const n = Fraction(1).div(state.span.duration);
@@ -1165,6 +1208,7 @@ export const perx = new Pattern(function (state) {
* Mainly useful in combination with other functions that reset the cycle. See also
* `close`.
* @tags temporal
* @type {Pattern}
* @example
* sound("bd sd [- bd] sd".fast(2))
* .lpf(open.slow(4).range(300,3000)) // close envelope over 4 cycles
@@ -1176,6 +1220,7 @@ export const open = signal((t) => t.min(1));
* The same as `open`, but goes from `1` to `0` over one cycle, and then
* stays on `0` forever.
* @tags temporal
* @type {Pattern}
* @example
* sound("bd sd [- bd] sd".fast(2))
* .lpf(close.slow(4).range(300,3000)) // close envelope over 4 cycles
@@ -1272,3 +1317,60 @@ function __smoothHap(time, hapA, hapB) {
const progress = time.sub(hapA.whole.begin).div(hapA.whole.end.sub(hapA.whole.begin));
return new Hap(hapA.whole, hapA.part, a + (b - a) * (progress.lt(0) ? 0 : progress), context);
}
/**
* Creates a pattern of numbers in base b from a number or pattern of numbers
* limited to d digits long from the right
*
* @name base
* @tags generators
* @param {number | Pattern | number[]} n - number to convert
* @param {number | Pattern} b - base to convert to (defaults to 10)
* @param {number | Pattern} d - max number of digits to produce for each n (defaults to 0 for all)
* @returns {number | Pattern}
* @example
* $: note(base("7175 543", 10, 3)).scale("c:major").s("saw")
* // $: note("1 7 5 5 4 3").scale("c:major").s("saw")
*/
export const base = (n, b = 10, d = 0) => {
if (Array.isArray(n)) {
n = sequence(n);
}
n = reify(n);
b = reify(b);
d = reify(d);
return d
.withValue((e) => {
return b
.withValue((c) => {
return n
.withValue((v) => {
let digits = [];
let value = v;
while (value > 0) {
digits.unshift(value % c);
value = Math.floor(value / c);
}
if (e) {
const l = digits.length;
if (l > e) {
digits = digits.slice(-1 * e);
}
/*
if (l < e){
for (let i = l; i < e; i++) {
digits.unshift("~");//0); //Would like to be padding this but ~- doesn't work
}
console.log("digits", digits);
}
*/
}
return sequence(digits);
})
.squeezeJoin();
})
.squeezeJoin();
})
.squeezeJoin();
};
+2 -1
View File
@@ -4,7 +4,8 @@ Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/
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 { fastcat, stack, slowcat, silence, pure } from '../pattern.mjs';
import { silence, pure } from '../pattern-atoms.mjs';
import { slowcat, fastcat, stack } from '../pattern-combiners.mjs';
import { describe, it, expect } from 'vitest';
import drawLine from '../drawLine.mjs';
+1 -1
View File
@@ -1,6 +1,6 @@
import { bjorklund } from '../euclid.mjs';
import { describe, expect, it } from 'vitest';
import { fastcat } from '../pattern.mjs';
import { fastcat } from '../pattern-combiners.mjs';
describe('bjorklund', () => {
it('should apply bjorklundlund to ons and steps', () => {
+2 -1
View File
@@ -52,13 +52,14 @@ import {
stackLeft,
stackRight,
stackCentre,
stackCenter,
stepcat,
sometimes,
expand,
arp,
} from '../index.mjs';
import { reify, stackCenter } from '../pattern.mjs';
import { reify } from '../pattern-atoms.mjs';
import { steady } from '../signal.mjs';
+1 -1
View File
@@ -4,7 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/
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 { pure } from '../pattern.mjs';
import { pure } from '../pattern-atoms.mjs';
import {
_mod,
compose,
+85 -16
View File
@@ -212,6 +212,11 @@ export function curry(func, overload, arity = func.length) {
return fn;
}
/**
* parses a number. supports midi notes as strings
* @param {number | string} numOrString
* @returns {number}
*/
export function parseNumeral(numOrString) {
const asNumber = Number(numOrString);
if (!isNaN(asNumber)) {
@@ -223,10 +228,20 @@ export function parseNumeral(numOrString) {
throw new Error(`cannot parse as numeral: "${numOrString}"`);
}
/**
* map over the arguments of a function
* @param {Function} fn
* @param {Function} mapFn
* @returns {Function}
*/
export function mapArgs(fn, mapFn) {
return (...args) => fn(...args.map(mapFn));
}
/** converts the arguments of a function into numbers
* @param {Function} fn
* @returns {Function}
*/
export function numeralArgs(fn) {
return mapArgs(fn, parseNumeral);
}
@@ -328,7 +343,12 @@ export const sol2note = (n, notation = 'letters') => {
return note + oct;
};
// Remove duplicates from list
/**
* Remove duplicates from list
* @template T
* @param {T[]} a
* @returns {T[]}
*/
export function uniq(a) {
var seen = {};
return a.filter(function (item) {
@@ -336,14 +356,26 @@ export function uniq(a) {
});
}
// Remove duplicates from list, sorting in the process. Mutates argument!
/**
* Remove duplicate primitives from list, sorting in the process. Mutates argument!
* Use {@link uniqsortr} for objects instead.
* @template T
* @param {T[]} a (only primitives)
* @returns {T[]}
*/
export function uniqsort(a) {
return a.sort().filter(function (item, pos, ary) {
return !pos || item != ary[pos - 1];
});
}
// rational version
/**
* Remove duplicate objects from list, sorting in the process. Mutates argument!
* Use {@link uniqsort} for primitives instead.
* @template T
* @param {T[]} a (only objects)
* @returns {T[]}
*/
export function uniqsortr(a) {
return a
.sort((x, y) => x.compare(y))
@@ -375,22 +407,47 @@ export function base64ToUnicode(base64String) {
return decodedText;
}
/**
* converts unicode text into a URL hash
* @ignore
* @param {string} code
* @returns {string}
*/
export function code2hash(code) {
return encodeURIComponent(unicodeToBase64(code));
//return '#' + encodeURIComponent(btoa(code));
}
/**
* converts the URL hash into unicode text
* @ignore
* @param {string} hash
* @returns {string}
*/
export function hash2code(hash) {
return base64ToUnicode(decodeURIComponent(hash));
//return atob(decodeURIComponent(codeParam || ''));
}
/**
* maps over the entries of an object
* @param {object} obj
* @param {Function} fn
* @returns {object}
*/
export function objectMap(obj, fn) {
if (Array.isArray(obj)) {
return obj.map(fn);
}
return Object.fromEntries(Object.entries(obj).map(([k, v], i) => [k, fn(v, k, i)]));
}
/**
* converts the cycle into seconds
* @param {number} cycle
* @param {number} cps
* @returns {number} `cycle / cps`
*/
export function cycleToSeconds(cycle, cps) {
return cycle / cps;
}
@@ -454,6 +511,10 @@ export class ClockCollator {
}
}
/**
* The total time that strudel has been running
* @returns {number}
*/
export function getPerformanceTimeSeconds() {
return performance.now() * 0.001;
}
@@ -474,21 +535,24 @@ export const keyAlias = new Map([
]);
let keyState;
/**
* returns the all the keys currently being pressed or released
* @returns {object | void}
*/
export function getCurrentKeyboardState() {
if (keyState == null) {
if (typeof window === 'undefined') {
return;
}
keyState = {};
// Listen for the keydown event to mark the key as pressed
window.addEventListener('keydown', (event) => {
keyState[event.key] = true; // Mark the key as pressed
});
if (typeof window !== 'undefined') {
// Listen for the keydown event to mark the key as pressed
window.addEventListener('keydown', (event) => {
keyState[event.key] = true; // Mark the key as pressed
});
// Listen for the keyup event to mark the key as released
window.addEventListener('keyup', (event) => {
keyState[event.key] = false; // Mark the key as released
});
// Listen for the keyup event to mark the key as released
window.addEventListener('keyup', (event) => {
keyState[event.key] = false; // Mark the key as released
});
}
}
return { ...keyState }; // Return a shallow copy of the key state object
@@ -514,8 +578,13 @@ export function getCurrentKeyboardState() {
// return lcm((x * y) / gcd(x, y), ...z);
// };
// Takes values -- typically derived from events, i.e. `hap`s -- and renders them
// into a readable format
/**
* Takes values -- typically derived from events, i.e. `hap`s -- and renders them
* into a readable format
* @param {*} value
* @param {boolean} [compact=false] creates a compacter version
* @returns {boolean}
*/
export function stringifyValues(value, compact = false) {
return typeof value === 'object'
? compact
+6
View File
@@ -7,6 +7,12 @@ This program is free software: you can redistribute it and/or modify it under th
import { curry } from './util.mjs';
import { logger } from './logger.mjs';
/** combine two objects into one
* @param {object} a
* @param {object} b
* @param {Function} func
* @returns {object}
*/
export function unionWithObj(a, b, func) {
if (b?.value !== undefined && Object.keys(b).length === 1) {
// https://codeberg.org/uzu/strudel/issues/1026
+2 -1
View File
@@ -442,7 +442,8 @@ export function applyFM(param, value, begin) {
} else {
control = `fmi${i}${j}`;
}
const amt = value[control];
// If we can't find fm3/fm2/fm1/etc, fall back to fm32/fm21/fm10/etc
const amt = value[control] ?? (i === j + 1 ? value[`fmi${i}${j}`] : undefined);
if (!amt) continue;
let io = [];
for (let [isMod, idx] of [
+2 -1
View File
@@ -35,7 +35,7 @@ function humanFileSize(bytes, si) {
* Has optional param `n` (for instance, the `2` in `s("casio:2")`)
*
* Note: `must` be called with await, otherwise you'll get a pending Promise object.
*
* @global
* @name getDuration
* @synonyms getDur
* @tags samples
@@ -260,6 +260,7 @@ export async function fetchSampleMap(url) {
/**
* Loads a collection of samples to use with `s`
* @tags samples
* @global
* @example
* samples('github:tidalcycles/dirt-samples');
* s("[bd ~]*2, [~ hh]*2, ~ sd")
+5 -2
View File
@@ -39,6 +39,7 @@ export let maxPolyphony = DEFAULT_MAX_POLYPHONY;
* start to die out in first-in-first-out order once the max polyphony has been hit
*
* @name setMaxPolyphony
* @global
* @tags superdough
* @param {number} polyphony Max polyphony. Defaults to 128
* @example
@@ -76,7 +77,7 @@ export function applyGainCurve(val) {
/**
* Apply a function to all gains provided in patterns. Can be used to rescale gain to be
* quadratic, exponential, etc. rather than linear
*
* @global
* @name setGainCurve
* @tags amplitude, superdough
* @param {Function} newGainCurveFunc function to apply to all gain values
@@ -130,9 +131,10 @@ async function aliasBankPath(path) {
/**
* Register an alias for a bank of sounds.
* @global
* @param {...any} args either one or two arguments. first argument is bank to alias. Second argument is alias to use for the bank.
* Optionally accepts a single argument map of bank aliases.
* Optionally accepts a single argument string of a path to a JSON file containing bank aliases.
* @param {...any} args either one or two arguments. first argument is bank to alias. Second argument is alias to use for the bank.
* @returns {void}
* @tags samples
*/
@@ -153,6 +155,7 @@ export async function aliasBank(...args) {
/**
* Register an alias for a sound.
* @global
* @tags samples
* @param {string} original - The original sound name
* @param {string} alias - The alias to use for the sound
+83
View File
@@ -404,6 +404,89 @@ export function registerSynthSounds() {
{ prebake: true, type: 'input' },
);
registerSound(
'goabd',
(t, value, onended) => {
const {
duration,
attack = 0,
hold = 0.2,
decay = 0.25,
sustain = 0,
release = 0,
pdecay = 1,
penv = 84,
pcurve = 0.85,
clip,
} = value;
const ctx = getAudioContext();
const soundGain = 0.5;
const mixGain = 1;
const freq = getFrequencyFromValue(value, 24);
const f = getWorklet(ctx, 'goabd-freq-env-processor', {
begin: t,
end: t + pdecay,
freq0: freq * Math.pow(2, penv / 12),
freq1: freq,
pcurve: pcurve,
});
const o = ctx.createOscillator();
o.type = 'sine';
o.frequency.value = 0;
f.connect(o.frequency);
const g = gainNode(soundGain);
let soundDuration = attack + hold + decay;
if (sustain > 0) {
soundDuration = Math.max(soundDuration, duration) + release;
}
if (attack > 0) {
g.gain.setValueAtTime(0.0001, t);
g.gain.exponentialRampToValueAtTime(soundGain, t + attack);
} else {
g.gain.setValueAtTime(soundGain, t);
}
if (hold > 0) {
g.gain.setValueAtTime(soundGain, t + attack + hold);
}
g.gain.exponentialRampToValueAtTime(Math.max(0.0001, sustain), t + soundDuration - release);
g.gain.exponentialRampToValueAtTime(0.0001, t + soundDuration);
o.start(t);
const mix = gainNode(mixGain);
onceEnded(o, () => {
releaseAudioNode(f);
releaseAudioNode(o);
releaseAudioNode(g);
releaseAudioNode(mix);
onended();
});
const node = o.connect(g).connect(mix);
// prevent clicking
let mixDuration = soundDuration;
if (clip != null) {
mixDuration = Math.min(clip * duration, mixDuration);
}
const mixEnd = t + mixDuration;
mix.gain.setValueAtTime(mixGain, mixEnd - 0.01);
mix.gain.linearRampToValueAtTime(0, mixEnd);
o.stop(mixEnd);
return {
node,
nodes: { source: [o] },
stop: (endTime) => {
o.stop(endTime);
},
};
},
{ type: 'synth', prebake: true },
);
[...noises].forEach((s) => {
registerSound(
s,
+1
View File
@@ -111,6 +111,7 @@ export function getCommonSampleInfo(hapValue, bank) {
}
/** Selects entries from `source` and renames them via `map`
* @global
* @tags internals
* @param {object} source
* @param {*} map
+1 -1
View File
@@ -184,7 +184,7 @@ export function registerWaveTable(key, tables, params) {
/**
* Loads a collection of wavetables to use with `s`
*
* @global
* @param {string} url
* @param {*} frameLen
* @param {string} json
+45
View File
@@ -850,6 +850,8 @@ registerProcessor('pulse-oscillator', PulseOscillatorProcessor);
/** BYTE BEATS
* @tags internals
* @global
* @typedef Chyx
*/
const chyx = {
/*bit*/ bitC: function (x, y, z) {
@@ -983,6 +985,49 @@ class ByteBeatProcessor extends AudioWorkletProcessor {
registerProcessor('byte-beat-processor', ByteBeatProcessor);
class GoaBdFreqEnvProcessor extends AudioWorkletProcessor {
static get parameterDescriptors() {
return [
{ name: 'begin', defaultValue: 0 },
{ name: 'end', defaultValue: 0 },
{ name: 'freq0', defaultValue: 55 * 64 },
{ name: 'freq1', defaultValue: 55 },
{ name: 'pcurve', defaultValue: 0.5 },
];
}
constructor() {
super();
this.p0 = 0.006699687;
this.p1 = 0.00001884606;
this.time = 0;
}
process(_inputs, outputs, params) {
const begin = params['begin'][0];
const end = params['end'][0];
if (currentTime >= end) {
return false;
}
if (currentTime <= begin) {
return true;
}
const out = outputs[0][0];
const freq0 = params['freq0'][0];
const freq1 = params['freq1'][0];
const pcurve = params['pcurve'][0];
const p = (1 - pcurve) * this.p0 + pcurve * this.p1;
const dt = (INVSR * 1) / (end - begin);
for (let i = 0; i < out.length; i++) {
out[i] = freq1 + (freq0 - freq1) / (1 + this.time / p);
this.time += dt;
}
return true;
}
}
registerProcessor('goabd-freq-env-processor', GoaBdFreqEnvProcessor);
class EnvelopeProcessor extends AudioWorkletProcessor {
static get parameterDescriptors() {
return [
+1
View File
@@ -196,6 +196,7 @@ export const rootNotes = register('rootNotes', function (octave, pat) {
* @name voicing
* @tags tonal
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* n("0 1 2 3").chord("<C Am F G>").voicing()
*/
+37 -3
View File
@@ -12,7 +12,10 @@ import { initAudioOnFirstClick, registerSynthSounds, webaudioRepl } from '@strud
import { evaluate as _evaluate, transpiler } from '@strudel/transpiler';
import { miniAllStrings } from '@strudel/mini';
// init logic
/**
* init logic
* @global
*/
export async function defaultPrebake() {
const loadModules = evalScope(
evalScope,
@@ -30,6 +33,28 @@ export async function defaultPrebake() {
let initDone;
let repl;
/** initiates strudel
* @global
* @param {object} options
* @param {*} options.onSchedule
* @param {*} options.defaultOutput
* @param {*} options.onEvalError
* @param {*} options.beforeEval
* @param {*} options.beforeStart
* @param {*} options.afterEval
* @param {*} options.getTime
* @param {*} options.transpiler
* @param {*} options.onToggle
* @param {*} options.editPattern
* @param {*} options.onUpdateState
* @param {*} options.sync = false
* @param {*} options.setInterval
* @param {*} options.clearInterval
* @param {*} options.id
* @param {*} options.mondo = false
* @param {*} options.prebake
* @returns {object}
*/
export function initStrudel(options = {}) {
initAudioOnFirstClick();
options.miniAllStrings !== false && miniAllStrings();
@@ -58,12 +83,21 @@ Pattern.prototype.play = function () {
return this;
};
// stop playback
/**
* stop playback
* @global
*/
export function hush() {
repl.stop();
}
// evaluate and play the given code using the transpiler
/**
* evaluate and play the given code using the transpiler
* @global
* @param {*} code
* @param {*} autoplay
* @returns {*}
*/
export async function evaluate(code, autoplay = true) {
return repl.evaluate(code, autoplay);
}
+2
View File
@@ -99,6 +99,7 @@ function clearScreen(smear = 0, smearRGB = `0,0,0`, ctx = getDrawContext()) {
* Renders an oscilloscope for the frequency domain of the audio signal.
* @name fscope
* @tags visualization
* @memberof Pattern.prototype
* @param {object} config object that may have the following arguments
* @param {string} config.color line color as hex or color name. defaults to white.
* @param {number} config.scale scales the y-axis. Defaults to 0.25
@@ -124,6 +125,7 @@ Pattern.prototype.fscope = function (config = {}) {
/**
* Renders an oscilloscope for the time domain of the audio signal.
* @name scope
* @memberof Pattern.prototype
* @synonyms tscope
* @tags visualization
* @param {object} config optional config with options:
+1
View File
@@ -5,6 +5,7 @@ import { analysers, getAnalyzerData } from 'superdough';
/**
* Renders a spectrum analyzer for the incoming audio signal.
* @name spectrum
* @memberof Pattern.prototype
* @tags visualization
* @param {object} config optional config with options:
* @param {number} [thickness=3] line thickness in px (default 3)
+3 -3
View File
@@ -93,7 +93,7 @@ export async function renderPatternAudio(
/**
* Renders a whole pattern to an OfflineAudioContext in one go.
*
* @global
* @param {OfflineAudioContext} audioContext The OfflineAudioContext to render to
* @param {Pattern} pattern The pattern to render
* @param {ExportCheckpoint[]} checkpoints A list of checkpoints indicating the cps changes throughout the song
@@ -122,7 +122,7 @@ async function renderPatternAudioWhole(audioContext, pattern, checkpoints) {
* overall audio graph smaller.
*
* Not suppoerted on Firefox
*
* @global
* @param {OfflineAudioContext} audioContext
* @param {Pattern} pattern
* @param {ExportCheckpoint[]} checkpoints
@@ -184,7 +184,7 @@ async function renderPatternAudioInChunks(audioContext, pattern, checkpoints) {
/**
* Schedule all haps between 2 checkpoints
*
* @global
* @param {Pattern} pattern The pattern to render
* @param {number} chunkStartTime The time in seconds where the chunk starts
* @param {ExportCheckpoint} checkpointA The starting checkpoint of the chunk
+6 -1
View File
@@ -7,7 +7,12 @@ This program is free software: you can redistribute it and/or modify it under th
import { register, _mod, parseNumeral, removeUndefineds, Pattern, parray, State } from '@strudel/core';
import Tune from './tunejs.js';
// returns a list of frequency ratios for given edo scale
/**
* returns a list of frequency ratios for given edo scale
* @param {string} name
* @returns {number[]}
* @global
*/
export function edo(name) {
if (!/^[1-9]+[0-9]*edo$/.test(name)) {
throw new Error('not an edo scale: "' + name + '"');
-87
View File
@@ -467,9 +467,6 @@ importers:
specifier: workspace:*
version: link:../mondo
devDependencies:
mondo:
specifier: '*'
version: 0.4.4
vite:
specifier: ^6.0.11
version: 6.0.11(@types/node@22.10.10)(jiti@2.4.2)(lightningcss@1.29.1)(terser@5.37.0)(yaml@2.7.0)
@@ -3337,10 +3334,6 @@ packages:
resolution: {integrity: sha512-groO71Fvi5SWpxjI9Ia+chy0QBwT61mg6yxJV27f5YFf+Mw+STT75K6SHySpP8Co5LsCrtsbCH5dJZSRtkSKaQ==}
engines: {node: '>= 14.0.0'}
amdefine@1.0.1:
resolution: {integrity: sha512-S2Hw0TtNkMJhIabBwIojKL9YHO5T0n5eNqWJ7Lrlel/zDbftQpxpapi8tZs3X1HWa+u+QeydGmzzNU0m09+Rcg==}
engines: {node: '>=0.4.2'}
ansi-align@3.0.1:
resolution: {integrity: sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==}
@@ -3473,9 +3466,6 @@ packages:
resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==}
engines: {node: '>= 0.4'}
async@0.2.10:
resolution: {integrity: sha512-eAkdoKxU6/LkKDBzLpT+t6Ff5EtfSF4wx1WfJiPEEV7WNLnDaRXk0oVysiEPm262roaachGexwUv94WhSgN5TQ==}
async@3.2.6:
resolution: {integrity: sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==}
@@ -3718,9 +3708,6 @@ packages:
claviature@0.1.0:
resolution: {integrity: sha512-Ai12axNwQ7x/F9QAj64RYKsgvi5Y33+X3GUSKAC/9s/adEws8TSSc0efeiqhKNGKBo6rT/c+CSCwSXzXxwxZzQ==}
cldr-plurals@1.0.0:
resolution: {integrity: sha512-xGkehDsjj/ng1LtYiAzdiqDgqTQ/qmWafDlB6R8CfXbpXe4Ge2Tl4l7gxiA+yaD1WCTP3EVfwerdmVwfco7vxw==}
clean-stack@2.2.0:
resolution: {integrity: sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==}
engines: {node: '>=6'}
@@ -4826,9 +4813,6 @@ packages:
engines: {node: '>=16 || 14 >=14.17'}
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
globalize@0.1.1:
resolution: {integrity: sha512-5e01v8eLGfuQSOvx2MsDMOWS0GFtCx1wPzQSmcHw4hkxFzrQDBO3Xwg/m8Hr/7qXMrHeOIE29qWVzyv06u1TZA==}
globals@11.12.0:
resolution: {integrity: sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==}
engines: {node: '>=4'}
@@ -4890,11 +4874,6 @@ packages:
h3@1.14.0:
resolution: {integrity: sha512-ao22eiONdgelqcnknw0iD645qW0s9NnrJHr5OBz4WOMdBdycfSas1EQf1wXRsm+PcB2Yoj43pjBPwqIpJQTeWg==}
handlebars@1.1.2:
resolution: {integrity: sha512-6lekK3aSHE7XnEqEs+JWQJRSRdCqJYHEVjEfWWZv9pjLUYZNeP26EtlgOrpDCSX+k5N1m74urTbztgBOCko1Kg==}
engines: {node: '>=0.4.7'}
hasBin: true
handlebars@4.7.8:
resolution: {integrity: sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==}
engines: {node: '>=0.4.7'}
@@ -6053,10 +6032,6 @@ packages:
engines: {node: '>=18'}
hasBin: true
mondo@0.4.4:
resolution: {integrity: sha512-3ot6iKwC9KZvwmyZ9dgPCnlt0O1GuBnK8QZyhnoJdtkIiRL9X/cmQuu88CbFSznQx6bq19xQdwJHpv8hggH62Q==}
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
mrmime@2.0.0:
resolution: {integrity: sha512-eu38+hdgojoyq63s+yTpN4XMBdt5l8HhMhc4VKLO9KM5caLIBvUm4thi7fFaxyTmCKeNnXZ5pAlBwCUnhA09uw==}
engines: {node: '>=10'}
@@ -6312,9 +6287,6 @@ packages:
resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==}
engines: {node: '>=12'}
optimist@0.3.7:
resolution: {integrity: sha512-TCx0dXQzVtSCg2OgY/bO9hjM9cV4XYx09TVK+s3+FhkjT6LovsLe+pPMzpWf+6yXK/hUizs2gUoTw3jHM0VaTQ==}
optionator@0.9.4:
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
engines: {node: '>= 0.8.0'}
@@ -7240,10 +7212,6 @@ packages:
source-map-support@0.5.21:
resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==}
source-map@0.1.43:
resolution: {integrity: sha512-VtCvB9SIQhk3aF6h+N85EaqIaBFIAfZ9Cu+NJHHVvc8BbEcnvDcFw6sqQ2dQrT6SlOrZq3tIvyD9+EGq/lJryQ==}
engines: {node: '>=0.8.0'}
source-map@0.5.7:
resolution: {integrity: sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==}
engines: {node: '>=0.10.0'}
@@ -7690,11 +7658,6 @@ packages:
ufo@1.5.4:
resolution: {integrity: sha512-UsUk3byDzKd04EyoZ7U4DOlxQaD14JUKQl6/P7wiX4FNvUfm3XL246n9W5AmqwW5RSFJ27NAuM0iLscAOYUiGQ==}
uglify-js@2.3.6:
resolution: {integrity: sha512-T2LWWydxf5+Btpb0S/Gg/yKFmYjnX9jtQ4mdN9YRq73BhN21EhU0Dvw3wYDLqd3TooGUJlCKf3Gfyjjy/RTcWA==}
engines: {node: '>=0.4.0'}
hasBin: true
uglify-js@3.19.3:
resolution: {integrity: sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==}
engines: {node: '>=0.8.0'}
@@ -7713,9 +7676,6 @@ packages:
underscore@1.13.7:
resolution: {integrity: sha512-GMXzWtsc57XAtguZgaQViUOzs0KTkk8ojr3/xAxXLITqf/3EMwxC0inyETfDFjH/Krbhuep0HNbbjI9i/q3F3g==}
underscore@1.5.2:
resolution: {integrity: sha512-yejOFsRnTJs0N9CK5Apzf6maDO2djxGoLLrlZlvGs2o9ZQuhIhDL18rtFyy4FBIbOkzA6+4hDgXbgz5EvDQCXQ==}
undici-types@6.20.0:
resolution: {integrity: sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==}
@@ -8096,10 +8056,6 @@ packages:
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
wordwrap@0.0.3:
resolution: {integrity: sha512-1tMA907+V4QmxV7dbRvb4/8MaRALK6q9Abid3ndMYnbyo8piisCmeONVqVSXqQA3KaP4SLt5b7ud6E2sqP8TFw==}
engines: {node: '>=0.4.0'}
wordwrap@1.0.0:
resolution: {integrity: sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==}
@@ -11185,9 +11141,6 @@ snapshots:
'@algolia/requester-fetch': 5.20.0
'@algolia/requester-node-http': 5.20.0
amdefine@1.0.1:
optional: true
ansi-align@3.0.1:
dependencies:
string-width: 4.2.3
@@ -11399,9 +11352,6 @@ snapshots:
async-function@1.0.0: {}
async@0.2.10:
optional: true
async@3.2.6: {}
asynckit@0.4.0: {}
@@ -11665,8 +11615,6 @@ snapshots:
claviature@0.1.0: {}
cldr-plurals@1.0.0: {}
clean-stack@2.2.0: {}
cli-boxes@3.0.0: {}
@@ -12868,8 +12816,6 @@ snapshots:
minipass: 4.2.8
path-scurry: 1.11.1
globalize@0.1.1: {}
globals@11.12.0: {}
globals@14.0.0: {}
@@ -12936,12 +12882,6 @@ snapshots:
uncrypto: 0.1.3
unenv: 1.10.0
handlebars@1.1.2:
dependencies:
optimist: 0.3.7
optionalDependencies:
uglify-js: 2.3.6
handlebars@4.7.8:
dependencies:
minimist: 1.2.8
@@ -14536,13 +14476,6 @@ snapshots:
requirejs: 2.3.7
requirejs-config-file: 4.0.0
mondo@0.4.4:
dependencies:
cldr-plurals: 1.0.0
globalize: 0.1.1
handlebars: 1.1.2
underscore: 1.5.2
mrmime@2.0.0: {}
ms@2.0.0: {}
@@ -14846,10 +14779,6 @@ snapshots:
is-docker: 2.2.1
is-wsl: 2.2.0
optimist@0.3.7:
dependencies:
wordwrap: 0.0.3
optionator@0.9.4:
dependencies:
deep-is: 0.1.4
@@ -15997,11 +15926,6 @@ snapshots:
buffer-from: 1.1.2
source-map: 0.6.1
source-map@0.1.43:
dependencies:
amdefine: 1.0.1
optional: true
source-map@0.5.7: {}
source-map@0.6.1: {}
@@ -16482,13 +16406,6 @@ snapshots:
ufo@1.5.4: {}
uglify-js@2.3.6:
dependencies:
async: 0.2.10
optimist: 0.3.7
source-map: 0.1.43
optional: true
uglify-js@3.19.3:
optional: true
@@ -16505,8 +16422,6 @@ snapshots:
underscore@1.13.7: {}
underscore@1.5.2: {}
undici-types@6.20.0: {}
unenv@1.10.0:
@@ -16881,8 +16796,6 @@ snapshots:
word-wrap@1.2.5: {}
wordwrap@0.0.3: {}
wordwrap@1.0.0: {}
workbox-background-sync@7.0.0:
+108 -3
View File
@@ -611,7 +611,22 @@ exports[`runs examples > example "FX" example index 1 1`] = `
]
`;
exports[`runs examples > example "Hap" example index 0 1`] = `[]`;
exports[`runs examples > example "Hap" example index 0 1`] = `
[
"[ 0/1 → 1/2 | s:sd ]",
"[ 0/1 → 1/1 | s:bd ]",
"[ 1/2 → 1/1 | s:sd ]",
"[ 1/1 → 3/2 | s:sd ]",
"[ 1/1 → 2/1 | s:bd ]",
"[ 3/2 → 2/1 | s:sd ]",
"[ 2/1 → 5/2 | s:sd ]",
"[ 2/1 → 3/1 | s:bd ]",
"[ 5/2 → 3/1 | s:sd ]",
"[ 3/1 → 7/2 | s:sd ]",
"[ 3/1 → 4/1 | s:bd ]",
"[ 7/2 → 4/1 | s:sd ]",
]
`;
exports[`runs examples > example "Hap" example index 1 1`] = `
[
@@ -1310,6 +1325,23 @@ exports[`runs examples > example "beat" example index 1 1`] = `
]
`;
exports[`runs examples > example "beat" example index 2 1`] = `
[
"[ 0/1 → 1/8 | s:sd ]",
"[ 3/8 → 1/2 | s:sd ]",
"[ 3/4 → 7/8 | s:sd ]",
"[ 1/1 → 9/8 | s:sd ]",
"[ 11/8 → 3/2 | s:sd ]",
"[ 7/4 → 15/8 | s:sd ]",
"[ 2/1 → 17/8 | s:sd ]",
"[ 19/8 → 5/2 | s:sd ]",
"[ 11/4 → 23/8 | s:sd ]",
"[ 3/1 → 25/8 | s:sd ]",
"[ 27/8 → 7/2 | s:sd ]",
"[ 15/4 → 31/8 | s:sd ]",
]
`;
exports[`runs examples > example "begin" example index 0 1`] = `
[
"[ 0/1 → 1/2 | s:rave begin:0 ]",
@@ -7116,7 +7148,30 @@ exports[`runs examples > example "keep" example index 0 1`] = `
]
`;
exports[`runs examples > example "keyDown" example index 0 1`] = `[]`;
exports[`runs examples > example "keyDown" example index 0 1`] = `
[
"[ 0/1 → 1/8 | s:bd ]",
"[ 1/4 → 3/8 | s:bd ]",
"[ 3/8 → 1/2 | s:bd ]",
"[ 5/8 → 3/4 | s:bd ]",
"[ 3/4 → 7/8 | s:bd ]",
"[ 1/1 → 9/8 | s:bd ]",
"[ 5/4 → 11/8 | s:bd ]",
"[ 11/8 → 3/2 | s:bd ]",
"[ 13/8 → 7/4 | s:bd ]",
"[ 7/4 → 15/8 | s:bd ]",
"[ 2/1 → 17/8 | s:bd ]",
"[ 9/4 → 19/8 | s:bd ]",
"[ 19/8 → 5/2 | s:bd ]",
"[ 21/8 → 11/4 | s:bd ]",
"[ 11/4 → 23/8 | s:bd ]",
"[ 3/1 → 25/8 | s:bd ]",
"[ 13/4 → 27/8 | s:bd ]",
"[ 27/8 → 7/2 | s:bd ]",
"[ 29/8 → 15/4 | s:bd ]",
"[ 15/4 → 31/8 | s:bd ]",
]
`;
exports[`runs examples > example "lastOf" example index 0 1`] = `
[
@@ -8621,6 +8676,8 @@ exports[`runs examples > example "note" example index 3 1`] = `
]
`;
exports[`runs examples > example "nothing" example index 0 1`] = `[]`;
exports[`runs examples > example "nrpnn" example index 0 1`] = `
[
"[ 0/1 → 1/1 | note:c4 nrpnn:[1 8] nrpv:123 midichan:1 ]",
@@ -11801,6 +11858,31 @@ exports[`runs examples > example "scut" example index 0 1`] = `
]
`;
exports[`runs examples > example "secondsPer" example index 0 1`] = `
[
"[ 0/1 → 1/4 | note:f decay:0.5 ]",
"[ 1/4 → 1/2 | note:a decay:0.5 ]",
"[ 1/2 → 5/8 | note:c decay:0.25 ]",
"[ 5/8 → 3/4 | note:d decay:0.25 ]",
"[ 3/4 → 1/1 | note:e decay:0.5 ]",
"[ 1/1 → 5/4 | note:f decay:0.5 ]",
"[ 5/4 → 3/2 | note:a decay:0.5 ]",
"[ 3/2 → 13/8 | note:c decay:0.25 ]",
"[ 13/8 → 7/4 | note:d decay:0.25 ]",
"[ 7/4 → 2/1 | note:e decay:0.5 ]",
"[ 2/1 → 9/4 | note:f decay:0.5 ]",
"[ 9/4 → 5/2 | note:a decay:0.5 ]",
"[ 5/2 → 21/8 | note:c decay:0.25 ]",
"[ 21/8 → 11/4 | note:d decay:0.25 ]",
"[ 11/4 → 3/1 | note:e decay:0.5 ]",
"[ 3/1 → 13/4 | note:f decay:0.5 ]",
"[ 13/4 → 7/2 | note:a decay:0.5 ]",
"[ 7/2 → 29/8 | note:c decay:0.25 ]",
"[ 29/8 → 15/4 | note:d decay:0.25 ]",
"[ 15/4 → 4/1 | note:e decay:0.5 ]",
]
`;
exports[`runs examples > example "seed" example index 0 1`] = `
[
"[ 0/1 → 1/4 | s:bd ]",
@@ -16048,7 +16130,30 @@ exports[`runs examples > example "when" example index 0 1`] = `
]
`;
exports[`runs examples > example "whenKey" example index 0 1`] = `[]`;
exports[`runs examples > example "whenKey" example index 0 1`] = `
[
"[ 0/1 → 1/8 | s:bd ]",
"[ 1/4 → 3/8 | s:bd ]",
"[ 3/8 → 1/2 | s:bd ]",
"[ 5/8 → 3/4 | s:bd ]",
"[ 3/4 → 7/8 | s:bd ]",
"[ 1/1 → 9/8 | s:bd ]",
"[ 5/4 → 11/8 | s:bd ]",
"[ 11/8 → 3/2 | s:bd ]",
"[ 13/8 → 7/4 | s:bd ]",
"[ 7/4 → 15/8 | s:bd ]",
"[ 2/1 → 17/8 | s:bd ]",
"[ 9/4 → 19/8 | s:bd ]",
"[ 19/8 → 5/2 | s:bd ]",
"[ 21/8 → 11/4 | s:bd ]",
"[ 11/4 → 23/8 | s:bd ]",
"[ 3/1 → 25/8 | s:bd ]",
"[ 13/4 → 27/8 | s:bd ]",
"[ 27/8 → 7/2 | s:bd ]",
"[ 29/8 → 15/4 | s:bd ]",
"[ 15/4 → 31/8 | s:bd ]",
]
`;
exports[`runs examples > example "withBase" example index 0 1`] = `
[
+1 -1
View File
@@ -31,7 +31,7 @@ describe('runs examples', () => {
}
doc.examples?.forEach((example, i) => {
it(`example "${doc.name}" example index ${i}`, async ({ expect }) => {
const haps = await queryCode(example, 4);
const haps = await queryCode(example, 4, true);
expect(haps).toMatchSnapshot();
});
});
+2 -2
View File
@@ -182,9 +182,9 @@ evalScope(
);
// TBD: use transpiler to support labeled statements
export const queryCode = async (code, cycles = 1) => {
export const queryCode = async (code, cycles = 1, propagateExceptions = false) => {
const { pattern } = await evaluate(code);
const haps = pattern.sortHapsByPart().queryArc(0, cycles);
const haps = pattern.sortHapsByPart().queryArc(0, cycles, { propagateExceptions });
return haps.map((h) => h.show(true));
};
+561 -176
View File
File diff suppressed because it is too large Load Diff
@@ -134,7 +134,7 @@ This group of functions allows to modify the value of events.
## as
<JsDoc client:idle name="as" h={0} />
<JsDoc client:idle name="Pattern#as" h={0} />
# Custom Parameters
+1 -1
View File
@@ -26,7 +26,7 @@ import { JsDoc } from '../../docs/JsDoc';
## echoWith
<JsDoc client:idle name="echoWith" h={0} />
<JsDoc client:idle name="Pattern#echoWith" h={0} />
## stut
@@ -34,11 +34,11 @@ import { JsDoc } from '../../docs/JsDoc';
## arp
<JsDoc client:idle name="arp" h={0} />
<JsDoc client:idle name="Pattern#arp" h={0} />
## arpWith 🧪
<JsDoc client:idle name="arpWith" h={0} />
<JsDoc client:idle name="Pattern#arpWith" h={0} />
## struct
@@ -62,47 +62,47 @@ import { JsDoc } from '../../docs/JsDoc';
## invert
<JsDoc client:idle name="invert" h={0} />
<JsDoc client:idle name="Pattern#invert" h={0} />
## pick
<JsDoc client:idle name="pick" h={0} />
<JsDoc client:idle name="Pattern#pick" h={0} />
## pickmod
<JsDoc client:idle name="pickmod" h={0} />
<JsDoc client:idle name="Pattern#pickmod" h={0} />
## pickF
<JsDoc client:idle name="pickF" h={0} />
<JsDoc client:idle name="Pattern#pickF" h={0} />
## pickmodF
<JsDoc client:idle name="pickmodF" h={0} />
<JsDoc client:idle name="Pattern#pickmodF" h={0} />
## pickRestart
<JsDoc client:idle name="pickRestart" h={0} />
<JsDoc client:idle name="Pattern#pickRestart" h={0} />
## pickmodRestart
<JsDoc client:idle name="pickmodRestart" h={0} />
<JsDoc client:idle name="Pattern#pickmodRestart" h={0} />
## pickReset
<JsDoc client:idle name="pickReset" h={0} />
<JsDoc client:idle name="Pattern#pickReset" h={0} />
## pickmodReset
<JsDoc client:idle name="pickmodReset" h={0} />
<JsDoc client:idle name="Pattern#pickmodReset" h={0} />
## inhabit
<JsDoc client:idle name="inhabit" h={0} />
<JsDoc client:idle name="Pattern#inhabit" h={0} />
## inhabitmod
<JsDoc client:idle name="inhabitmod" h={0} />
<JsDoc client:idle name="Pattern#inhabitmod" h={0} />
## squeeze
+55 -55
View File
@@ -150,35 +150,35 @@ Each filter has 2 parameters:
## lpf
<JsDoc client:idle name="lpf" h={0} />
<JsDoc client:idle name="Pattern#lpf" h={0} />
## lpq
<JsDoc client:idle name="lpq" h={0} />
<JsDoc client:idle name="Pattern#lpq" h={0} />
## hpf
<JsDoc client:idle name="hpf" h={0} />
<JsDoc client:idle name="Pattern#hpf" h={0} />
## hpq
<JsDoc client:idle name="hpq" h={0} />
<JsDoc client:idle name="Pattern#hpq" h={0} />
## bpf
<JsDoc client:idle name="bpf" h={0} />
<JsDoc client:idle name="Pattern#bpf" h={0} />
## bpq
<JsDoc client:idle name="bpq" h={0} />
<JsDoc client:idle name="Pattern#bpq" h={0} />
## ftype
<JsDoc client:idle name="ftype" h={0} />
<JsDoc client:idle name="Pattern#ftype" h={0} />
## vowel
<JsDoc client:idle name="vowel" h={0} />
<JsDoc client:idle name="Pattern#vowel" h={0} />
# Amplitude Modulation
@@ -186,27 +186,27 @@ Amplitude modulation changes the amplitude (gain) periodically over time.
## tremolo
<JsDoc client:idle name="tremolo" h={0} />
<JsDoc client:idle name="Pattern#tremolo" h={0} />
## tremolosync
<JsDoc client:idle name="tremolosync" h={0} />
<JsDoc client:idle name="Pattern#tremolosync" h={0} />
## tremolodepth
<JsDoc client:idle name="tremolodepth" h={0} />
<JsDoc client:idle name="Pattern#tremolodepth" h={0} />
## tremoloskew
<JsDoc client:idle name="tremoloskew" h={0} />
<JsDoc client:idle name="Pattern#tremoloskew" h={0} />
## tremolophase
<JsDoc client:idle name="tremolophase" h={0} />
<JsDoc client:idle name="Pattern#tremolophase" h={0} />
## tremoloshape
<JsDoc client:idle name="tremoloshape" h={0} />
<JsDoc client:idle name="Pattern#tremoloshape" h={0} />
# Amplitude Envelope
@@ -219,23 +219,23 @@ Strudel uses ADSR envelopes, which are probably the most common way to describe
## attack
<JsDoc client:idle name="attack" h={0} />
<JsDoc client:idle name="Pattern#attack" h={0} />
## decay
<JsDoc client:idle name="decay" h={0} />
<JsDoc client:idle name="Pattern#decay" h={0} />
## sustain
<JsDoc client:idle name="sustain" h={0} />
<JsDoc client:idle name="Pattern#sustain" h={0} />
## release
<JsDoc client:idle name="release" h={0} />
<JsDoc client:idle name="Pattern#release" h={0} />
## adsr
<JsDoc client:idle name="adsr" h={0} />
<JsDoc client:idle name="Pattern#adsr" h={0} />
# Filter Envelope
@@ -271,23 +271,23 @@ There is one filter envelope for each filter type and thus one set of envelope f
## lpattack
<JsDoc client:idle name="lpattack" h={0} />
<JsDoc client:idle name="Pattern#lpattack" h={0} />
## lpdecay
<JsDoc client:idle name="lpdecay" h={0} />
<JsDoc client:idle name="Pattern#lpdecay" h={0} />
## lpsustain
<JsDoc client:idle name="lpsustain" h={0} />
<JsDoc client:idle name="Pattern#lpsustain" h={0} />
## lprelease
<JsDoc client:idle name="lprelease" h={0} />
<JsDoc client:idle name="Pattern#lprelease" h={0} />
## lpenv
<JsDoc client:idle name="lpenv" h={0} />
<JsDoc client:idle name="Pattern#lpenv" h={0} />
# Pitch Envelope
@@ -321,45 +321,45 @@ Let's break down all pitch envelope controls:
## pattack
<JsDoc client:idle name="pattack" h={0} />
<JsDoc client:idle name="Pattern#pattack" h={0} />
## pdecay
<JsDoc client:idle name="pdecay" h={0} />
<JsDoc client:idle name="Pattern#pdecay" h={0} />
## prelease
<JsDoc client:idle name="prelease" h={0} />
<JsDoc client:idle name="Pattern#prelease" h={0} />
## penv
<JsDoc client:idle name="penv" h={0} />
<JsDoc client:idle name="Pattern#penv" h={0} />
## pcurve
<JsDoc client:idle name="pcurve" h={0} />
<JsDoc client:idle name="Pattern#pcurve" h={0} />
## panchor
<JsDoc client:idle name="panchor" h={0} />
<JsDoc client:idle name="Pattern#panchor" h={0} />
# Dynamics
## gain
<JsDoc client:idle name="gain" h={0} />
<JsDoc client:idle name="Pattern#gain" h={0} />
## velocity
<JsDoc client:idle name="velocity" h={0} />
<JsDoc client:idle name="Pattern#velocity" h={0} />
## compressor
<JsDoc client:idle name="compressor" h={0} />
<JsDoc client:idle name="Pattern#compressor" h={0} />
## postgain
<JsDoc client:idle name="postgain" h={0} />
<JsDoc client:idle name="Pattern#postgain" h={0} />
## xfade
@@ -377,21 +377,21 @@ Let's break down all pitch envelope controls:
## pan
<JsDoc client:idle name="pan" h={0} />
<JsDoc client:idle name="Pattern#pan" h={0} />
# Waveshaping
## coarse
<JsDoc client:idle name="coarse" h={0} />
<JsDoc client:idle name="Pattern#coarse" h={0} />
## crush
<JsDoc client:idle name="crush" h={0} />
<JsDoc client:idle name="Pattern#crush" h={0} />
## distort
<JsDoc client:idle name="distort" h={0} />
<JsDoc client:idle name="Pattern#distort" h={0} />
# Global Effects
@@ -402,78 +402,78 @@ global effects use the same chain for all events of the same orbit:
## orbit
<JsDoc client:idle name="orbit" h={0} />
<JsDoc client:idle name="Pattern#orbit" h={0} />
## Delay
### delay
<JsDoc client:idle name="delay" h={0} />
<JsDoc client:idle name="Pattern#delay" h={0} />
### delaytime
<JsDoc client:idle name="delaytime" h={0} />
<JsDoc client:idle name="Pattern#delaytime" h={0} />
### delayfeedback
<JsDoc client:idle name="delayfeedback" h={0} />
<JsDoc client:idle name="Pattern#delayfeedback" h={0} />
## Reverb
### room
<JsDoc client:idle name="room" h={0} />
<JsDoc client:idle name="Pattern#room" h={0} />
### roomsize
<JsDoc client:idle name="roomsize" h={0} />
<JsDoc client:idle name="Pattern#roomsize" h={0} />
### roomfade
<JsDoc client:idle name="roomfade" h={0} />
<JsDoc client:idle name="Pattern#roomfade" h={0} />
### roomlp
<JsDoc client:idle name="roomlp" h={0} />
<JsDoc client:idle name="Pattern#roomlp" h={0} />
### roomdim
<JsDoc client:idle name="roomdim" h={0} />
<JsDoc client:idle name="Pattern#roomdim" h={0} />
### iresponse
<JsDoc client:idle name="iresponse" h={0} />
<JsDoc client:idle name="Pattern#iresponse" h={0} />
## Phaser
### phaser
<JsDoc client:idle name="phaser" h={0} />
<JsDoc client:idle name="Pattern#phaser" h={0} />
### phaserdepth
<JsDoc client:idle name="phaserdepth" h={0} />
<JsDoc client:idle name="Pattern#phaserdepth" h={0} />
### phasercenter
<JsDoc client:idle name="phasercenter" h={0} />
<JsDoc client:idle name="Pattern#phasercenter" h={0} />
### phasersweep
<JsDoc client:idle name="phasersweep" h={0} />
<JsDoc client:idle name="Pattern#phasersweep" h={0} />
## Duck
### duckorbit
<JsDoc client:idle name="duckorbit" h={0} />
<JsDoc client:idle name="Pattern#duckorbit" h={0} />
### duckattack
<JsDoc client:idle name="duckattack" h={0} />
<JsDoc client:idle name="Pattern#duckattack" h={0} />
### duckdepth
<JsDoc client:idle name="duckdepth" h={0} />
<JsDoc client:idle name="Pattern#duckdepth" h={0} />
Next, we'll look at input / output via [MIDI, OSC and other methods](/learn/input-output).
+1 -1
View File
@@ -30,7 +30,7 @@ These are the equivalents used by the Mini Notation:
## stack
<JsDoc client:idle name="stack" h={0} />
<JsDoc client:idle name="Pattern#stack" h={0} />
## stepcat
+1 -1
View File
@@ -76,7 +76,7 @@ $: midiport('IAC Driver');
$: note('c a f e').midiport('<0 1 2 3>').midi();
```
<JsDoc client:idle name="midiport" h={0} />
<JsDoc client:idle name="Pattern#midiport" h={0} />
## midichan(number)
+7 -7
View File
@@ -329,7 +329,7 @@ Sampler effects are functions that can be used to change the behaviour of sample
### begin
<JsDoc client:idle name="begin" h={0} />
<JsDoc client:idle name="Pattern#begin" h={0} />
### end
@@ -337,23 +337,23 @@ Sampler effects are functions that can be used to change the behaviour of sample
### loop
<JsDoc client:idle name="loop" h={0} />
<JsDoc client:idle name="Pattern#loop" h={0} />
### loopBegin
<JsDoc client:idle name="loopBegin" h={0} />
<JsDoc client:idle name="Pattern#loopBegin" h={0} />
### loopEnd
<JsDoc client:idle name="loopEnd" h={0} />
<JsDoc client:idle name="Pattern#loopEnd" h={0} />
### cut
<JsDoc client:idle name="cut" h={0} />
<JsDoc client:idle name="Pattern#cut" h={0} />
### clip
<JsDoc client:idle name="clip" h={0} />
<JsDoc client:idle name="Pattern#clip" h={0} />
### loopAt
@@ -385,6 +385,6 @@ Sampler effects are functions that can be used to change the behaviour of sample
### speed
<JsDoc client:idle name="speed" h={0} />
<JsDoc client:idle name="Pattern#speed" h={0} />
After samples, let's see what [Synths](/learn/synths) afford us.
+9 -9
View File
@@ -82,7 +82,7 @@ Earlier versions of many of these functions had `s_` prefixes, and the `pace` fu
### pace
<JsDoc client:idle name="pace" h={0} />
<JsDoc client:idle name="Pattern#pace" h={0} />
### stepcat
@@ -94,23 +94,23 @@ Earlier versions of many of these functions had `s_` prefixes, and the `pace` fu
### expand
<JsDoc client:idle name="expand" h={0} />
<JsDoc client:idle name="Pattern#expand" h={0} />
### contract
<JsDoc client:idle name="contract" h={0} />
<JsDoc client:idle name="Pattern#contract" h={0} />
### extend
<JsDoc client:idle name="extend" h={0} />
<JsDoc client:idle name="Pattern#extend" h={0} />
### take
<JsDoc client:idle name="take" h={0} />
<JsDoc client:idle name="Pattern#take" h={0} />
### drop
<JsDoc client:idle name="drop" h={0} />
<JsDoc client:idle name="Pattern#drop" h={0} />
### polymeter
@@ -118,15 +118,15 @@ Earlier versions of many of these functions had `s_` prefixes, and the `pace` fu
### shrink
<JsDoc client:idle name="shrink" h={0} />
<JsDoc client:idle name="Pattern#shrink" h={0} />
### grow
<JsDoc client:idle name="grow" h={0} />
<JsDoc client:idle name="Pattern#grow" h={0} />
### tour
<JsDoc client:idle name="tour" h={0} />
<JsDoc client:idle name="Pattern#tour" h={0} />
### zip
+8 -8
View File
@@ -141,11 +141,11 @@ These phases too can be declared in Strudel and can give your sounds interesting
### vib
<JsDoc client:idle name="vib" h={0} />
<JsDoc client:idle name="Pattern#vib" h={0} />
### vibmod
<JsDoc client:idle name="vibmod" h={0} />
<JsDoc client:idle name="Pattern#vibmod" h={0} />
## FM Synthesis
@@ -155,27 +155,27 @@ You can use fm with any of the above waveforms, although the below examples all
### fm
<JsDoc client:idle name="fm" h={0} />
<JsDoc client:idle name="Pattern#fm" h={0} />
### fmh
<JsDoc client:idle name="fmh" h={0} />
<JsDoc client:idle name="Pattern#fmh" h={0} />
### fmattack
<JsDoc client:idle name="fmattack" h={0} />
<JsDoc client:idle name="Pattern#fmattack" h={0} />
### fmdecay
<JsDoc client:idle name="fmdecay" h={0} />
<JsDoc client:idle name="Pattern#fmdecay" h={0} />
### fmsustain
<JsDoc client:idle name="fmsustain" h={0} />
<JsDoc client:idle name="Pattern#fmsustain" h={0} />
### fmenv
<JsDoc client:idle name="fmenv" h={0} />
<JsDoc client:idle name="Pattern#fmenv" h={0} />
## Wavetable Synthesis
+14 -14
View File
@@ -36,7 +36,7 @@ Some of these have equivalent operators in the Mini Notation:
## clip / legato
<JsDoc client:idle name="clip" h={0} />
<JsDoc client:idle name="Pattern#clip" h={0} />
## euclid
@@ -56,7 +56,7 @@ Some of these have equivalent operators in the Mini Notation:
## palindrome
<JsDoc client:idle name="palindrome" h={0} />
<JsDoc client:idle name="Pattern#palindrome" h={0} />
## iter
@@ -68,50 +68,50 @@ Some of these have equivalent operators in the Mini Notation:
## ply
<JsDoc client:idle name="ply" h={0} />
<JsDoc client:idle name="Pattern#ply" h={0} />
## segment
<JsDoc client:idle name="segment" h={0} />
<JsDoc client:idle name="Pattern#segment" h={0} />
## compress
<JsDoc client:idle name="compress" h={0} />
<JsDoc client:idle name="Pattern#compress" h={0} />
## zoom
<JsDoc client:idle name="zoom" h={0} />
<JsDoc client:idle name="Pattern#zoom" h={0} />
## linger
<JsDoc client:idle name="linger" h={0} />
<JsDoc client:idle name="Pattern#linger" h={0} />
## fastGap
<JsDoc client:idle name="fastGap" h={0} />
<JsDoc client:idle name="Pattern#fastGap" h={0} />
## inside
<JsDoc client:idle name="inside" h={0} />
<JsDoc client:idle name="Pattern#inside" h={0} />
## outside
<JsDoc client:idle name="outside" h={0} />
<JsDoc client:idle name="Pattern#outside" h={0} />
## cpm
<JsDoc client:idle name="cpm" h={0} />
<JsDoc client:idle name="Pattern#cpm" h={0} />
## ribbon
<JsDoc client:idle name="ribbon" h={0} />
<JsDoc client:idle name="Pattern#ribbon" h={0} />
## swingBy
<JsDoc client:idle name="swingBy" h={0} />
<JsDoc client:idle name="Pattern#swingBy" h={0} />
## swing
<JsDoc client:idle name="swing" h={0} />
<JsDoc client:idle name="Pattern#swing" h={0} />
Apart from modifying time, there are ways to [Control Parameters](/functions/value-modifiers/).
+2 -2
View File
@@ -12,7 +12,7 @@ These functions use [tonaljs](https://github.com/tonaljs/tonal) to provide helpe
### voicing()
<JsDoc client:idle name="voicing" h={0} />
<JsDoc client:idle name="Pattern#voicing" h={0} />
Here's an example of how you can play chords and a bassline:
@@ -29,7 +29,7 @@ Here's an example of how you can play chords and a bassline:
### scale(name)
<JsDoc client:idle name="scale" h={0} />
<JsDoc client:idle name="Pattern#scale" h={0} />
### transpose(semitones)
+3 -3
View File
@@ -93,7 +93,7 @@ What follows is the API doc of all the options you can pass:
## Scope
<JsDoc client:idle name="scope" h={0} />
<JsDoc client:idle name="Pattern#scope" h={0} />
## Pitchwheel
@@ -101,7 +101,7 @@ What follows is the API doc of all the options you can pass:
## Spectrum
<JsDoc client:idle name="spectrum" h={0} />
<JsDoc client:idle name="Pattern#spectrum" h={0} />
## Print
@@ -109,4 +109,4 @@ What follows is the API doc of all the options you can pass:
## markcss
<JsDoc client:idle name="markcss" h={0} />
<JsDoc client:idle name="Pattern#markcss" h={0} />