Compare commits
1 Commits
fixes
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
| dea8808721 |
12
ToposServer/package-lock.json
generated
@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "topos-server",
|
||||
"version": "1.0.0",
|
||||
"version": "0.0.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "topos-server",
|
||||
"version": "1.0.0",
|
||||
"version": "0.0.1",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"osc": "^2.4.4",
|
||||
"ws": "^8.14.2"
|
||||
"ws": "^8.17.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@serialport/binding-mock": {
|
||||
@ -309,9 +309,9 @@
|
||||
"integrity": "sha512-P+6vtWyuDw+MB01X7UeF8TaHBvbCovf4HPEMF/SV7BdDc1SMTiBy13SRD71lQh4ExFTG1d/WNzDGDCyOKSMblw=="
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "8.14.2",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz",
|
||||
"integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==",
|
||||
"version": "8.17.1",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz",
|
||||
"integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
|
||||
@ -10,6 +10,6 @@
|
||||
"license": "GPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"osc": "^2.4.4",
|
||||
"ws": "^8.14.2"
|
||||
"ws": "^8.17.1"
|
||||
}
|
||||
}
|
||||
|
||||
2
global.d.ts
vendored
@ -1,3 +1 @@
|
||||
/// <reference types="vite-plugin-pwa/client" />
|
||||
|
||||
|
||||
|
||||
37
index.html
@ -32,22 +32,26 @@
|
||||
}
|
||||
|
||||
.hydracanvas {
|
||||
position: fixed;
|
||||
top: 0px; left: 0px;
|
||||
width: 100%; height: 100%;
|
||||
position: fixed; /* ignore margins */
|
||||
top: 0px;
|
||||
left: 0px;
|
||||
width: 100%; /* fill screen */
|
||||
height: 100%;
|
||||
background-size: cover;
|
||||
overflow-y: hidden;
|
||||
z-index: -5;
|
||||
z-index: -5; /* place behind everything else */
|
||||
display: block;
|
||||
}
|
||||
|
||||
.fullscreencanvas {
|
||||
position: fixed;
|
||||
top: 0px; left: 0px;
|
||||
width: 100%; height: 100%;
|
||||
position: fixed; /* ignore margins */
|
||||
top: 0px;
|
||||
left: 0px;
|
||||
width: 100%; /* fill screen */
|
||||
height: 100%;
|
||||
background-size: cover;
|
||||
overflow-y: hidden;
|
||||
z-index: -1;
|
||||
z-index: -1; /* place behind everything else */
|
||||
display: block;
|
||||
}
|
||||
|
||||
@ -104,12 +108,12 @@
|
||||
<header class="py-0 block">
|
||||
<div id="topbar" class="mx-auto flex flex-wrap pl-2 py-1 flex-row items-center bg-background">
|
||||
<a class="flex title-font font-medium items-center mb-0">
|
||||
<img id="topos_logo" src="topos_frog.svg" class="w-12 h-12 text-selection_foreground p-2 rounded-full bg-foreground" alt="Topos Frog Logo"/>
|
||||
<img id="topos-logo" src="topos_frog.svg" class="w-12 h-12 text-selection_foreground p-2 rounded-full bg-foreground" alt="Topos Frog Logo"/>
|
||||
<input id="universe-viewer" class="hidden transparent xl:block ml-4 text-2xl bg-background text-brightwhite placeholder-brightwhite" id="renamer" type="text" placeholder="Topos">
|
||||
</a>
|
||||
<nav class="py-2 flex flex-wrap items-center text-base absolute right-0">
|
||||
<!-- Play Button -->
|
||||
<a title="Play button (Ctrl+P)" id="play-button" class="bar_button">
|
||||
<a title="Play button (Ctrl+P)" id="play-button-1" class="bar_button">
|
||||
<svg id="play-icon" class="w-7 h-7" fill="currentColor" viewBox="0 0 14 16">
|
||||
<path d="M0 .984v14.032a1 1 0 0 0 1.506.845l12.006-7.016a.974.974 0 0 0 0-1.69L1.506.139A1 1 0 0 0 0 .984Z"/>
|
||||
</svg>
|
||||
@ -120,7 +124,7 @@
|
||||
</a>
|
||||
|
||||
<!-- Stop button -->
|
||||
<a title="Stop button (Ctrl+R)" id="stop-button" class="bar_button">
|
||||
<a title="Stop button (Ctrl+R)" id="stop-button-1" class="bar_button">
|
||||
<svg class="w-7 h-7 " aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5Z"/>
|
||||
<rect x="6.5" y="6.5" width="7" height="7" fill="selection_background" rx="1" ry="1"/>
|
||||
@ -136,6 +140,13 @@
|
||||
<p class="hidden lg:block text-xl pl-2 inline-block">Eval</p>
|
||||
</a>
|
||||
|
||||
<a title="Clear button" id="clear-button-1" class="bar_button">
|
||||
<svg class="w-7 h-7 " aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 18 20">
|
||||
<path d="M17 4h-4V2a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v2H1a1 1 0 0 0 0 2h1v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V6h1a1 1 0 1 0 0-2ZM7 2h4v2H7V2Zm1 14a1 1 0 1 1-2 0V8a1 1 0 0 1 2 0v8Zm4 0a1 1 0 0 1-2 0V8a1 1 0 0 1 2 0v8Z"/>
|
||||
</svg>
|
||||
<p class="hidden lg:block text-xl pl-2 inline-block">Clear</p>
|
||||
</a>
|
||||
|
||||
<a title="Share button" id="share-button" class="bar_button">
|
||||
<svg class="w-7 h-7 " aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 19 19">
|
||||
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.013 7.962a3.519 3.519 0 0 0-4.975 0l-3.554 3.554a3.518 3.518 0 0 0 4.975 4.975l.461-.46m-.461-4.515a3.518 3.518 0 0 0 4.975 0l3.553-3.554a3.518 3.518 0 0 0-4.974-4.975L10.3 3.7"/>
|
||||
@ -150,7 +161,6 @@
|
||||
<p class="hidden lg:block text-xl pl-2 inline-block">Docs</p>
|
||||
</a>
|
||||
|
||||
<div id="transport_viewer" class="pr-2 text-selection_background"></div>
|
||||
</nav>
|
||||
</nav>
|
||||
</div>
|
||||
@ -330,6 +340,7 @@
|
||||
<select id="theme-selector" class="ml-4 border mb-2
|
||||
text-sm rounded-lg block p-2.5">
|
||||
</select>
|
||||
<div id="theme-previewer"></div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Editor mode selection -->
|
||||
@ -565,6 +576,7 @@
|
||||
<div id="editor" class="relative flex flex-row h-screen overflow-y-hidden">
|
||||
<canvas id="scope" class="fullscreencanvas"></canvas>
|
||||
<canvas id="feedback" class="fullscreencanvas"></canvas>
|
||||
<canvas id="drawings" class="fullscreencanvas"></canvas>
|
||||
<canvas id="hydra-bg" class="hydracanvas"></canvas>
|
||||
</div>
|
||||
<p id="error_line" class="hidden w-screen bg-background font-mono absolute bottom-0 pl-2 py-2">Hello kids</p>
|
||||
@ -580,5 +592,6 @@
|
||||
</li>
|
||||
</template>
|
||||
</body>
|
||||
<p id="timeviewer" class="rounded-lg px-2 py-2 font-bold cursor-textpointer-events-none select-none text-sm absolute bottom-2 right-2 bg-foreground text-background"></p>
|
||||
<p id="fillviewer" class="invisible rounded-lg px-2 py-2 font-bold cursor-textpointer-events-none select-none text-sm absolute right-2 bottom-12 bg-foreground text-background">/////// Fill ///////</p>
|
||||
</html>
|
||||
|
||||
@ -32,7 +32,7 @@
|
||||
"fflate": "^0.8.0",
|
||||
"highlight.js": "^11.9.0",
|
||||
"jisg": "^0.9.7",
|
||||
"lru-cache": "^10.2.0",
|
||||
"lru-cache": "^10.0.1",
|
||||
"marked": "^7.0.3",
|
||||
"osc": "^2.4.4",
|
||||
"postcss": "^8.4.27",
|
||||
|
||||
2678
src/API.ts
Normal file
630
src/API/API.ts
@ -1,630 +0,0 @@
|
||||
import * as Transport from './Time/Transport';
|
||||
import * as Mouse from './DOM/Mouse';
|
||||
import * as Theme from './DOM/Theme';
|
||||
import * as Canvas from './DOM/Canvas';
|
||||
import * as Cache from './Cache';
|
||||
import * as Script from './Script';
|
||||
import * as Drunk from './Drunk';
|
||||
import * as Warp from './Time/Warp';
|
||||
import * as Mathematics from './Math';
|
||||
import * as Ziffers from './Ziffers';
|
||||
import * as Filters from './Time/Filters';
|
||||
import * as LFO from './LFO';
|
||||
import * as Probability from './Probabilities';
|
||||
import * as OSC from './IO/OSC';
|
||||
import * as Randomness from './Randomness';
|
||||
import * as Counter from './Counter';
|
||||
import * as Sound from './Sound';
|
||||
import * as Console from './DOM/Console';
|
||||
import { type SoundEvent } from '../Classes/SoundEvent';
|
||||
import { type SkipEvent } from '../Classes/SkipEvent';
|
||||
import { OscilloscopeConfig } from "../DOM/Visuals/Oscilloscope";
|
||||
import { Player } from "../Classes/ZPlayer";
|
||||
import { InputOptions } from "../Classes/ZPlayer";
|
||||
import { type ShapeObject } from "../API/DOM/Canvas";
|
||||
import { nearScales } from "zifferjs";
|
||||
import { MidiConnection } from "../IO/MidiConnection";
|
||||
import { DrunkWalk } from "../Utils/Drunk";
|
||||
import { Editor } from "../main";
|
||||
import { LRUCache } from "lru-cache";
|
||||
import {
|
||||
loadUniverse,
|
||||
openUniverseModal,
|
||||
} from "../Editor/FileManagement";
|
||||
import {
|
||||
samples,
|
||||
initAudioOnFirstClick,
|
||||
registerSynthSounds,
|
||||
registerZZFXSounds,
|
||||
soundMap,
|
||||
// @ts-ignore
|
||||
} from "superdough";
|
||||
import { getScaleNotes } from "zifferjs";
|
||||
import drums from "../tidal-drum-machines.json";
|
||||
import { updatePlayPauseIcon } from '../DOM/UILogic';
|
||||
|
||||
export async function loadSamples() {
|
||||
return Promise.all([
|
||||
initAudioOnFirstClick(),
|
||||
samples("github:tidalcycles/Dirt-Samples/master", undefined, {
|
||||
tag: "Tidal",
|
||||
}).then(() => registerSynthSounds()),
|
||||
registerZZFXSounds(),
|
||||
samples(drums, "github:ritchse/tidal-drum-machines/main/machines/", {
|
||||
tag: "Machines",
|
||||
}),
|
||||
samples("github:Bubobubobubobubo/Dough-Fox/main", undefined, {
|
||||
tag: "FoxDot",
|
||||
}),
|
||||
samples("github:Bubobubobubobubo/Dough-Samples/main", undefined, {
|
||||
tag: "Pack",
|
||||
}),
|
||||
samples("github:Bubobubobubobubo/Dough-Amiga/main", undefined, {
|
||||
tag: "Amiga",
|
||||
}),
|
||||
samples("github:Bubobubobubobubo/Dough-Juj/main", undefined, {
|
||||
tag: "Juliette",
|
||||
}),
|
||||
samples("github:Bubobubobubobubo/Dough-Amen/main", undefined, {
|
||||
tag: "Amen",
|
||||
}),
|
||||
samples("github:Bubobubobubobubo/Dough-Waveforms/main", undefined, {
|
||||
tag: "Waveforms",
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
export class UserAPI {
|
||||
/**
|
||||
* The UserAPI class is the interface between the user's code and the backend. It provides
|
||||
* access to the AudioContext, to the MIDI Interface, to internal variables, mouse position,
|
||||
* useful functions, etc... This class is exposed to the user's action and any function
|
||||
* destined to the user should be placed here.
|
||||
*/
|
||||
|
||||
public codeExamples: { [key: string]: string } = {};
|
||||
public counters: { [key: string]: any } = {};
|
||||
//@ts-ignore
|
||||
public _drunk: DrunkWalk = new DrunkWalk(-100, 100, false);
|
||||
public randomGen = Math.random;
|
||||
public currentSeed: string | undefined = undefined;
|
||||
public localSeeds = new Map<string, Function>();
|
||||
public patternCache = new LRUCache({ max: 10000, ttl: 10000 * 60 * 5 });
|
||||
public invalidPatterns: { [key: string]: boolean } = {};
|
||||
public cueTimes: { [key: string]: number } = {};
|
||||
private errorTimeoutID: number = 0;
|
||||
private printTimeoutID: number = 0;
|
||||
public MidiConnection: MidiConnection;
|
||||
public scale_aid: string | number | undefined = undefined;
|
||||
public hydra: any;
|
||||
public onceEvaluator: boolean = true;
|
||||
public forceEvaluator: boolean = false;
|
||||
|
||||
load: samples;
|
||||
public global: { [key: string]: any };
|
||||
time: () => number;
|
||||
play: () => void;
|
||||
pause: () => void;
|
||||
stop: () => void;
|
||||
silence: () => void;
|
||||
mouseX: () => number;
|
||||
mouseY: () => number;
|
||||
noteX: () => number;
|
||||
noteY: () => number;
|
||||
tempo: (n?: number | undefined) => number;
|
||||
ppqn: (n?: number | undefined) => number;
|
||||
time_signature: (numerator: number, denominator: number) => void;
|
||||
theme: (color_scheme: string) => void;
|
||||
themeName: () => string;
|
||||
randomTheme: () => void;
|
||||
nextTheme: () => void;
|
||||
getThemes: () => string[];
|
||||
pulseLocation: () => number;
|
||||
clear: () => boolean;
|
||||
loadHydra: () => void;
|
||||
w: () => number;
|
||||
h: () => number;
|
||||
hc: () => number;
|
||||
wc: () => number;
|
||||
background: (color: string | number, ...gb: number[]) => boolean;
|
||||
linearGradient: (x1: number, y1: number, x2: number, y2: number, ...stops: (number | string)[]) => CanvasGradient;
|
||||
radialGradient: (x1: number, y1: number, r1: number, x2: number, y2: number, r2: number, ...stops: (number | string)[]) => CanvasGradient;
|
||||
conicGradient: (x: number, y: number, angle: number, ...stops: (number | string)[]) => CanvasGradient;
|
||||
draw: (func: Function) => boolean;
|
||||
balloid: (curves: number | ShapeObject, radius: number, curve: number, fillStyle: string, secondary: string, x: number, y: number) => boolean;
|
||||
equilateral: (radius: number | ShapeObject, fillStyle: string, rotation: number, x: number, y: number) => boolean;
|
||||
triangular: (width: number | ShapeObject, height: number, fillStyle: string, rotation: number, x: number, y: number) => boolean;
|
||||
ball: (radius: number | ShapeObject, fillStyle: string, x: number, y: number) => boolean;
|
||||
circle: (radius: number | ShapeObject, fillStyle: string, x: number, y: number) => boolean;
|
||||
donut: (slices: number | ShapeObject, eaten: number, radius: number, hole: number, fillStyle: string, secondary: string, stroke: string, rotation: number, x: number, y: number) => boolean;
|
||||
pie: (slices: number | ShapeObject, eaten: number, radius: number, fillStyle: string, secondary: string, stroke: string, rotation: number, x: number, y: number) => boolean;
|
||||
star: (points: number | ShapeObject, radius: number, fillStyle: string, rotation: number, outerRadius: number, x: number, y: number) => boolean;
|
||||
stroke: (width: number | ShapeObject, strokeStyle: string, rotation: number, x1: number, y1: number, x2: number, y2: number) => boolean;
|
||||
box: (width: number | ShapeObject, height: number, fillStyle: string, rotation: number, x: number, y: number) => boolean;
|
||||
smiley: (happiness: number | ShapeObject, radius: number, eyeSize: number, fillStyle: string, rotation: number, x: number, y: number) => boolean;
|
||||
text: (text: string | ShapeObject, fontSize: number, rotation: number, font: string, x: number, y: number, fillStyle: string, filter: string) => boolean;
|
||||
image: (url: string | ShapeObject, width: number, height: number, rotation: number, x: number, y: number, filter: string) => boolean;
|
||||
randomChar: (length: number, min: number, max: number) => string;
|
||||
randomFromRange: (min: number, max: number) => string;
|
||||
emoji: (n: number) => string;
|
||||
food: (n: number) => string;
|
||||
animals: (n: number) => string;
|
||||
expressions: (n: number) => string;
|
||||
generateCacheKey: (...args: any[]) => string;
|
||||
resetAllFromCache: () => void;
|
||||
clearPatternCache: () => void;
|
||||
removePatternFromCache: (id: string) => void;
|
||||
script: (...args: number[]) => void;
|
||||
s: (...args: number[]) => void;
|
||||
delete_script: (script: number) => void;
|
||||
cs: (script: number) => void;
|
||||
copy_script: (from: number, to: number) => void;
|
||||
cps: (from: number, to: number) => void;
|
||||
copy_universe: (from: string, to: string) => void;
|
||||
delete_universe: (universe: string) => void;
|
||||
big_bang: () => void;
|
||||
drunk: (n?: number | undefined) => number;
|
||||
drunk_max: (max: number) => void;
|
||||
drunk_min: (min: number) => void;
|
||||
drunk_wrap: (wrap: boolean) => void;
|
||||
warp: (n: number) => void;
|
||||
beat_warp: (beat: number) => void;
|
||||
min: (...values: number[]) => number;
|
||||
max: (...values: number[]) => number;
|
||||
mean: (...values: number[]) => number;
|
||||
limit: (value: number, min: number, max: number) => number;
|
||||
abs: (value: number) => number;
|
||||
z: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
fullseq: (sequence: string, duration: number) => boolean | boolean[];
|
||||
seq: (expr: string, duration?: number) => boolean;
|
||||
beat: (n?: number | number[], nudge?: number) => boolean;
|
||||
bar: (n?: number | number[], nudge?: number) => boolean;
|
||||
pulse: (n?: number | number[], nudge?: number) => boolean;
|
||||
tick: (tick: number | number[], offset?: number) => boolean;
|
||||
dur: (n: number | number[]) => boolean;
|
||||
flip: (chunk: number, ratio?: number) => boolean;
|
||||
flipbar: (chunk?: number) => boolean;
|
||||
onbar: (bars: number | number[], n?: number) => boolean;
|
||||
onbeat: (...beat: number[]) => boolean;
|
||||
oncount: (beats: number | number[], count: number) => boolean;
|
||||
oneuclid: (pulses: number, length: number, rotate?: number) => boolean;
|
||||
euclid: (iterator: number, pulses: number, length: number, rotate?: number) => boolean;
|
||||
ec: any;
|
||||
rhythm: (div: number, pulses: number, length: number, rotate?: number) => boolean;
|
||||
ry: any;
|
||||
nrhythm: (div: number, pulses: number, length: number, rotate?: number) => boolean;
|
||||
nry: any;
|
||||
bin: (iterator: number, n: number) => boolean;
|
||||
binrhythm: (div: number, n: number) => boolean;
|
||||
bry: any;
|
||||
line: any;
|
||||
sine: any;
|
||||
usine: any;
|
||||
saw: any;
|
||||
usaw: any;
|
||||
triangle: any;
|
||||
utriangle: any;
|
||||
square: any;
|
||||
usquare: any;
|
||||
noise: any;
|
||||
unoise: any;
|
||||
prob: (p: number) => boolean;
|
||||
toss: () => boolean;
|
||||
odds: (n: number, beats?: number) => boolean;
|
||||
never: (beats?: number) => boolean;
|
||||
almostNever: (beats?: number) => boolean;
|
||||
rarely: (beats?: number) => boolean;
|
||||
scarcely: (beats?: number) => boolean;
|
||||
sometimes: (beats?: number) => boolean;
|
||||
often: (beats?: number) => boolean;
|
||||
frequently: (beats?: number) => boolean;
|
||||
almostAlways: (beats?: number) => boolean;
|
||||
always: (beats?: number) => boolean;
|
||||
dice: (sides: number) => number;
|
||||
osc: (address: string, port: number, ...args: any[]) => void;
|
||||
getOSC: (address?: string | undefined) => any[];
|
||||
gif: (options: any) => void;
|
||||
scope: (config: OscilloscopeConfig) => void;
|
||||
randI: any;
|
||||
rand: any;
|
||||
ir: any;
|
||||
irand: any;
|
||||
r: any;
|
||||
seed: any;
|
||||
localSeededRandom: any;
|
||||
clearLocalSeed: any;
|
||||
once: () => boolean;
|
||||
counter: (name: string | number, limit?: number | undefined, step?: number | undefined) => number;
|
||||
$: any;
|
||||
count: any;
|
||||
i: (n?: number | undefined) => any;
|
||||
sound: (sound: string | string[] | null | undefined) => SoundEvent | SkipEvent;
|
||||
snd: any;
|
||||
log: (message: any) => void;
|
||||
logOnce: (message: any) => void;
|
||||
speak: (text: string, lang?: string, voiceIndex?: number, rate?: number, pitch?: number) => void;
|
||||
cbar: () => number;
|
||||
ctick: () => number;
|
||||
cpulse: () => number;
|
||||
cbeat: () => number;
|
||||
ebeat: () => number;
|
||||
epulse: () => number;
|
||||
nominator: () => number;
|
||||
meter: () => number;
|
||||
denominator: () => number;
|
||||
pulsesForBar: () => number;
|
||||
z0!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z1!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z2!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z3!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z4!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z5!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z6!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z7!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z8!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z9!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z10!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z11!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z12!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z13!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z14!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z15!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
z16!: (input: string | Generator<number>, options: InputOptions, id: number | string) => Player;
|
||||
|
||||
constructor(public app: Editor) {
|
||||
this.MidiConnection = new MidiConnection(this, app.settings);
|
||||
this.global = {};
|
||||
this.g = this.global;
|
||||
this.time = Transport.time(this);
|
||||
this.play = Transport.play(this);
|
||||
this.pause = Transport.pause(this);
|
||||
this.stop = Transport.stop(this);
|
||||
this.silence = Transport.silence(this);
|
||||
this.tempo = Transport.tempo(this.app);
|
||||
this.ppqn = Transport.ppqn(this.app);
|
||||
this.time_signature = Transport.time_signature(this.app);
|
||||
this.mouseX = Mouse.mouseX(this.app);
|
||||
this.mouseY = Mouse.mouseY(this.app);
|
||||
this.noteX = Mouse.noteX(this.app);
|
||||
this.noteY = Mouse.noteY(this.app);
|
||||
this.theme = Theme.theme(this.app);
|
||||
this.themeName = Theme.themeName(this.app);
|
||||
this.randomTheme = Theme.randomTheme(this.app);
|
||||
this.nextTheme = Theme.nextTheme(this.app);
|
||||
this.getThemes = Theme.getThemes();
|
||||
this.pulseLocation = Canvas.pulseLocation(this.app);
|
||||
this.loadHydra = Canvas.loadHydra(this.app);
|
||||
this.clear = Canvas.clear(this.app);
|
||||
this.w = Canvas.w(this.app);
|
||||
this.h = Canvas.h(this.app);
|
||||
this.hc = Canvas.hc(this.app);
|
||||
this.wc = Canvas.wc(this.app);
|
||||
this.background = Canvas.background(this.app);
|
||||
this.linearGradient = Canvas.linearGradient(this.app);
|
||||
this.radialGradient = Canvas.radialGradient(this.app);
|
||||
this.conicGradient = Canvas.conicGradient(this.app);
|
||||
this.draw = Canvas.draw(this.app);
|
||||
this.balloid = Canvas.balloid(this.app);
|
||||
this.equilateral = Canvas.equilateral(this.app);
|
||||
this.triangular = Canvas.triangular(this.app);
|
||||
this.ball = Canvas.ball(this.app);
|
||||
this.circle = Canvas.circle(this.app);
|
||||
this.donut = Canvas.donut(this.app);
|
||||
this.pie = Canvas.pie(this.app);
|
||||
this.star = Canvas.star(this.app);
|
||||
this.stroke = Canvas.stroke(this.app);
|
||||
this.box = Canvas.box(this.app);
|
||||
this.smiley = Canvas.smiley(this.app);
|
||||
this.text = Canvas.text(this.app);
|
||||
this.image = Canvas.image(this.app);
|
||||
this.randomChar = Canvas.randomChar();
|
||||
this.randomFromRange = Canvas.randomFromRange();
|
||||
this.emoji = Canvas.emoji();
|
||||
this.food = Canvas.food();
|
||||
this.animals = Canvas.animals();
|
||||
this.expressions = Canvas.expressions();
|
||||
this.generateCacheKey = Cache.generateCacheKey();
|
||||
this.resetAllFromCache = Cache.resetAllFromCache(this);
|
||||
this.clearPatternCache = Cache.clearPatternCache(this);
|
||||
this.removePatternFromCache = Cache.removePatternFromCache(this);
|
||||
this.script = Script.script(this.app);
|
||||
this.s = this.script;
|
||||
this.delete_script = Script.delete_script(this.app);
|
||||
this.cs = this.delete_script;
|
||||
this.copy_script = Script.copy_script(this.app);
|
||||
this.cps = this.copy_script;
|
||||
this.copy_universe = Script.copy_universe(this.app);
|
||||
this.delete_universe = Script.delete_universe(this.app);
|
||||
this.big_bang = Script.big_bang(this.app);
|
||||
this.drunk = Drunk.drunk(this);
|
||||
this.drunk_max = Drunk.drunk_max(this);
|
||||
this.drunk_min = Drunk.drunk_min(this);
|
||||
this.drunk_wrap = Drunk.drunk_wrap(this);
|
||||
this.warp = Warp.warp(this.app);
|
||||
this.beat_warp = Warp.beat_warp(this.app);
|
||||
this.min = Mathematics.min();
|
||||
this.max = Mathematics.max();
|
||||
this.mean = Mathematics.mean();
|
||||
this.limit = Mathematics.limit();
|
||||
this.abs = Mathematics.abs();
|
||||
this.z = Ziffers.z(this);
|
||||
Object.assign(this, Ziffers.generateZFunctions(this));
|
||||
this.fullseq = Filters.fullseq();
|
||||
this.seq = Filters.seq(this.app);
|
||||
this.beat = Filters.beat(this.app);
|
||||
this.bar = Filters.bar(this.app);
|
||||
this.pulse = Filters.pulse(this.app);
|
||||
this.tick = Filters.tick(this.app);
|
||||
this.dur = Filters.dur(this.app);
|
||||
this.flip = Filters.flip(this.app);
|
||||
this.flipbar = Filters.flipbar(this.app);
|
||||
this.onbar = Filters.onbar(this.app);
|
||||
this.onbeat = Filters.onbeat(this);
|
||||
this.oncount = Filters.oncount(this.app);
|
||||
this.oneuclid = Filters.oneuclid(this.app);
|
||||
this.euclid = Filters.euclid();
|
||||
this.ec = this.euclid;
|
||||
this.rhythm = Filters.rhythm(this.app);
|
||||
this.ry = this.rhythm;
|
||||
this.nrhythm = Filters.nrhythm(this.app);
|
||||
this.nry = this.nrhythm;
|
||||
this.bin = Filters.bin();
|
||||
this.binrhythm = Filters.binrhythm(this.app);
|
||||
this.bry = this.binrhythm;
|
||||
this.line = LFO.line();
|
||||
this.sine = LFO.sine(this.app);
|
||||
this.usine = LFO.usine(this.app);
|
||||
this.saw = LFO.saw(this.app);
|
||||
this.usaw = LFO.usaw(this.app);
|
||||
this.triangle = LFO.triangle(this.app);
|
||||
this.utriangle = LFO.utriangle(this.app);
|
||||
this.square = LFO.square(this.app);
|
||||
this.usquare = LFO.usquare(this.app);
|
||||
this.noise = LFO.noise(this);
|
||||
this.unoise = LFO.unoise(this);
|
||||
this.prob = Probability.prob(this);
|
||||
this.toss = Probability.toss(this);
|
||||
this.odds = Probability.odds(this);
|
||||
this.never = Probability.never();
|
||||
this.almostNever = Probability.almostNever(this);
|
||||
this.rarely = Probability.rarely(this);
|
||||
this.scarcely = Probability.scarcely(this);
|
||||
this.sometimes = Probability.sometimes(this);
|
||||
this.often = Probability.often(this);
|
||||
this.frequently = Probability.frequently(this);
|
||||
this.almostAlways = Probability.almostAlways(this);
|
||||
this.always = Probability.always();
|
||||
this.dice = Probability.dice(this);
|
||||
this.osc = OSC.osc(this.app);
|
||||
this.getOSC = OSC.getOSC();
|
||||
this.gif = Canvas.gif(this.app);
|
||||
this.scope = Canvas.scope(this.app);
|
||||
this.randI = Randomness.randI(this);
|
||||
this.ir = this.randI;
|
||||
this.irand = this.randI;
|
||||
this.rand = Randomness.rand(this);
|
||||
this.r = this.rand;
|
||||
this.seed = Randomness.seed(this);
|
||||
this.localSeededRandom = Randomness.localSeededRandom(this);
|
||||
this.clearLocalSeed = Randomness.clearLocalSeed(this);
|
||||
this.once = Counter.once(this);
|
||||
this.counter = Counter.counter(this);
|
||||
this.$ = this.counter;
|
||||
this.count = this.counter;
|
||||
this.i = Counter.i(this.app);
|
||||
this.sound = Sound.sound(this.app);
|
||||
this.snd = this.sound;
|
||||
this.speak = Sound.speak();
|
||||
this.log = Console.log(this);
|
||||
this.logOnce = Console.logOnce(this);
|
||||
this.cbar = Transport.cbar(this.app);
|
||||
this.ctick = Transport.ctick(this.app);
|
||||
this.cpulse = Transport.cpulse(this.app);
|
||||
this.cbeat = Transport.cbeat(this.app);
|
||||
this.ebeat = Transport.ebeat(this.app);
|
||||
this.epulse = Transport.epulse(this.app);
|
||||
this.nominator = Transport.nominator(this.app);
|
||||
this.meter = Transport.meter(this.app);
|
||||
this.denominator = Transport.denominator(this.app);
|
||||
this.pulsesForBar = Transport.pulsesForBar(this.app);
|
||||
}
|
||||
|
||||
public g: any;
|
||||
|
||||
_loadUniverseFromInterface = (universe: string) => {
|
||||
this.app.selected_universe = universe.trim();
|
||||
this.app.settings.selected_universe = universe.trim();
|
||||
loadUniverse(this.app, universe as string);
|
||||
openUniverseModal();
|
||||
};
|
||||
|
||||
_deleteUniverseFromInterface = (universe: string) => {
|
||||
delete this.app.universes[universe];
|
||||
if (this.app.settings.selected_universe === universe) {
|
||||
this.app.settings.selected_universe = "Welcome";
|
||||
this.app.selected_universe = "Welcome";
|
||||
}
|
||||
this.app.settings.saveApplicationToLocalStorage(
|
||||
this.app.universes,
|
||||
this.app.settings,
|
||||
);
|
||||
this.app.updateKnownUniversesView();
|
||||
};
|
||||
|
||||
_playDocExample = (code?: string) => {
|
||||
/**
|
||||
* Play an example from the documentation. The example is going
|
||||
* to be stored in the example buffer belonging to the universe.
|
||||
* This buffer is going to be cleaned everytime the user press
|
||||
* pause or leaves the documentation window.
|
||||
*
|
||||
* @param code - The code example to play (identifier)
|
||||
*/
|
||||
let current_universe = this.app.universes[this.app.selected_universe]!;
|
||||
this.app.exampleIsPlaying = true;
|
||||
if (!current_universe.example) {
|
||||
current_universe.example = {
|
||||
candidate: "",
|
||||
committed: "",
|
||||
evaluations: 0,
|
||||
};
|
||||
current_universe.example.candidate! = code
|
||||
? code
|
||||
: (this.app.selectedExample as string);
|
||||
} else {
|
||||
current_universe.example.candidate! = code
|
||||
? code
|
||||
: (this.app.selectedExample as string);
|
||||
}
|
||||
this.patternCache.clear();
|
||||
if (this.app.isPlaying) {
|
||||
} else {
|
||||
this.app.clock.resume();
|
||||
updatePlayPauseIcon(this.app, "play");
|
||||
this.app.api.MidiConnection.sendStartMessage();
|
||||
}
|
||||
|
||||
// this.app.clock.start();
|
||||
};
|
||||
|
||||
_stopDocExample = () => {
|
||||
let current_universe = this.app.universes[this.app.selected_universe];
|
||||
if (current_universe?.example !== undefined) {
|
||||
this.app.exampleIsPlaying = false;
|
||||
current_universe.example.candidate! = "";
|
||||
current_universe.example.committed! = "";
|
||||
}
|
||||
this.clearPatternCache();
|
||||
this.stop();
|
||||
};
|
||||
|
||||
_playDocExampleOnce = (code?: string) => {
|
||||
let current_universe = this.app.universes[this.app.selected_universe];
|
||||
if (current_universe?.example !== undefined) {
|
||||
current_universe.example.candidate! = "";
|
||||
current_universe.example.committed! = "";
|
||||
}
|
||||
this.clearPatternCache();
|
||||
this.stop();
|
||||
this.play();
|
||||
this.app.exampleIsPlaying = true;
|
||||
evaluateOnce(this.app, code as string);
|
||||
};
|
||||
|
||||
_all_samples = (): object => {
|
||||
return soundMap.get();
|
||||
};
|
||||
|
||||
_reportError = (error: any): void => {
|
||||
const extractLineAndColumn = (error: Error) => {
|
||||
const stackLines = error.stack?.split("\n");
|
||||
if (stackLines) {
|
||||
for (const line of stackLines) {
|
||||
if (line.includes("<anonymous>")) {
|
||||
const match = line.match(/<anonymous>:(\d+):(\d+)/);
|
||||
if (match as RegExpMatchArray)
|
||||
return {
|
||||
// @ts-ignore
|
||||
line: parseInt(match[1], 10),
|
||||
// @ts-ignore
|
||||
column: parseInt(match[2]!, 10),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return { line: null, column: null };
|
||||
};
|
||||
|
||||
const { line, column } = extractLineAndColumn(error);
|
||||
const errorMessage =
|
||||
line && column
|
||||
? `${error.message} (Line: ${line - 2}, Column: ${column})`
|
||||
: error.message;
|
||||
|
||||
clearTimeout(this.errorTimeoutID);
|
||||
clearTimeout(this.printTimeoutID);
|
||||
this.app.interface.error_line.innerHTML = errorMessage;
|
||||
this.app.interface.error_line.style.color = "red";
|
||||
this.app.interface.error_line.classList.remove("hidden");
|
||||
// @ts-ignore
|
||||
this.errorTimeoutID = setTimeout(
|
||||
() => this.app.interface.error_line.classList.add("hidden"),
|
||||
2000,
|
||||
);
|
||||
};
|
||||
|
||||
_logMessage = (message: any, error: boolean = false): void => {
|
||||
console.log(message);
|
||||
clearTimeout(this.printTimeoutID);
|
||||
clearTimeout(this.errorTimeoutID);
|
||||
this.app.interface.error_line.innerHTML = message as string;
|
||||
this.app.interface.error_line.style.color = error ? "red" : "white";
|
||||
this.app.interface.error_line.classList.remove("hidden");
|
||||
// @ts-ignore
|
||||
this.printTimeoutID = setTimeout(
|
||||
() => this.app.interface.error_line.classList.add("hidden"),
|
||||
4000,
|
||||
);
|
||||
};
|
||||
|
||||
// =============================================================
|
||||
// Quantification functions
|
||||
// =============================================================
|
||||
|
||||
public quantize = (value: number, quantization: number[]): number => {
|
||||
/**
|
||||
* Returns the closest value in an array to a given value.
|
||||
*
|
||||
* @param value - The value to quantize
|
||||
* @param quantization - The array of values to quantize to
|
||||
* @returns The closest value in the array to the given value
|
||||
*/
|
||||
if (quantization.length === 0) {
|
||||
return value;
|
||||
}
|
||||
let closest: number | undefined = quantization[0];
|
||||
quantization.forEach((q) => {
|
||||
if (Math.abs(q - value) < Math.abs(closest! - value)) {
|
||||
closest = q;
|
||||
}
|
||||
});
|
||||
return closest!;
|
||||
};
|
||||
quant = this.quantize;
|
||||
|
||||
public clamp = (value: number, min: number, max: number): number => {
|
||||
/**
|
||||
* Returns a value clamped between min and max.
|
||||
*
|
||||
* @param value - The value to clamp
|
||||
* @param min - The minimum value of the clamped value
|
||||
* @param max - The maximum value of the clamped value
|
||||
* @returns A value clamped between min and max
|
||||
*/
|
||||
return Math.min(Math.max(value, min), max);
|
||||
};
|
||||
cmp = this.clamp;
|
||||
|
||||
// =============================================================
|
||||
// Time markers
|
||||
// =============================================================
|
||||
|
||||
// =============================================================
|
||||
// Fill
|
||||
// =============================================================
|
||||
|
||||
public fill = (): boolean => this.app.fill;
|
||||
|
||||
scale = getScaleNotes;
|
||||
nearScales = nearScales;
|
||||
|
||||
public cue = (functionName: string | Function): void => {
|
||||
functionName = typeof functionName === "function" ? functionName.name : functionName;
|
||||
this.cueTimes[functionName] = this.app.clock.grain;
|
||||
};
|
||||
|
||||
onmousemove = (e: MouseEvent) => {
|
||||
this.app._mouseX = e.pageX;
|
||||
this.app._mouseY = e.pageY;
|
||||
};
|
||||
}
|
||||
@ -1,61 +0,0 @@
|
||||
import { isGenerator, isGeneratorFunction, maybeToNumber } from "../Utils/Generic";
|
||||
import { type Player } from "../Classes/ZPlayer";
|
||||
import { type UserAPI } from "./API";
|
||||
|
||||
|
||||
export const generateCacheKey = () => (...args: any[]): string => {
|
||||
return args.map((arg) => JSON.stringify(arg)).join(",");
|
||||
};
|
||||
|
||||
export const resetAllFromCache = (api: UserAPI) => (): void => {
|
||||
api.patternCache.forEach((player) => (player as Player).reset());
|
||||
};
|
||||
|
||||
export const clearPatternCache = (api: UserAPI) => (): void => {
|
||||
api.patternCache.clear();
|
||||
};
|
||||
|
||||
export const removePatternFromCache = (api: UserAPI) => (id: string): void => {
|
||||
api.patternCache.delete(id);
|
||||
};
|
||||
|
||||
|
||||
export const cache = (api: UserAPI) => (key: string, value: any) => {
|
||||
if (value !== undefined) {
|
||||
if (isGenerator(value)) {
|
||||
if (api.patternCache.has(key)) {
|
||||
const cachedValue = (api.patternCache.get(key) as Generator<any>).next().value;
|
||||
if (cachedValue !== 0 && !cachedValue) {
|
||||
const generator = value as unknown as Generator<any>;
|
||||
api.patternCache.set(key, generator);
|
||||
return maybeToNumber(generator.next().value);
|
||||
}
|
||||
return maybeToNumber(cachedValue);
|
||||
} else {
|
||||
const generator = value as unknown as Generator<any>;
|
||||
api.patternCache.set(key, generator);
|
||||
return maybeToNumber(generator.next().value);
|
||||
}
|
||||
} else if (isGeneratorFunction(value)) {
|
||||
if (api.patternCache.has(key)) {
|
||||
const cachedValue = (api.patternCache.get(key) as Generator<any>).next().value;
|
||||
if (cachedValue || cachedValue === 0 || cachedValue === 0n) {
|
||||
return maybeToNumber(cachedValue);
|
||||
} else {
|
||||
const generator = value();
|
||||
api.patternCache.set(key, generator);
|
||||
return maybeToNumber(generator.next().value);
|
||||
}
|
||||
} else {
|
||||
const generator = value();
|
||||
api.patternCache.set(key, generator);
|
||||
return maybeToNumber(generator.next().value);
|
||||
}
|
||||
} else {
|
||||
api.patternCache.set(key, value);
|
||||
return maybeToNumber(value);
|
||||
}
|
||||
} else {
|
||||
return maybeToNumber(api.patternCache.get(key));
|
||||
}
|
||||
};
|
||||
@ -1,43 +0,0 @@
|
||||
import { type UserAPI } from "./API";
|
||||
import { type Editor } from "../main";
|
||||
|
||||
export const once = (api: UserAPI) => (): boolean => {
|
||||
const firstTime = api.onceEvaluator;
|
||||
api.onceEvaluator = false;
|
||||
return firstTime;
|
||||
};
|
||||
|
||||
export const counter = (api: UserAPI) => (name: string | number, limit?: number, step?: number): number => {
|
||||
if (!(name in api.counters)) {
|
||||
api.counters[name] = {
|
||||
value: 0,
|
||||
step: step ?? 1,
|
||||
limit,
|
||||
};
|
||||
} else {
|
||||
if (api.counters[name].limit !== limit) {
|
||||
api.counters[name].value = 0;
|
||||
api.counters[name].limit = limit;
|
||||
}
|
||||
|
||||
if (api.counters[name].step !== step) {
|
||||
api.counters[name].step = step ?? api.counters[name].step;
|
||||
}
|
||||
|
||||
api.counters[name].value += api.counters[name].step;
|
||||
|
||||
if (api.counters[name].limit !== undefined && api.counters[name].value > api.counters[name].limit) {
|
||||
api.counters[name].value = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return api.counters[name].value;
|
||||
};
|
||||
|
||||
export const i = (app: Editor) => (n?: number) => {
|
||||
if (n !== undefined) {
|
||||
app.universes[app.selected_universe]!.global.evaluations = n;
|
||||
return app.universes[app.selected_universe];
|
||||
}
|
||||
return app.universes[app.selected_universe]!.global.evaluations as number;
|
||||
};
|
||||
@ -1,452 +0,0 @@
|
||||
import { OscilloscopeConfig } from "../../DOM/Visuals/Oscilloscope";
|
||||
import { createConicGradient, createLinearGradient, createRadialGradient, drawBackground, drawBox, drawBall, drawBalloid, drawDonut, drawEquilateral, drawImage, drawPie, drawSmiley, drawStar, drawStroke, drawText, drawTriangular } from "../../DOM/Visuals/CanvasVisuals";
|
||||
import { Editor } from "../../main";
|
||||
|
||||
export type ShapeObject = {
|
||||
x: number;
|
||||
y: number;
|
||||
x1: number;
|
||||
y1: number;
|
||||
x2: number;
|
||||
y2: number;
|
||||
radius: number;
|
||||
width: number;
|
||||
height: number;
|
||||
fillStyle: string;
|
||||
secondary: string;
|
||||
strokeStyle: string;
|
||||
rotation: number;
|
||||
points: number;
|
||||
outerRadius: number;
|
||||
eyeSize: number;
|
||||
happiness: number;
|
||||
slices: number;
|
||||
gap: number;
|
||||
font: string;
|
||||
fontSize: number;
|
||||
text: string;
|
||||
filter: string;
|
||||
url: string;
|
||||
curve: number;
|
||||
curves: number;
|
||||
stroke: string;
|
||||
eaten: number;
|
||||
hole: number;
|
||||
};
|
||||
|
||||
|
||||
export const loadHydra = (app: Editor) => (): void => {
|
||||
app.api.log("Hydra is now loaded!")
|
||||
app.ensureHydraLoaded()
|
||||
}
|
||||
|
||||
export const w = (app: Editor) => (): number => {
|
||||
const canvas: HTMLCanvasElement = app.interface["feedback"] as HTMLCanvasElement;
|
||||
return canvas.clientWidth;
|
||||
};
|
||||
|
||||
export const pulseLocation = (app: Editor) => (): number => {
|
||||
return ((app.api.epulse() / app.api.pulsesForBar()) * w(app)()) % w(app)();
|
||||
};
|
||||
|
||||
export const clear = (app: Editor) => (): boolean => {
|
||||
const canvas: HTMLCanvasElement = app.interface["feedback"] as HTMLCanvasElement;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
export const h = (app: Editor) => (): number => {
|
||||
const canvas: HTMLCanvasElement = app.interface["feedback"] as HTMLCanvasElement;
|
||||
return canvas.clientHeight;
|
||||
};
|
||||
|
||||
export const hc = (app: Editor) => (): number => {
|
||||
return h(app)() / 2;
|
||||
};
|
||||
|
||||
export const wc = (app: Editor) => (): number => {
|
||||
return w(app)() / 2;
|
||||
};
|
||||
|
||||
export const background = (app: Editor) => (color: string | number, ...gb: number[]): boolean => {
|
||||
drawBackground(app.interface["feedback"] as HTMLCanvasElement, color, ...gb);
|
||||
return true;
|
||||
};
|
||||
export const bg = background;
|
||||
|
||||
export const linearGradient = (app: Editor) => (x1: number, y1: number, x2: number, y2: number, ...stops: (number | string)[]): CanvasGradient => {
|
||||
return createLinearGradient(app.interface["feedback"] as HTMLCanvasElement, x1, y1, x2, y2, ...stops);
|
||||
};
|
||||
|
||||
export const radialGradient = (app: Editor) => (x1: number, y1: number, r1: number, x2: number, y2: number, r2: number, ...stops: (number | string)[]) => {
|
||||
return createRadialGradient(app.interface["feedback"] as HTMLCanvasElement, x1, y1, r1, x2, y2, r2, ...stops);
|
||||
};
|
||||
|
||||
export const conicGradient = (app: Editor) => (x: number, y: number, angle: number, ...stops: (number | string)[]) => {
|
||||
return createConicGradient(app.interface["feedback"] as HTMLCanvasElement, x, y, angle, ...stops);
|
||||
};
|
||||
|
||||
export const draw = (app: Editor) => (func: Function): boolean => {
|
||||
if (typeof func === "string") {
|
||||
drawText(app.interface["feedback"] as HTMLCanvasElement, func, 24, 0, "Arial", wc(app)(), hc(app)(), "white", "none");
|
||||
} else {
|
||||
const canvas: HTMLCanvasElement = app.interface["feedback"] as HTMLCanvasElement;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
func(ctx);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// Additional drawing and utility functions in canvas.ts
|
||||
export const balloid = (app: Editor) => (
|
||||
curves: number | ShapeObject = 6,
|
||||
radius: number = hc(app)() / 2,
|
||||
curve: number = 1.5,
|
||||
fillStyle: string = "white",
|
||||
secondary: string = "black",
|
||||
x: number = wc(app)(),
|
||||
y: number = hc(app)(),
|
||||
): boolean => {
|
||||
if (typeof curves === "object") {
|
||||
fillStyle = curves.fillStyle || "white";
|
||||
x = curves.x || wc(app)();
|
||||
y = curves.y || hc(app)();
|
||||
curve = curves.curve || 1.5;
|
||||
radius = curves.radius || hc(app)() / 2;
|
||||
curves = curves.curves || 6;
|
||||
}
|
||||
drawBalloid(app.interface["feedback"] as HTMLCanvasElement, curves, radius, curve, fillStyle, secondary, x, y);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const equilateral = (app: Editor) => (
|
||||
radius: number | ShapeObject = hc(app)() / 3,
|
||||
fillStyle: string = "white",
|
||||
rotation: number = 0,
|
||||
x: number = wc(app)(),
|
||||
y: number = hc(app)(),
|
||||
): boolean => {
|
||||
if (typeof radius === "object") {
|
||||
fillStyle = radius.fillStyle || "white";
|
||||
x = radius.x || wc(app)();
|
||||
y = radius.y || hc(app)();
|
||||
rotation = radius.rotation || 0;
|
||||
radius = radius.radius || hc(app)() / 3;
|
||||
}
|
||||
drawEquilateral(app.interface["feedback"] as HTMLCanvasElement, radius, fillStyle, rotation, x, y);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const triangular = (app: Editor) => (
|
||||
width: number | ShapeObject = hc(app)() / 3,
|
||||
height: number = hc(app)() / 3,
|
||||
fillStyle: string = "white",
|
||||
rotation: number = 0,
|
||||
x: number = wc(app)(),
|
||||
y: number = hc(app)(),
|
||||
): boolean => {
|
||||
if (typeof width === "object") {
|
||||
fillStyle = width.fillStyle || "white";
|
||||
x = width.x || wc(app)();
|
||||
y = width.y || hc(app)();
|
||||
rotation = width.rotation || 0;
|
||||
height = width.height || hc(app)() / 3;
|
||||
width = width.width || hc(app)() / 3;
|
||||
}
|
||||
drawTriangular(app.interface['feedback'] as HTMLCanvasElement, width, height, fillStyle, rotation, x, y);
|
||||
return true;
|
||||
};
|
||||
export const pointy = triangular;
|
||||
|
||||
export const ball = (app: Editor) => (
|
||||
radius: number | ShapeObject = hc(app)() / 3,
|
||||
fillStyle: string = "white",
|
||||
x: number = wc(app)(),
|
||||
y: number = hc(app)(),
|
||||
): boolean => {
|
||||
if (typeof radius === "object") {
|
||||
fillStyle = radius.fillStyle || "white";
|
||||
x = radius.x || wc(app)();
|
||||
y = radius.y || hc(app)();
|
||||
radius = radius.radius || hc(app)() / 3;
|
||||
}
|
||||
drawBall(app.interface['feedback'] as HTMLCanvasElement, radius, fillStyle, x, y);
|
||||
return true;
|
||||
};
|
||||
export const circle = ball;
|
||||
|
||||
export const donut = (app: Editor) => (
|
||||
slices: number | ShapeObject = 3,
|
||||
eaten: number = 0,
|
||||
radius: number = hc(app)() / 3,
|
||||
hole: number = hc(app)() / 12,
|
||||
fillStyle: string = "white",
|
||||
secondary: string = "black",
|
||||
stroke: string = "black",
|
||||
rotation: number = 0,
|
||||
x: number = wc(app)(),
|
||||
y: number = hc(app)(),
|
||||
): boolean => {
|
||||
if (typeof slices === "object") {
|
||||
fillStyle = slices.fillStyle || "white";
|
||||
x = slices.x || wc(app)();
|
||||
y = slices.y || hc(app)();
|
||||
rotation = slices.rotation || 0;
|
||||
radius = slices.radius || hc(app)() / 3;
|
||||
eaten = slices.eaten || 0;
|
||||
hole = slices.hole || hc(app)() / 12;
|
||||
secondary = slices.secondary || "black";
|
||||
stroke = slices.stroke || "black";
|
||||
slices = slices.slices || 3;
|
||||
}
|
||||
drawDonut(app.interface['feedback'] as HTMLCanvasElement, slices, eaten, radius, hole, fillStyle, secondary, stroke, rotation, x, y);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const pie = (app: Editor) => (
|
||||
slices: number | ShapeObject = 3,
|
||||
eaten: number = 0,
|
||||
radius: number = hc(app)() / 3,
|
||||
fillStyle: string = "white",
|
||||
secondary: string = "black",
|
||||
stroke: string = "black",
|
||||
rotation: number = 0,
|
||||
x: number = wc(app)(),
|
||||
y: number = hc(app)(),
|
||||
): boolean => {
|
||||
if (typeof slices === "object") {
|
||||
fillStyle = slices.fillStyle || "white";
|
||||
x = slices.x || wc(app)();
|
||||
y = slices.y || hc(app)();
|
||||
rotation = slices.rotation || 0;
|
||||
radius = slices.radius || hc(app)() / 3;
|
||||
secondary = slices.secondary || "black";
|
||||
stroke = slices.stroke || "black";
|
||||
eaten = slices.eaten || 0;
|
||||
slices = slices.slices || 3;
|
||||
}
|
||||
drawPie(app.interface['feedback'] as HTMLCanvasElement, slices, eaten, radius, fillStyle, secondary, stroke, rotation, x, y);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const star = (app: Editor) => (
|
||||
points: number | ShapeObject = 5,
|
||||
radius: number = hc(app)() / 3,
|
||||
fillStyle: string = "white",
|
||||
rotation: number = 0,
|
||||
outerRadius: number = radius / 100,
|
||||
x: number = wc(app)(),
|
||||
y: number = hc(app)(),
|
||||
): boolean => {
|
||||
if (typeof points === "object") {
|
||||
radius = points.radius || hc(app)() / 3;
|
||||
fillStyle = points.fillStyle || "white";
|
||||
x = points.x || wc(app)();
|
||||
y = points.y || hc(app)();
|
||||
rotation = points.rotation || 0;
|
||||
outerRadius = points.outerRadius || radius / 100;
|
||||
points = points.points || 5;
|
||||
}
|
||||
drawStar(app.interface['feedback'] as HTMLCanvasElement, points, radius, fillStyle, rotation, outerRadius, x, y);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const stroke = (app: Editor) => (
|
||||
width: number | ShapeObject = 1,
|
||||
strokeStyle: string = "white",
|
||||
rotation: number = 0,
|
||||
x1: number = wc(app)() - wc(app)() / 10,
|
||||
y1: number = hc(app)(),
|
||||
x2: number = wc(app)() + wc(app)() / 5,
|
||||
y2: number = hc(app)(),
|
||||
): boolean => {
|
||||
if (typeof width === "object") {
|
||||
strokeStyle = width.strokeStyle || "white";
|
||||
x1 = width.x1 || wc(app)() - wc(app)() / 10;
|
||||
y1 = width.y1 || hc(app)();
|
||||
x2 = width.x2 || wc(app)() + wc(app)() / 5;
|
||||
y2 = width.y2 || hc(app)();
|
||||
rotation = width.rotation || 0;
|
||||
width = width.width || 1;
|
||||
}
|
||||
drawStroke(app.interface['feedback'] as HTMLCanvasElement, width, strokeStyle, rotation, x1, y1, x2, y2);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const box = (app: Editor) => (
|
||||
width: number | ShapeObject = wc(app)() / 4,
|
||||
height: number = wc(app)() / 4,
|
||||
fillStyle: string = "white",
|
||||
rotation: number = 0,
|
||||
x: number = wc(app)() - wc(app)() / 8,
|
||||
y: number = hc(app)() - hc(app)() / 8,
|
||||
): boolean => {
|
||||
if (typeof width === "object") {
|
||||
fillStyle = width.fillStyle || "white";
|
||||
x = width.x || wc(app)() - wc(app)() / 4;
|
||||
y = width.y || hc(app)() - hc(app)() / 2;
|
||||
rotation = width.rotation || 0;
|
||||
height = width.height || wc(app)() / 4;
|
||||
width = width.width || wc(app)() / 4;
|
||||
}
|
||||
drawBox(app.interface['feedback'] as HTMLCanvasElement, width, height, fillStyle, rotation, x, y);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const smiley = (app: Editor) => (
|
||||
happiness: number | ShapeObject = 0,
|
||||
radius: number = hc(app)() / 3,
|
||||
eyeSize: number = 3.0,
|
||||
fillStyle: string = "yellow",
|
||||
rotation: number = 0,
|
||||
x: number = wc(app)(),
|
||||
y: number = hc(app)(),
|
||||
): boolean => {
|
||||
if (typeof happiness === "object") {
|
||||
fillStyle = happiness.fillStyle || "yellow";
|
||||
x = happiness.x || wc(app)();
|
||||
y = happiness.y || hc(app)();
|
||||
rotation = happiness.rotation || 0;
|
||||
eyeSize = happiness.eyeSize || 3.0;
|
||||
radius = happiness.radius || hc(app)() / 3;
|
||||
happiness = happiness.happiness || 0;
|
||||
}
|
||||
drawSmiley(app.interface['feedback'] as HTMLCanvasElement, happiness, radius, eyeSize, fillStyle, rotation, x, y);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const text = (app: Editor) => (
|
||||
text: string | ShapeObject,
|
||||
fontSize: number = 24,
|
||||
rotation: number = 0,
|
||||
font: string = "Arial",
|
||||
x: number = wc(app)(),
|
||||
y: number = hc(app)(),
|
||||
fillStyle: string = "white",
|
||||
filter: string = "none",
|
||||
): boolean => {
|
||||
if (typeof text === "object") {
|
||||
fillStyle = text.fillStyle || "white";
|
||||
x = text.x || wc(app)();
|
||||
y = text.y || hc(app)();
|
||||
rotation = text.rotation || 0;
|
||||
font = text.font || "Arial";
|
||||
fontSize = text.fontSize || 24;
|
||||
filter = text.filter || "none";
|
||||
text = text.text || "";
|
||||
}
|
||||
drawText(app.interface['feedback'] as HTMLCanvasElement, text, fontSize, rotation, font, x, y, fillStyle, filter);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const image = (app: Editor) => (
|
||||
url: string | ShapeObject,
|
||||
width: number = wc(app)() / 2,
|
||||
height: number = hc(app)() / 2,
|
||||
rotation: number = 0,
|
||||
x: number = wc(app)(),
|
||||
y: number = hc(app)(),
|
||||
filter: string = "none",
|
||||
): boolean => {
|
||||
if (typeof url === "object") {
|
||||
if (!url.url) return true;
|
||||
x = url.x || wc(app)();
|
||||
y = url.y || hc(app)();
|
||||
rotation = url.rotation || 0;
|
||||
width = url.width || 100;
|
||||
height = url.height || 100;
|
||||
filter = url.filter || "none";
|
||||
url = url.url || "";
|
||||
}
|
||||
drawImage(app.interface['feedback'] as HTMLCanvasElement, url, width, height, rotation, x, y, filter);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const randomChar = () => (length: number = 1, min: number = 0, max: number = 65536): string => {
|
||||
return Array.from(
|
||||
{ length }, () => String.fromCodePoint(Math.floor(Math.random() * (max - min) + min))
|
||||
).join('');
|
||||
};
|
||||
|
||||
export const randomFromRange = () => (min: number, max: number): string => {
|
||||
const codePoint = Math.floor(Math.random() * (max - min) + min);
|
||||
return String.fromCodePoint(codePoint);
|
||||
};
|
||||
|
||||
export const emoji = () => (n: number = 1): string => {
|
||||
return randomChar()(n, 0x1f600, 0x1f64f);
|
||||
};
|
||||
|
||||
export const food = () => (n: number = 1): string => {
|
||||
return randomChar()(n, 0x1f32d, 0x1f37f);
|
||||
};
|
||||
|
||||
export const animals = () => (n: number = 1): string => {
|
||||
return randomChar()(n, 0x1f400, 0x1f4d3);
|
||||
};
|
||||
|
||||
export const expressions = () => (n: number = 1): string => {
|
||||
return randomChar()(n, 0x1f910, 0x1f92f);
|
||||
};
|
||||
|
||||
export const gif = (app: Editor) => (options: any): void => {
|
||||
const {
|
||||
url,
|
||||
posX = 0,
|
||||
posY = 0,
|
||||
opacity = 1,
|
||||
size = "auto",
|
||||
center = false,
|
||||
rotation = 0,
|
||||
filter = 'none',
|
||||
duration = 10
|
||||
} = options;
|
||||
|
||||
let real_duration = duration * app.clock.time_position.tick_duration * app.clock.ppqn;
|
||||
let fadeOutDuration = real_duration * 0.1;
|
||||
let visibilityDuration = real_duration - fadeOutDuration;
|
||||
const gifElement = document.createElement("img");
|
||||
gifElement.src = url;
|
||||
gifElement.style.position = "fixed";
|
||||
gifElement.style.left = center ? "50%" : `${posX}px`;
|
||||
gifElement.style.top = center ? "50%" : `${posY}px`;
|
||||
gifElement.style.opacity = `${opacity}`;
|
||||
gifElement.style.zIndex = "1000"; // Ensure it's on top, fixed zIndex
|
||||
if (size !== "auto") {
|
||||
gifElement.style.width = size;
|
||||
gifElement.style.height = size;
|
||||
}
|
||||
const transformRules = [`rotate(${rotation}deg)`];
|
||||
if (center) {
|
||||
transformRules.unshift("translate(-50%, -50%)");
|
||||
}
|
||||
gifElement.style.transform = transformRules.join(" ");
|
||||
gifElement.style.filter = filter;
|
||||
gifElement.style.transition = `opacity ${fadeOutDuration}s ease`;
|
||||
document.body.appendChild(gifElement);
|
||||
|
||||
// Start the fade-out at the end of the visibility duration
|
||||
setTimeout(() => {
|
||||
gifElement.style.opacity = "0";
|
||||
}, visibilityDuration * 1000);
|
||||
|
||||
// Remove the GIF from the DOM after the fade-out duration
|
||||
setTimeout(() => {
|
||||
if (document.body.contains(gifElement)) {
|
||||
document.body.removeChild(gifElement);
|
||||
}
|
||||
}, real_duration * 1000);
|
||||
};
|
||||
|
||||
export const scope = (app: Editor) => (config: OscilloscopeConfig): void => {
|
||||
/**
|
||||
* Configures the oscilloscope.
|
||||
* @param config - The configuration object for the oscilloscope.
|
||||
*/
|
||||
app.osc = {
|
||||
...app.osc,
|
||||
...config,
|
||||
};
|
||||
};
|
||||
@ -1,22 +0,0 @@
|
||||
import { type UserAPI } from "../API";
|
||||
|
||||
export const log = (api: UserAPI) => (message: any) => {
|
||||
/**
|
||||
* Logs a message to the console and app-specific logger.
|
||||
* @param message - The message to log.
|
||||
*/
|
||||
console.log(message);
|
||||
api._logMessage(message, false);
|
||||
};
|
||||
|
||||
export const logOnce = (api: UserAPI) => (message: any) => {
|
||||
/**
|
||||
* Logs a message to the console and app-specific logger, but only once.
|
||||
* @param message - The message to log.
|
||||
*/
|
||||
if (api.onceEvaluator) {
|
||||
console.log(message);
|
||||
api._logMessage(message, false);
|
||||
api.onceEvaluator = false;
|
||||
}
|
||||
};
|
||||
@ -1,29 +0,0 @@
|
||||
import { Editor } from "../../main";
|
||||
|
||||
export const mouseX = (app: Editor) => (): number => {
|
||||
/**
|
||||
* @returns The current x position of the mouse
|
||||
*/
|
||||
return app._mouseX;
|
||||
};
|
||||
|
||||
export const mouseY = (app: Editor) => (): number => {
|
||||
/**
|
||||
* @returns The current y position of the mouse
|
||||
*/
|
||||
return app._mouseY;
|
||||
};
|
||||
|
||||
export const noteX = (app: Editor) => (): number => {
|
||||
/**
|
||||
* @returns The current x position scaled to 0-127 using screen width
|
||||
*/
|
||||
return Math.floor((app._mouseX / document.body.clientWidth) * 127);
|
||||
};
|
||||
|
||||
export const noteY = (app: Editor) => (): number => {
|
||||
/**
|
||||
* @returns The current y position scaled to 0-127 using screen height
|
||||
*/
|
||||
return Math.floor((app._mouseY / document.body.clientHeight) * 127);
|
||||
};
|
||||
@ -1,32 +0,0 @@
|
||||
import { type Editor } from '../../main';
|
||||
import colorschemes from "../../Editor/colors.json";
|
||||
|
||||
export const theme = (app: Editor) => (color_scheme: string): void => {
|
||||
app.readTheme(color_scheme);
|
||||
};
|
||||
|
||||
export const themeName = (app: Editor) => (): string => {
|
||||
return app.currentThemeName;
|
||||
};
|
||||
|
||||
export const randomTheme = (app: Editor) => (): void => {
|
||||
let theme_names = getThemes()();
|
||||
let selected_theme = theme_names[Math.floor(Math.random() * theme_names.length)];
|
||||
if (selected_theme) {
|
||||
app.readTheme(selected_theme);
|
||||
}
|
||||
};
|
||||
|
||||
export const nextTheme = (app: Editor) => (): void => {
|
||||
let theme_names = getThemes()();
|
||||
let current_theme = themeName(app)();
|
||||
let current_theme_idx = theme_names.indexOf(current_theme);
|
||||
let next_theme_idx = (current_theme_idx + 1) % theme_names.length;
|
||||
let next_theme = theme_names[next_theme_idx];
|
||||
app.readTheme(next_theme!);
|
||||
app.api.log(next_theme);
|
||||
};
|
||||
|
||||
export const getThemes = () => (): string[] => {
|
||||
return Object.keys(colorschemes);
|
||||
};
|
||||
@ -1,39 +0,0 @@
|
||||
import { type UserAPI } from './API';
|
||||
|
||||
export const drunk = (api: UserAPI) => (n?: number): number => {
|
||||
/**
|
||||
* This function sets or returns the current drunk mechanism's value.
|
||||
* @param n - [optional] The value to set the drunk mechanism to
|
||||
* @returns The current value of the drunk mechanism
|
||||
*/
|
||||
if (n !== undefined) {
|
||||
api._drunk.position = n;
|
||||
return api._drunk.getPosition();
|
||||
}
|
||||
api._drunk.step();
|
||||
return api._drunk.getPosition();
|
||||
};
|
||||
|
||||
export const drunk_max = (api: UserAPI) => (max: number): void => {
|
||||
/**
|
||||
* Sets the maximum value of the drunk mechanism.
|
||||
* @param max - The maximum value of the drunk mechanism
|
||||
*/
|
||||
api._drunk.max = max;
|
||||
};
|
||||
|
||||
export const drunk_min = (api: UserAPI) => (min: number): void => {
|
||||
/**
|
||||
* Sets the minimum value of the drunk mechanism.
|
||||
* @param min - The minimum value of the drunk mechanism
|
||||
*/
|
||||
api._drunk.min = min;
|
||||
};
|
||||
|
||||
export const drunk_wrap = (api: UserAPI) => (wrap: boolean): void => {
|
||||
/**
|
||||
* Sets whether the drunk mechanism should wrap around
|
||||
* @param wrap - Whether the drunk mechanism should wrap around
|
||||
*/
|
||||
api._drunk.toggleWrap(wrap);
|
||||
};
|
||||
@ -1,198 +0,0 @@
|
||||
import { getAllScaleNotes } from 'zifferjs';
|
||||
import {
|
||||
MidiCCEvent,
|
||||
MidiNoteEvent,
|
||||
} from "../../IO/MidiConnection";
|
||||
import { MidiEvent, MidiParams } from "../../Classes/MidiEvent";
|
||||
import { UserAPI } from '../API';
|
||||
import { Editor } from '../../main';
|
||||
|
||||
interface ControlChange {
|
||||
channel: number;
|
||||
control: number;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export const midi_outputs = (api: UserAPI) => (): void => {
|
||||
api._logMessage(api.MidiConnection.listMidiOutputs(), false);
|
||||
};
|
||||
|
||||
export const midi_output = (api: UserAPI) => (outputName: string): void => {
|
||||
if (!outputName) {
|
||||
console.log(api.MidiConnection.getCurrentMidiPort());
|
||||
} else {
|
||||
api.MidiConnection.switchMidiOutput(outputName);
|
||||
}
|
||||
};
|
||||
|
||||
export const midi = (app: Editor) => (
|
||||
value: number | number[] = 60,
|
||||
velocity?: number | number[],
|
||||
channel?: number | number[],
|
||||
port?: number | string | number[] | string[],
|
||||
): MidiEvent => {
|
||||
const event = { note: value, velocity, channel, port } as MidiParams;
|
||||
return new MidiEvent(event, app);
|
||||
};
|
||||
|
||||
export const sysex = (api: UserAPI) => (data: Array<number>): void => {
|
||||
api.MidiConnection.sendSysExMessage(data);
|
||||
};
|
||||
|
||||
export const pitch_bend = (api: UserAPI) => (value: number, channel: number): void => {
|
||||
api.MidiConnection.sendPitchBend(value, channel);
|
||||
};
|
||||
|
||||
export const program_change = (api: UserAPI) => (program: number, channel: number): void => {
|
||||
api.MidiConnection.sendProgramChange(program, channel);
|
||||
};
|
||||
|
||||
export const midi_clock = (api: UserAPI) => (): void => {
|
||||
api.MidiConnection.sendMidiClock();
|
||||
};
|
||||
|
||||
export const control_change = (api: UserAPI) => ({
|
||||
control = 20,
|
||||
value = 0,
|
||||
channel = 0,
|
||||
}: ControlChange): void => {
|
||||
api.MidiConnection.sendMidiControlChange(control, value, channel);
|
||||
};
|
||||
|
||||
export const cc = control_change;
|
||||
|
||||
export const midi_panic = (api: UserAPI) => (): void => {
|
||||
api.MidiConnection.panic();
|
||||
};
|
||||
|
||||
export const active_note_events = (api: UserAPI) => (
|
||||
channel?: number,
|
||||
): MidiNoteEvent[] | undefined => {
|
||||
let events;
|
||||
if (channel) {
|
||||
events = api.MidiConnection.activeNotesFromChannel(channel);
|
||||
} else {
|
||||
events = api.MidiConnection.activeNotes;
|
||||
}
|
||||
if (events.length > 0) return events;
|
||||
else return undefined;
|
||||
};
|
||||
|
||||
export const transmission = (api: UserAPI) => (): boolean => {
|
||||
return api.MidiConnection.activeNotes.length > 0;
|
||||
};
|
||||
|
||||
export const active_notes = (api: UserAPI) => (channel?: number): number[] | undefined => {
|
||||
const events = active_note_events(api)(channel);
|
||||
if (events && events.length > 0) return events.map((e) => e.note);
|
||||
else return undefined;
|
||||
};
|
||||
|
||||
export const kill_active_notes = (api: UserAPI) => (): void => {
|
||||
api.MidiConnection.activeNotes = [];
|
||||
};
|
||||
|
||||
export const sticky_notes = (api: UserAPI) => (channel?: number): number[] | undefined => {
|
||||
let notes;
|
||||
if (channel) notes = api.MidiConnection.stickyNotesFromChannel(channel);
|
||||
else notes = api.MidiConnection.stickyNotes;
|
||||
if (notes.length > 0) return notes.map((e: any) => e.note);
|
||||
else return undefined;
|
||||
};
|
||||
|
||||
export const kill_sticky_notes = (api: UserAPI) => (): void => {
|
||||
api.MidiConnection.stickyNotes = [];
|
||||
};
|
||||
|
||||
export const buffer = (api: UserAPI) => (channel?: number): boolean => {
|
||||
if (channel)
|
||||
return (
|
||||
api.MidiConnection.findNoteFromBufferInChannel(channel) !== undefined
|
||||
);
|
||||
else return api.MidiConnection.noteInputBuffer.length > 0;
|
||||
};
|
||||
|
||||
export const buffer_event = (api: UserAPI) => (channel?: number): MidiNoteEvent | undefined => {
|
||||
if (channel)
|
||||
return api.MidiConnection.findNoteFromBufferInChannel(channel);
|
||||
else return api.MidiConnection.noteInputBuffer.shift();
|
||||
};
|
||||
|
||||
export const buffer_note = (api: UserAPI) => (channel?: number): number | undefined => {
|
||||
const note = buffer_event(api)(channel);
|
||||
return note ? note.note : undefined;
|
||||
};
|
||||
|
||||
export const last_note_event = (api: UserAPI) => (channel?: number): MidiNoteEvent | undefined => {
|
||||
if (channel) return api.MidiConnection.lastNoteInChannel[channel];
|
||||
else return api.MidiConnection.lastNote;
|
||||
};
|
||||
|
||||
export const last_note = (api: UserAPI) => (channel?: number): number => {
|
||||
const note = last_note_event(api)(channel);
|
||||
return note ? note.note : 60;
|
||||
};
|
||||
|
||||
export const ccIn = (api: UserAPI) => (control: number, channel?: number): number => {
|
||||
if (channel) {
|
||||
if (api.MidiConnection.lastCCInChannel[channel]) {
|
||||
return api.MidiConnection.lastCCInChannel[channel]?.[control] ?? 0;
|
||||
} else return 0;
|
||||
} else return api.MidiConnection.lastCC[control] ?? 0;
|
||||
};
|
||||
|
||||
export const has_cc = (api: UserAPI) => (channel?: number): boolean => {
|
||||
if (channel)
|
||||
return (
|
||||
api.MidiConnection.findCCFromBufferInChannel(channel) !== undefined
|
||||
);
|
||||
else return api.MidiConnection.ccInputBuffer.length > 0;
|
||||
};
|
||||
|
||||
export const buffer_cc = (api: UserAPI) => (channel?: number): MidiCCEvent | undefined => {
|
||||
if (channel) return api.MidiConnection.findCCFromBufferInChannel(channel);
|
||||
else return api.MidiConnection.ccInputBuffer.shift();
|
||||
};
|
||||
|
||||
export const show_scale = (api: UserAPI) => (
|
||||
root: number | string,
|
||||
scale: number | string,
|
||||
channel: number = 0,
|
||||
port: number | string = api.MidiConnection.currentOutputIndex || 0,
|
||||
soundOff: boolean = false,
|
||||
): void => {
|
||||
if (!api.scale_aid || scale !== api.scale_aid) {
|
||||
hide_scale(api)(channel, port);
|
||||
const scaleNotes = getAllScaleNotes(scale, root);
|
||||
scaleNotes.forEach((note) => {
|
||||
api.MidiConnection.sendMidiOn(note, channel, 1, port);
|
||||
if (soundOff) api.MidiConnection.sendAllSoundOff(channel, port);
|
||||
});
|
||||
api.scale_aid = scale;
|
||||
}
|
||||
};
|
||||
|
||||
export const hide_scale = (api: UserAPI) => (
|
||||
channel: number = 0,
|
||||
port: number | string = api.MidiConnection.currentOutputIndex || 0,
|
||||
): void => {
|
||||
const allNotes = Array.from(Array(128).keys());
|
||||
allNotes.forEach((note) => {
|
||||
api.MidiConnection.sendMidiOff(note, channel, port);
|
||||
});
|
||||
api.scale_aid = undefined;
|
||||
};
|
||||
|
||||
export const midi_notes_off = (api: UserAPI) => (
|
||||
channel: number = 0,
|
||||
port: number | string = api.MidiConnection.currentOutputIndex || 0,
|
||||
): void => {
|
||||
api.MidiConnection.sendAllNotesOff(channel, port);
|
||||
};
|
||||
|
||||
export const midi_sound_off = (api: UserAPI) => (
|
||||
channel: number = 0,
|
||||
port: number | string = api.MidiConnection.currentOutputIndex || 0,
|
||||
): void => {
|
||||
api.MidiConnection.sendAllSoundOff(channel, port);
|
||||
};
|
||||
@ -1,28 +0,0 @@
|
||||
import { sendToServer, type OSCMessage } from "../../IO/OSC";
|
||||
import { oscMessages } from "../../IO/OSC";
|
||||
import { type Editor } from "../../main";
|
||||
|
||||
export const osc = (app: Editor) => (address: string, port: number, ...args: any[]): void => {
|
||||
/**
|
||||
* Sends an OSC message to the server.
|
||||
*/
|
||||
sendToServer({
|
||||
address: address,
|
||||
port: port,
|
||||
args: args,
|
||||
timetag: Math.round(Date.now() - app.clock.getTimeDeviation()),
|
||||
} as OSCMessage);
|
||||
};
|
||||
|
||||
export const getOSC = () => (address?: string): any[] => {
|
||||
/**
|
||||
* Retrieves incoming OSC messages. Filters by address if provided.
|
||||
*/
|
||||
if (address) {
|
||||
let messages = oscMessages.filter((msg: { address: string; }) => msg.address === address);
|
||||
messages = messages.map((msg: { data: any; }) => msg.data);
|
||||
return messages;
|
||||
} else {
|
||||
return oscMessages;
|
||||
}
|
||||
};
|
||||
@ -1,68 +0,0 @@
|
||||
import { Editor } from "../main";
|
||||
import { UserAPI } from "./API";
|
||||
|
||||
export const line = () => (start: number, end: number, step: number = 1): number[] => {
|
||||
const countPlaces = (num: number) => {
|
||||
var text = num.toString();
|
||||
var index = text.indexOf(".");
|
||||
return index == -1 ? 0 : (text.length - index - 1);
|
||||
};
|
||||
|
||||
const result: number[] = [];
|
||||
|
||||
if ((end > start && step > 0) || (end < start && step < 0)) {
|
||||
for (let value = start; value <= end; value += step) {
|
||||
result.push(value);
|
||||
}
|
||||
} else if ((end > start && step < 0) || (end < start && step > 0)) {
|
||||
for (let value = start; value >= end; value -= step) {
|
||||
result.push(parseFloat(value.toFixed(countPlaces(step))));
|
||||
}
|
||||
} else {
|
||||
console.error("Invalid range or step provided.");
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
export const sine = (app: Editor) => (freq: number = 1, phase: number = 0): number => {
|
||||
return Math.sin(2 * Math.PI * freq * (app.clock.ctx.currentTime - phase));
|
||||
};
|
||||
|
||||
export const usine = (app: Editor) => (freq: number = 1, phase: number = 0): number => {
|
||||
return ((sine(app)(freq, phase) + 1) / 2);
|
||||
};
|
||||
|
||||
export const saw = (app: Editor) => (freq: number = 1, phase: number = 0): number => {
|
||||
return (((app.clock.ctx.currentTime * freq + phase) % 1) * 2 - 1);
|
||||
};
|
||||
|
||||
export const usaw = (app: Editor) => (freq: number = 1, phase: number = 0): number => {
|
||||
return ((saw(app)(freq, phase) + 1) / 2);
|
||||
};
|
||||
|
||||
export const triangle = (app: Editor) => (freq: number = 1, phase: number = 0): number => {
|
||||
return (Math.abs(saw(app)(freq, phase)) * 2 - 1);
|
||||
};
|
||||
|
||||
export const utriangle = (app: Editor) => (freq: number = 1, phase: number = 0): number => {
|
||||
return ((triangle(app)(freq, phase) + 1) / 2);
|
||||
};
|
||||
|
||||
export const square = (app: Editor) => (freq: number = 1, duty: number = 0.5): number => {
|
||||
const period = 1 / freq;
|
||||
const t = (app.clock.ctx.currentTime % period);
|
||||
return (t / period < duty ? 1 : -1);
|
||||
};
|
||||
|
||||
export const usquare = (app: Editor) => (freq: number = 1, duty: number = 0.5): number => {
|
||||
return ((square(app)(freq, duty) + 1) / 2);
|
||||
};
|
||||
|
||||
export const noise = (api: UserAPI) => (): number => {
|
||||
return (api.randomGen() * 2 - 1); // Assuming randomGen() is defined in the app context
|
||||
};
|
||||
|
||||
export const unoise = (api: UserAPI) => (): number => {
|
||||
return ((noise(api)() + 1) / 2);
|
||||
};
|
||||
@ -1,36 +0,0 @@
|
||||
// mathFunctions.ts
|
||||
export const min = () => (...values: number[]): number => {
|
||||
/**
|
||||
* Returns the minimum value of a list of numbers.
|
||||
*/
|
||||
return Math.min(...values);
|
||||
};
|
||||
|
||||
export const max = () => (...values: number[]): number => {
|
||||
/**
|
||||
* Returns the maximum value of a list of numbers.
|
||||
*/
|
||||
return Math.max(...values);
|
||||
};
|
||||
|
||||
export const mean = () => (...values: number[]): number => {
|
||||
/**
|
||||
* Returns the mean of a list of numbers.
|
||||
*/
|
||||
const sum = values.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
|
||||
return values.length > 0 ? sum / values.length : 0;
|
||||
};
|
||||
|
||||
export const limit = () => (value: number, min: number, max: number): number => {
|
||||
/**
|
||||
* Limits a value between a minimum and a maximum.
|
||||
*/
|
||||
return Math.min(Math.max(value, min), max);
|
||||
};
|
||||
|
||||
export const abs = () => (value: number): number => {
|
||||
/**
|
||||
* Returns the absolute value of a number.
|
||||
*/
|
||||
return Math.abs(value);
|
||||
};
|
||||
@ -1,53 +0,0 @@
|
||||
import { type UserAPI } from "./API";
|
||||
|
||||
export const prob = (api: UserAPI) => (p: number): boolean => {
|
||||
return api.randomGen() * 100 < p;
|
||||
};
|
||||
|
||||
export const toss = (api: UserAPI) => (): boolean => {
|
||||
return api.randomGen() > 0.5;
|
||||
};
|
||||
|
||||
export const odds = (api: UserAPI) => (n: number, beats: number = 1): boolean => {
|
||||
return api.randomGen() < (n * api.ppqn()) / (api.ppqn() * beats);
|
||||
};
|
||||
|
||||
export const never = () => (): boolean => {
|
||||
return false;
|
||||
};
|
||||
|
||||
export const almostNever = (api: UserAPI) => (beats: number = 1): boolean => {
|
||||
return api.randomGen() < (0.025 * api.ppqn()) / (api.ppqn() * beats);
|
||||
};
|
||||
|
||||
export const rarely = (api: UserAPI) => (beats: number = 1): boolean => {
|
||||
return api.randomGen() < (0.1 * api.ppqn()) / (api.ppqn() * beats);
|
||||
};
|
||||
|
||||
export const scarcely = (api: UserAPI) => (beats: number = 1): boolean => {
|
||||
return api.randomGen() < (0.25 * api.ppqn()) / (api.ppqn() * beats);
|
||||
};
|
||||
|
||||
export const sometimes = (api: UserAPI) => (beats: number = 1): boolean => {
|
||||
return api.randomGen() < (0.5 * api.ppqn()) / (api.ppqn() * beats);
|
||||
};
|
||||
|
||||
export const often = (api: UserAPI) => (beats: number = 1): boolean => {
|
||||
return api.randomGen() < (0.75 * api.ppqn()) / (api.ppqn() * beats);
|
||||
};
|
||||
|
||||
export const frequently = (api: UserAPI) => (beats: number = 1): boolean => {
|
||||
return api.randomGen() < (0.9 * api.ppqn()) / (api.ppqn() * beats);
|
||||
};
|
||||
|
||||
export const almostAlways = (api: UserAPI) => (beats: number = 1): boolean => {
|
||||
return api.randomGen() < (0.985 * api.ppqn()) / (api.ppqn() * beats);
|
||||
};
|
||||
|
||||
export const always = () => (): boolean => {
|
||||
return true;
|
||||
};
|
||||
|
||||
export const dice = (api: UserAPI) => (sides: number): number => {
|
||||
return Math.floor(api.randomGen() * sides) + 1;
|
||||
};
|
||||
@ -1,35 +0,0 @@
|
||||
import { seededRandom } from "zifferjs";
|
||||
import { UserAPI } from "./API";
|
||||
|
||||
export const randI = (api: UserAPI) => (min: number, max: number): number => {
|
||||
return Math.floor(api.randomGen() * (max - min + 1)) + min;
|
||||
};
|
||||
|
||||
export const rand = (api: UserAPI) => (min: number, max: number): number => {
|
||||
return api.randomGen() * (max - min) + min;
|
||||
};
|
||||
export const r = rand
|
||||
|
||||
export const seed = (api: UserAPI) => (seed: string | number): void => {
|
||||
if (typeof seed === "number") seed = seed.toString();
|
||||
if (api.currentSeed !== seed) {
|
||||
api.currentSeed = seed;
|
||||
api.randomGen = seededRandom(seed);
|
||||
}
|
||||
};
|
||||
|
||||
export const localSeededRandom = (api: UserAPI) => (seed: string | number): Function => {
|
||||
if (typeof seed === "number") seed = seed.toString();
|
||||
if (api.localSeeds.has(seed)) return api.localSeeds.get(seed) as Function;
|
||||
const newSeededRandom = seededRandom(seed);
|
||||
api.localSeeds.set(seed, newSeededRandom);
|
||||
return newSeededRandom;
|
||||
};
|
||||
|
||||
export const clearLocalSeed = (api: UserAPI) => (seed: string | number | undefined = undefined): void => {
|
||||
if (seed) {
|
||||
api.localSeeds.delete(seed.toString());
|
||||
} else {
|
||||
api.localSeeds.clear();
|
||||
}
|
||||
};
|
||||
@ -1,64 +0,0 @@
|
||||
import { tryEvaluate } from "../Evaluator";
|
||||
import { blinkScript } from "../DOM/Visuals/Blinkers";
|
||||
import { template_universes } from "../Editor/FileManagement";
|
||||
import { Editor } from "../main";
|
||||
|
||||
export const script = (app: Editor) => (...args: number[]): void => {
|
||||
args.forEach((arg) => {
|
||||
if (arg >= 1 && arg <= 9) {
|
||||
blinkScript(app, "local", arg);
|
||||
tryEvaluate(
|
||||
app,
|
||||
app.universes[app.selected_universe]!.locals[arg]!,
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const s = script;
|
||||
|
||||
export const delete_script = (app: Editor) => (script: number): void => {
|
||||
app.universes[app.selected_universe]!.locals[script] = {
|
||||
candidate: "",
|
||||
committed: "",
|
||||
evaluations: 0,
|
||||
};
|
||||
};
|
||||
|
||||
export const copy_script = (app: Editor) => (from: number, to: number): void => {
|
||||
//@ts-ignore
|
||||
app.universes[app.selected_universe].locals[to] = {
|
||||
...app.universes[app.selected_universe]!.locals[from],
|
||||
};
|
||||
};
|
||||
|
||||
export const copy_universe = (app: Editor) => (from: string, to: string): void => {
|
||||
//@ts-ignore
|
||||
app.universes[to] = { ...app.universes[from], };
|
||||
};
|
||||
|
||||
export const delete_universe = (app: Editor) => (universe: string): void => {
|
||||
if (app.selected_universe === universe) {
|
||||
app.selected_universe = "Default";
|
||||
}
|
||||
delete app.universes[universe];
|
||||
app.settings.saveApplicationToLocalStorage(
|
||||
app.universes,
|
||||
app.settings,
|
||||
);
|
||||
app.updateKnownUniversesView();
|
||||
};
|
||||
|
||||
export const big_bang = (app: Editor) => (): void => {
|
||||
if (confirm("Are you sure you want to delete all universes?")) {
|
||||
app.universes = {
|
||||
...template_universes, // Assuming template_universes is defined elsewhere
|
||||
};
|
||||
app.settings.saveApplicationToLocalStorage(
|
||||
app.universes,
|
||||
app.settings,
|
||||
);
|
||||
}
|
||||
app.selected_universe = "Default";
|
||||
app.updateKnownUniversesView();
|
||||
};
|
||||
@ -1,44 +0,0 @@
|
||||
import { SoundEvent } from "../Classes/SoundEvent";
|
||||
import { SkipEvent } from "../Classes/SkipEvent";
|
||||
import { Editor } from "../main";
|
||||
|
||||
export const sound = (app: Editor) => (sound: string | string[] | null | undefined) => {
|
||||
/**
|
||||
* Creates a sound event if a sound is specified, otherwise returns a skip event.
|
||||
* @param sound - The sound identifier or array of identifiers to play.
|
||||
* @returns SoundEvent if sound is defined, otherwise SkipEvent.
|
||||
*/
|
||||
if (sound) return new SoundEvent(sound, app);
|
||||
else return new SkipEvent();
|
||||
};
|
||||
|
||||
export const snd = sound;
|
||||
|
||||
export const speak = () => (text: string, lang: string = "en-US", voiceIndex: number = 0, rate: number = 1, pitch: number = 1): void => {
|
||||
/**
|
||||
* Speaks the given text using the browser's speech synthesis API.
|
||||
* @param text - The text to speak.
|
||||
* @param lang - The language code (e.g., "en-US").
|
||||
* @param voiceIndex - The index of the voice to use from the speechSynthesis voice list.
|
||||
* @param rate - The rate at which to speak the text.
|
||||
* @param pitch - The pitch at which to speak the text.
|
||||
*/
|
||||
const msg = new SpeechSynthesisUtterance(text);
|
||||
msg.lang = lang;
|
||||
msg.rate = rate;
|
||||
msg.pitch = pitch;
|
||||
|
||||
// Set the voice using a provided index
|
||||
const voices = window.speechSynthesis.getVoices();
|
||||
msg.voice = voices[voiceIndex] || null;
|
||||
|
||||
window.speechSynthesis.speak(msg);
|
||||
|
||||
msg.onend = () => {
|
||||
console.log("Finished speaking:", text);
|
||||
};
|
||||
|
||||
msg.onerror = (event) => {
|
||||
console.error("Speech synthesis error:", event);
|
||||
};
|
||||
};
|
||||
@ -1,215 +0,0 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { UserAPI } from "../API";
|
||||
|
||||
const _euclidean_cycle = (
|
||||
pulses: number,
|
||||
length: number,
|
||||
rotate: number = 0,
|
||||
): boolean[] => {
|
||||
if (pulses == length) return Array.from({ length }, () => true);
|
||||
function startsDescent(list: number[], i: number): boolean {
|
||||
const length = list.length;
|
||||
const nextIndex = (i + 1) % length;
|
||||
return list[i]! > list[nextIndex]!? true : false;
|
||||
}
|
||||
if (pulses >= length) return [true];
|
||||
const resList = Array.from(
|
||||
{ length },
|
||||
(_, i) => (((pulses * (i - 1)) % length) + length) % length,
|
||||
);
|
||||
let cycle = resList.map((_, i) => startsDescent(resList, i));
|
||||
if (rotate != 0) {
|
||||
cycle = cycle.slice(rotate).concat(cycle.slice(0, rotate));
|
||||
}
|
||||
return cycle;
|
||||
}
|
||||
|
||||
export const fullseq = () => (sequence: string, duration: number): boolean | Array<boolean> => {
|
||||
if (sequence.split("").every((c) => c === "x" || c === "o")) {
|
||||
return [...sequence].map((c) => c === "x").beat(duration);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const seq = (app: any) => (expr: string, duration: number = 0.5): boolean => {
|
||||
let len = expr.length * duration;
|
||||
let output: number[] = [];
|
||||
|
||||
for (let i = 1; i <= len + 1; i += duration) {
|
||||
output.push(Math.floor(i * 10) / 10);
|
||||
}
|
||||
output.pop();
|
||||
|
||||
output = output.filter((_, idx) => {
|
||||
const exprIdx = idx % expr.length;
|
||||
return expr[exprIdx] === "x";
|
||||
});
|
||||
|
||||
return oncount(app)(output, len);
|
||||
};
|
||||
|
||||
export const beat = (app: Editor) => (n: number | number[] = 1, nudge: number = 0): boolean => {
|
||||
const nArray = Array.isArray(n) ? n : [n];
|
||||
const results: boolean[] = nArray.map(
|
||||
(value) =>
|
||||
(app.clock.time_position.grain - Math.round(nudge * app.clock.time_position.ppqn)) %
|
||||
Math.round(value * app.clock.time_position.ppqn) === 0,
|
||||
);
|
||||
return results.some((value) => value === true);
|
||||
};
|
||||
|
||||
// export const beat = (app: Editor) => (n: number | number[] = 1, nudge: number = 0): boolean => {
|
||||
// const nArray = !Array.isArray(n) ? [n] : n;
|
||||
// return nArray.some(
|
||||
// (value) =>
|
||||
// !((app.clock.time_position.grain - nudge * app.clock.time_position.ppqn) % Math.floor(value * app.clock.time_position.ppqn))
|
||||
// );
|
||||
// };
|
||||
|
||||
export const bar = (app: Editor) => (n: number | number[] = 1, nudge: number = 0): boolean => {
|
||||
const nArray = Array.isArray(n) ? n : [n];
|
||||
const barLength = app.clock.time_position.num * app.clock.ppqn;
|
||||
const nudgeInPulses = Math.floor(nudge * barLength);
|
||||
const results: boolean[] = nArray.map(
|
||||
(value) =>
|
||||
(app.clock.grain - nudgeInPulses) %
|
||||
Math.floor(value * barLength) === 0,
|
||||
);
|
||||
return results.some((value) => value === true);
|
||||
};
|
||||
|
||||
export const pulse = (app: Editor) => (n: number | number[] = 1, nudge: number = 0): boolean => {
|
||||
const nArray = Array.isArray(n) ? n : [n];
|
||||
const results: boolean[] = nArray.map(
|
||||
(value) => (app.clock.grain - nudge) % value === 0,
|
||||
);
|
||||
return results.some((value) => value === true);
|
||||
};
|
||||
|
||||
export const tick = (app: Editor) => (tick: number | number[], offset: number = 0): boolean => {
|
||||
const nArray = Array.isArray(tick) ? tick : [tick];
|
||||
const results: boolean[] = nArray.map(
|
||||
(value) => app.clock.time_position.tick === value + offset,
|
||||
);
|
||||
return results.some((value) => value === true);
|
||||
};
|
||||
|
||||
export const dur = (app: Editor) => (n: number | number[]): boolean => {
|
||||
let nums: number[] = Array.isArray(n) ? n : [n];
|
||||
return beat(app)(nums.dur(...nums));
|
||||
};
|
||||
|
||||
|
||||
export const flip = (app: Editor) => (chunk: number, ratio: number = 50): boolean => {
|
||||
let realChunk = chunk * 2;
|
||||
const time_pos = app.clock.grain;
|
||||
const full_chunk = Math.floor(realChunk * app.clock.ppqn);
|
||||
const threshold = Math.floor((ratio / 100) * full_chunk);
|
||||
const pos_within_chunk = time_pos % full_chunk;
|
||||
return pos_within_chunk < threshold;
|
||||
};
|
||||
|
||||
export const flipbar = (app: Editor) => (chunk: number = 1): boolean => {
|
||||
let realFlip = chunk;
|
||||
const time_pos = app.clock.time_position.bar;
|
||||
const current_chunk = Math.floor(time_pos / realFlip);
|
||||
return current_chunk % 2 === 0;
|
||||
};
|
||||
|
||||
export const onbar = (app: Editor) => (
|
||||
bars: number[] | number,
|
||||
n: number = app.clock.time_position.num,
|
||||
): boolean => {
|
||||
let current_bar = (app.clock.time_position.bar % n) + 1;
|
||||
return typeof bars === "number"
|
||||
? bars === current_bar
|
||||
: bars.some((b) => b === current_bar);
|
||||
};
|
||||
|
||||
export const onbeat = (api: UserAPI) => (...beat: number[]): boolean => {
|
||||
let final_pulses: boolean[] = [];
|
||||
beat.forEach((b) => {
|
||||
let beatNumber = b % api.nominator() || api.nominator();
|
||||
let integral_part = Math.floor(beatNumber);
|
||||
integral_part = integral_part === 0 ? api.nominator() : integral_part;
|
||||
let decimal_part = Math.floor((beatNumber - integral_part) * api.app.clock.ppqn + 1);
|
||||
if (decimal_part <= 0)
|
||||
decimal_part += api.app.clock.ppqn * api.nominator();
|
||||
final_pulses.push(
|
||||
integral_part === api.cbeat() && api.cpulse() === decimal_part,
|
||||
);
|
||||
});
|
||||
return final_pulses.some((p) => p === true);
|
||||
};
|
||||
|
||||
export const oncount = (app: Editor) => (beats: number[] | number, count: number): boolean => {
|
||||
if (typeof beats === "number") beats = [beats];
|
||||
const origin = app.clock.grain;
|
||||
let final_pulses: boolean[] = [];
|
||||
beats.forEach((b) => {
|
||||
b = b < 1 ? 0 : b - 1;
|
||||
const beatInTicks = Math.ceil(b * app.clock.ppqn);
|
||||
const meterPosition = origin % (app.clock.ppqn * count);
|
||||
final_pulses.push(meterPosition === beatInTicks);
|
||||
});
|
||||
return final_pulses.some((p) => p === true);
|
||||
};
|
||||
|
||||
export const oneuclid = (app: Editor) => (pulses: number, length: number, rotate: number = 0): boolean => {
|
||||
const cycle = _euclidean_cycle(pulses, length, rotate);
|
||||
const beats = cycle.reduce((acc: number[], x: boolean, i: number) => {
|
||||
if (x) acc.push(i + 1);
|
||||
return acc;
|
||||
}, []);
|
||||
return oncount(app)(beats, length);
|
||||
};
|
||||
|
||||
export const euclid = () => (iterator: number, pulses: number, length: number, rotate: number = 0): boolean => {
|
||||
/**
|
||||
* Returns a Euclidean cycle of size length, with n pulses, rotated or not.
|
||||
*/
|
||||
const cycle = _euclidean_cycle(pulses, length, rotate);
|
||||
return cycle && cycle[iterator % length] === true;
|
||||
};
|
||||
export const ec = euclid;
|
||||
|
||||
export const rhythm = (app: Editor) => (div: number, pulses: number, length: number, rotate: number = 0): boolean => {
|
||||
/**
|
||||
* Returns a rhythm based on Euclidean cycle.
|
||||
*/
|
||||
return (
|
||||
beat(app)(div) && _euclidean_cycle(pulses, length, rotate).beat(div)
|
||||
);
|
||||
};
|
||||
export const ry = rhythm;
|
||||
|
||||
export const nrhythm = (app: Editor) => (div: number, pulses: number, length: number, rotate: number = 0): boolean => {
|
||||
/**
|
||||
* Returns a negated rhythm based on Euclidean cycle.
|
||||
*/
|
||||
let rhythm = _euclidean_cycle(pulses, length, rotate).map((n: any) => !n);
|
||||
return (
|
||||
beat(app)(div) && rhythm.beat(div)
|
||||
);
|
||||
};
|
||||
export const nry = nrhythm;
|
||||
|
||||
export const bin = () => (iterator: number, n: number): boolean => {
|
||||
/**
|
||||
* Returns a binary cycle of size n.
|
||||
*/
|
||||
let convert: string = n.toString(2);
|
||||
let tobin: boolean[] = convert.split("").map((x: string) => x === "1");
|
||||
return tobin[iterator % tobin.length] || false;
|
||||
};
|
||||
|
||||
export const binrhythm = (app: Editor) => (div: number, n: number): boolean => {
|
||||
/**
|
||||
* Returns a binary rhythm based on division and binary cycle.
|
||||
*/
|
||||
let convert: string = n.toString(2);
|
||||
let tobin: boolean[] = convert.split("").map((x: string) => x === "1");
|
||||
return beat(app)(div) && tobin.beat(div);
|
||||
};
|
||||
export const bry = binrhythm;
|
||||
@ -1,103 +0,0 @@
|
||||
import { type UserAPI } from "../API";
|
||||
import { type Editor } from "../../main";
|
||||
|
||||
export const time = (api: UserAPI) => (): number => {
|
||||
return api.app.audioContext.currentTime;
|
||||
};
|
||||
|
||||
export const play = (api: UserAPI) => (): void => {
|
||||
api.app.setButtonHighlighting("play", true);
|
||||
api.MidiConnection.sendStartMessage();
|
||||
api.app.clock.start();
|
||||
};
|
||||
|
||||
export const pause = (api: UserAPI) => (): void => {
|
||||
api.app.setButtonHighlighting("pause", true);
|
||||
api.app.clock.pause();
|
||||
};
|
||||
|
||||
export const stop = (api: UserAPI) => (): void => {
|
||||
api.app.setButtonHighlighting("stop", true);
|
||||
api.app.clock.stop();
|
||||
};
|
||||
|
||||
export const silence = (api: UserAPI) => (): void => {
|
||||
return stop(api)();
|
||||
};
|
||||
|
||||
export const tempo = (app: Editor) => (n?: number): number => {
|
||||
/**
|
||||
* Sets or returns the current bpm.
|
||||
*/
|
||||
if (n === undefined) return app.clock.bpm;
|
||||
|
||||
if (n >= 1 && n <= 500) {
|
||||
app.clock.bpm = n;
|
||||
} else {
|
||||
console.error("BPM out of acceptable range (1-500).");
|
||||
}
|
||||
return n;
|
||||
};
|
||||
|
||||
export const ppqn = (app: Editor) => (n?: number): number => {
|
||||
/**
|
||||
* Sets or returns the number of pulses per quarter note.
|
||||
*/
|
||||
if (n === undefined) return app.clock.ppqn;
|
||||
|
||||
if (n >= 1) {
|
||||
app.clock.ppqn = n;
|
||||
} else {
|
||||
console.error("Pulses per quarter note must be at least 1.");
|
||||
}
|
||||
return n;
|
||||
};
|
||||
|
||||
export const time_signature = (app: Editor) => (numerator: number, denominator: number): void => {
|
||||
/**
|
||||
* Sets the time signature.
|
||||
*/
|
||||
if (numerator < 1 || denominator < 1) {
|
||||
console.error("Time signature values must be at least 1.");
|
||||
} else {
|
||||
app.clock.setSignature(numerator, denominator);
|
||||
}
|
||||
};
|
||||
|
||||
export const cbar = (app: Editor) => (): number => {
|
||||
return app.clock.time_position.bar + 1;
|
||||
};
|
||||
|
||||
export const ctick = (app: Editor) => (): number => {
|
||||
return app.clock.grain + 1;
|
||||
};
|
||||
|
||||
export const cpulse = (app: Editor) => (): number => {
|
||||
return app.clock.time_position.tick + 1;
|
||||
};
|
||||
|
||||
export const cbeat = (app: Editor) => (): number => {
|
||||
return app.clock.time_position.beat + 1;
|
||||
};
|
||||
|
||||
export const ebeat = (app: Editor) => (): number => {
|
||||
return app.clock.beats_since_origin + 1;
|
||||
};
|
||||
|
||||
export const epulse = (app: Editor) => (): number => {
|
||||
return app.clock.grain + 1;
|
||||
};
|
||||
|
||||
export const nominator = (app: Editor) => (): number => {
|
||||
return app.clock.time_position.num;
|
||||
};
|
||||
|
||||
export const meter = (app: Editor) => (): number => {
|
||||
return app.clock.time_position.den;
|
||||
};
|
||||
|
||||
export const denominator = meter;
|
||||
|
||||
export const pulsesForBar = (app: Editor) => (): number => {
|
||||
return (app.clock.bpm * app.clock.ppqn * nominator(app)()) / 60;
|
||||
};
|
||||
@ -1,18 +0,0 @@
|
||||
import { Editor } from "../../main";
|
||||
|
||||
export const warp = (app: Editor) => (n: number): void => {
|
||||
/**
|
||||
* Time-warp the clock by using the tick you wish to jump to.
|
||||
*/
|
||||
app.clock.time_position.tick = n;
|
||||
app.clock.time_position = app.clock.convertTicksToTimeposition(n);
|
||||
};
|
||||
|
||||
export const beat_warp = (app: Editor) => (beat: number): void => {
|
||||
/**
|
||||
* Time-warp the clock by using the tick you wish to jump to.
|
||||
*/
|
||||
const ticks = beat * app.clock.ppqn;
|
||||
app.clock.time_position.tick = ticks;
|
||||
app.clock.time_position = app.clock.convertTicksToTimeposition(ticks);
|
||||
};
|
||||
@ -1,72 +0,0 @@
|
||||
import { InputOptions, Player } from "../Classes/ZPlayer";
|
||||
import { UserAPI } from "./API";
|
||||
import { generateCacheKey, removePatternFromCache } from "./Cache"
|
||||
|
||||
export const z = (api: UserAPI) => (input: string | Generator<number>, options: InputOptions = {}, id: number | string = ""): Player => {
|
||||
const zid = "z" + id.toString();
|
||||
const key = id === "" ? generateCacheKey()(input, options) : zid;
|
||||
|
||||
const validSyntax = typeof input === "string" && !api.invalidPatterns[input]
|
||||
|
||||
let player;
|
||||
let replace = false;
|
||||
|
||||
if (api.patternCache.has(key)) {
|
||||
player = api.patternCache.get(key) as Player;
|
||||
|
||||
if (typeof input === "string" &&
|
||||
player.input !== input &&
|
||||
(player.atTheBeginning() || api.forceEvaluator)) {
|
||||
replace = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ((typeof input !== "string" || validSyntax) && (!player || replace)) {
|
||||
if (typeof input === "string" && player && api.forceEvaluator) {
|
||||
if (!player.updatePattern(input, options)) {
|
||||
api.logOnce(`Invalid syntax: ${input}`);
|
||||
};
|
||||
api.forceEvaluator = false;
|
||||
} else {
|
||||
const newPlayer = player ? new Player(input, options, api.app, zid, player.nextEndTime()) : new Player(input, options, api.app, zid);
|
||||
if (newPlayer.isValid()) {
|
||||
player = newPlayer;
|
||||
api.patternCache.set(key, player);
|
||||
} else if (typeof input === "string") {
|
||||
api.invalidPatterns[input] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (player) {
|
||||
if (player.atTheBeginning()) {
|
||||
if (typeof input === "string" && !validSyntax) api.log(`Invalid syntax: ${input}`);
|
||||
}
|
||||
|
||||
if (player.ziffers.generator && player.ziffers.generatorDone) {
|
||||
removePatternFromCache(api)(key);
|
||||
}
|
||||
|
||||
if (typeof id === "number") player.zid = zid;
|
||||
|
||||
player.updateLastCallTime();
|
||||
|
||||
if (id !== "" && zid !== "z0") {
|
||||
// Sync named patterns to z0 by default
|
||||
player.sync("z0", false);
|
||||
}
|
||||
|
||||
return player;
|
||||
} else {
|
||||
throw new Error(`Invalid syntax: ${input}`);
|
||||
}
|
||||
};
|
||||
|
||||
// Generating numbered functions dynamically
|
||||
export const generateZFunctions = (api: UserAPI) => {
|
||||
const zFunctions: { [key: string]: (input: string, opts: InputOptions) => Player } = {};
|
||||
for (let i = 0; i <= 16; i++) {
|
||||
zFunctions[`z${i}`] = (input: string, opts: InputOptions = {}) => z(api)(input, opts, i);
|
||||
}
|
||||
return zFunctions;
|
||||
};
|
||||
259
src/Clock.ts
Normal file
@ -0,0 +1,259 @@
|
||||
// @ts-ignore
|
||||
import { TransportNode } from "./TransportNode";
|
||||
import TransportProcessor from "./TransportProcessor?worker&url";
|
||||
import { Editor } from "./main";
|
||||
|
||||
export interface TimePosition {
|
||||
/**
|
||||
* A position in time.
|
||||
*
|
||||
* @param bar - The bar number
|
||||
* @param beat - The beat number
|
||||
* @param pulse - The pulse number
|
||||
*/
|
||||
bar: number;
|
||||
beat: number;
|
||||
pulse: number;
|
||||
}
|
||||
|
||||
export class Clock {
|
||||
/**
|
||||
* The Clock Class is responsible for keeping track of the current time.
|
||||
* It is also responsible for starting and stopping the Clock TransportNode.
|
||||
*
|
||||
* @param app - The main application instance
|
||||
* @param ctx - The current AudioContext used by app
|
||||
* @param transportNode - The TransportNode helper
|
||||
* @param bpm - The current beats per minute value
|
||||
* @param time_signature - The time signature
|
||||
* @param time_position - The current time position
|
||||
* @param ppqn - The pulses per quarter note
|
||||
* @param tick - The current tick since origin
|
||||
* @param running - Is the clock running?
|
||||
* @param lastPauseTime - The last time the clock was paused
|
||||
* @param lastPlayPressTime - The last time the clock was started
|
||||
* @param totalPauseTime - The total time the clock has been paused / stopped
|
||||
*/
|
||||
|
||||
ctx: AudioContext;
|
||||
logicalTime: number;
|
||||
transportNode: TransportNode | null;
|
||||
private _bpm: number;
|
||||
time_signature: number[];
|
||||
time_position: TimePosition;
|
||||
private _ppqn: number;
|
||||
tick: number;
|
||||
running: boolean;
|
||||
lastPauseTime: number;
|
||||
lastPlayPressTime: number;
|
||||
totalPauseTime: number;
|
||||
|
||||
constructor(
|
||||
public app: Editor,
|
||||
ctx: AudioContext,
|
||||
) {
|
||||
this.time_position = { bar: 0, beat: 0, pulse: 0 };
|
||||
this.time_signature = [4, 4];
|
||||
this.logicalTime = 0;
|
||||
this.tick = 0;
|
||||
this._bpm = 120;
|
||||
this._ppqn = 48;
|
||||
this.transportNode = null;
|
||||
this.ctx = ctx;
|
||||
this.running = true;
|
||||
this.lastPauseTime = 0;
|
||||
this.lastPlayPressTime = 0;
|
||||
this.totalPauseTime = 0;
|
||||
ctx.audioWorklet
|
||||
.addModule(TransportProcessor)
|
||||
.then((e) => {
|
||||
this.transportNode = new TransportNode(ctx, {}, this.app);
|
||||
this.transportNode.connect(ctx.destination);
|
||||
return e;
|
||||
})
|
||||
.catch((e) => {
|
||||
console.log("Error loading TransportProcessor.js:", e);
|
||||
});
|
||||
}
|
||||
|
||||
convertTicksToTimeposition(ticks: number): TimePosition {
|
||||
/**
|
||||
* Converts ticks to a TimePosition object.
|
||||
* @param ticks The number of ticks to convert.
|
||||
* @returns The TimePosition object representing the converted ticks.
|
||||
*/
|
||||
|
||||
const beatsPerBar = this.app.clock.time_signature[0];
|
||||
const ppqnPosition = ticks % this.app.clock.ppqn;
|
||||
const beatNumber = Math.floor(ticks / this.app.clock.ppqn);
|
||||
const barNumber = Math.floor(beatNumber / beatsPerBar);
|
||||
const beatWithinBar = Math.floor(beatNumber % beatsPerBar);
|
||||
return { bar: barNumber, beat: beatWithinBar, pulse: ppqnPosition };
|
||||
}
|
||||
|
||||
get ticks_before_new_bar(): number {
|
||||
/**
|
||||
* This function returns the number of ticks separating the current moment
|
||||
* from the beginning of the next bar.
|
||||
*
|
||||
* @returns number of ticks until next bar
|
||||
*/
|
||||
const ticskMissingFromBeat = this.ppqn - this.time_position.pulse;
|
||||
const beatsMissingFromBar = this.beats_per_bar - this.time_position.beat;
|
||||
return beatsMissingFromBar * this.ppqn + ticskMissingFromBeat;
|
||||
}
|
||||
|
||||
get next_beat_in_ticks(): number {
|
||||
/**
|
||||
* This function returns the number of ticks separating the current moment
|
||||
* from the beginning of the next beat.
|
||||
*
|
||||
* @returns number of ticks until next beat
|
||||
*/
|
||||
return this.app.clock.pulses_since_origin + this.time_position.pulse;
|
||||
}
|
||||
|
||||
get beats_per_bar(): number {
|
||||
/**
|
||||
* Returns the number of beats per bar.
|
||||
*/
|
||||
return this.time_signature[0];
|
||||
}
|
||||
|
||||
get beats_since_origin(): number {
|
||||
/**
|
||||
* Returns the number of beats since the origin.
|
||||
*
|
||||
* @returns number of beats since origin
|
||||
*/
|
||||
return Math.floor(this.tick / this.ppqn);
|
||||
}
|
||||
|
||||
get pulses_since_origin(): number {
|
||||
/**
|
||||
* Returns the number of pulses since the origin.
|
||||
*
|
||||
* @returns number of pulses since origin
|
||||
*/
|
||||
return this.tick;
|
||||
}
|
||||
|
||||
get pulse_duration(): number {
|
||||
/**
|
||||
* Returns the duration of a pulse in seconds.
|
||||
*/
|
||||
return 60 / this.bpm / this.ppqn;
|
||||
}
|
||||
|
||||
public pulse_duration_at_bpm(bpm: number = this.bpm): number {
|
||||
/**
|
||||
* Returns the duration of a pulse in seconds at a specific bpm.
|
||||
*/
|
||||
return 60 / bpm / this.ppqn;
|
||||
}
|
||||
|
||||
get bpm(): number {
|
||||
return this._bpm;
|
||||
}
|
||||
|
||||
set nudge(nudge: number) {
|
||||
this.transportNode?.setNudge(nudge);
|
||||
}
|
||||
|
||||
set bpm(bpm: number) {
|
||||
if (bpm > 0 && this._bpm !== bpm) {
|
||||
this.transportNode?.setBPM(bpm);
|
||||
this._bpm = bpm;
|
||||
this.logicalTime = this.realTime;
|
||||
}
|
||||
}
|
||||
|
||||
get ppqn(): number {
|
||||
return this._ppqn;
|
||||
}
|
||||
|
||||
get realTime(): number {
|
||||
return this.app.audioContext.currentTime - this.totalPauseTime;
|
||||
}
|
||||
|
||||
get deviation(): number {
|
||||
return Math.abs(this.logicalTime - this.realTime);
|
||||
}
|
||||
|
||||
set ppqn(ppqn: number) {
|
||||
if (ppqn > 0 && this._ppqn !== ppqn) {
|
||||
this._ppqn = ppqn;
|
||||
this.transportNode?.setPPQN(ppqn);
|
||||
this.logicalTime = this.realTime;
|
||||
}
|
||||
}
|
||||
|
||||
public incrementTick(bpm: number) {
|
||||
this.tick++;
|
||||
this.logicalTime += this.pulse_duration_at_bpm(bpm);
|
||||
}
|
||||
|
||||
public nextTickFrom(time: number, nudge: number): number {
|
||||
/**
|
||||
* Compute the time remaining before the next clock tick.
|
||||
* @param time - audio context currentTime
|
||||
* @param nudge - nudge in the future (in seconds)
|
||||
* @returns remainingTime
|
||||
*/
|
||||
const pulseDuration = this.pulse_duration;
|
||||
const nudgedTime = time + nudge;
|
||||
const nextTickTime = Math.ceil(nudgedTime / pulseDuration) * pulseDuration;
|
||||
const remainingTime = nextTickTime - nudgedTime;
|
||||
|
||||
return remainingTime;
|
||||
}
|
||||
|
||||
public convertPulseToSecond(n: number): number {
|
||||
/**
|
||||
* Converts a pulse to a second.
|
||||
*/
|
||||
return n * this.pulse_duration;
|
||||
}
|
||||
|
||||
public start(): void {
|
||||
/**
|
||||
* Starts the TransportNode (starts the clock).
|
||||
*
|
||||
* @remark also sends a MIDI message if a port is declared
|
||||
*/
|
||||
this.app.audioContext.resume();
|
||||
this.running = true;
|
||||
this.app.api.MidiConnection.sendStartMessage();
|
||||
this.lastPlayPressTime = this.app.audioContext.currentTime;
|
||||
this.totalPauseTime += this.lastPlayPressTime - this.lastPauseTime;
|
||||
this.transportNode?.start();
|
||||
}
|
||||
|
||||
public pause(): void {
|
||||
/**
|
||||
* Pauses the TransportNode (pauses the clock).
|
||||
*
|
||||
* @remark also sends a MIDI message if a port is declared
|
||||
*/
|
||||
this.running = false;
|
||||
this.transportNode?.pause();
|
||||
this.app.api.MidiConnection.sendStopMessage();
|
||||
this.lastPauseTime = this.app.audioContext.currentTime;
|
||||
this.logicalTime = this.realTime;
|
||||
}
|
||||
|
||||
public stop(): void {
|
||||
/**
|
||||
* Stops the TransportNode (stops the clock).
|
||||
*
|
||||
* @remark also sends a MIDI message if a port is declared
|
||||
*/
|
||||
this.running = false;
|
||||
this.tick = 0;
|
||||
this.lastPauseTime = this.app.audioContext.currentTime;
|
||||
this.logicalTime = this.realTime;
|
||||
this.time_position = { bar: 0, beat: 0, pulse: 0 };
|
||||
this.app.api.MidiConnection.sendStopMessage();
|
||||
this.transportNode?.stop();
|
||||
}
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
export { introduction } from './welcome';
|
||||
export { atelier } from './atelier';
|
||||
export { software_interface } from './interface';
|
||||
export { shortcuts } from './keyboard';
|
||||
export { code } from './code';
|
||||
export { mouse } from './mouse';
|
||||
export { interaction } from './interaction';
|
||||
@ -1,6 +0,0 @@
|
||||
export { amplitude } from './amplitude';
|
||||
export { effects } from './effects';
|
||||
export { sampler } from './sampler';
|
||||
export { synths } from './synths';
|
||||
export { filters } from './filters';
|
||||
export { audio_basics } from './audio_basics';
|
||||
@ -1,3 +0,0 @@
|
||||
export { loading_samples } from './loading_samples';
|
||||
export { sample_banks } from './sample_banks';
|
||||
export { sample_list } from './sample_list';
|
||||
@ -1,5 +0,0 @@
|
||||
export { about } from './about';
|
||||
export { bonus } from './bonus';
|
||||
export { oscilloscope } from './oscilloscope';
|
||||
export { synchronisation } from './synchronisation';
|
||||
export { visualization } from './visualization.ts';
|
||||
@ -1,7 +0,0 @@
|
||||
export { chaining } from './chaining';
|
||||
export { functions } from './functions';
|
||||
export { generators } from './generators';
|
||||
export { lfos } from './lfos';
|
||||
export { patterns } from './patterns';
|
||||
export { probabilities } from './probabilities';
|
||||
export { variables } from './variables';
|
||||
@ -1,6 +0,0 @@
|
||||
export { ziffers_basics } from './ziffers_basics';
|
||||
export { ziffers_scales } from './ziffers_scales';
|
||||
export { ziffers_rhythm } from './ziffers_rhythm';
|
||||
export { ziffers_algorithmic } from './ziffers_algorithmic';
|
||||
export { ziffers_tonnetz } from './ziffers_tonnetz';
|
||||
export { ziffers_syncing } from './ziffers_syncing';
|
||||
@ -1,37 +1,53 @@
|
||||
import { Editor } from "../main";
|
||||
import { introduction, atelier, software_interface, shortcuts, code, mouse, interaction } from "./basics";
|
||||
import { amplitude, effects, sampler, synths, filters, audio_basics } from "./learning/audio_engine";
|
||||
import { lfos, functions, generators, variables, probabilities } from './patterns';
|
||||
import { ziffers_basics, ziffers_scales, ziffers_rhythm, ziffers_algorithmic, ziffers_tonnetz, ziffers_syncing } from "./patterns/ziffers";
|
||||
import { loading_samples } from "./learning/samples/loading_samples";
|
||||
import { sample_banks } from "./learning/samples/sample_banks";
|
||||
import { sample_list } from "./learning/samples/sample_list";
|
||||
import { oscilloscope } from "./more/oscilloscope";
|
||||
import { synchronisation } from "./more/synchronisation";
|
||||
import { about } from "./more/about";
|
||||
import { bonus } from "./more/bonus";
|
||||
import { visualization } from "./more/visualization";
|
||||
import { chaining } from "./patterns/chaining";
|
||||
import { time } from "./learning/time/time";
|
||||
import { linear_time } from "./learning/time/linear_time";
|
||||
import { cyclical_time } from "./learning/time/cyclical_time";
|
||||
import { long_forms } from "./learning/time/long_forms";
|
||||
import { midi } from "./learning/midi";
|
||||
import { osc } from "./learning/osc";
|
||||
import { patterns } from "./patterns/patterns";
|
||||
import { type Editor } from "./main";
|
||||
// Basics
|
||||
import { introduction } from "./documentation/basics/welcome";
|
||||
import { atelier } from "./documentation/basics/atelier";
|
||||
import { loading_samples } from "./documentation/learning/samples/loading_samples";
|
||||
import { amplitude } from "./documentation/learning/audio_engine/amplitude";
|
||||
import { effects } from "./documentation/learning/audio_engine/effects";
|
||||
import { sampler } from "./documentation/learning/audio_engine/sampler";
|
||||
import { sample_banks } from "./documentation/learning/samples/sample_banks";
|
||||
import { audio_basics } from "./documentation/learning/audio_engine/audio_basics";
|
||||
import { sample_list } from "./documentation/learning/samples/sample_list";
|
||||
import { software_interface } from "./documentation/basics/interface";
|
||||
import { shortcuts } from "./documentation/basics/keyboard";
|
||||
import { code } from "./documentation/basics/code";
|
||||
import { mouse } from "./documentation/basics/mouse";
|
||||
// More
|
||||
import { oscilloscope } from "./documentation/more/oscilloscope";
|
||||
import { synchronisation } from "./documentation/more/synchronisation";
|
||||
import { about } from "./documentation/more/about";
|
||||
import { bonus } from "./documentation/more/bonus";
|
||||
import { visualization } from "./documentation/more/visualization";
|
||||
import { chaining } from "./documentation/patterns/chaining";
|
||||
import { interaction } from "./documentation/basics/interaction";
|
||||
import { time } from "./documentation/learning/time/time";
|
||||
import { linear_time } from "./documentation/learning/time/linear_time";
|
||||
import { cyclical_time } from "./documentation/learning/time/cyclical_time";
|
||||
import { long_forms } from "./documentation/learning/time/long_forms";
|
||||
import { midi } from "./documentation/learning/midi";
|
||||
import { osc } from "./documentation/learning/osc";
|
||||
import { patterns } from "./documentation/patterns/patterns";
|
||||
import { functions } from "./documentation/patterns/functions";
|
||||
import { generators } from "./documentation/patterns/generators";
|
||||
import { variables } from "./documentation/patterns/variables";
|
||||
import { probabilities } from "./documentation/patterns/probabilities";
|
||||
import { lfos } from "./documentation/patterns/lfos";
|
||||
import { ziffers_basics } from "./documentation/patterns/ziffers/ziffers_basics";
|
||||
import { ziffers_scales } from "./documentation/patterns/ziffers/ziffers_scales";
|
||||
import { ziffers_rhythm } from "./documentation/patterns/ziffers/ziffers_rhythm";
|
||||
import { ziffers_algorithmic } from "./documentation/patterns/ziffers/ziffers_algorithmic";
|
||||
import { ziffers_tonnetz } from "./documentation/patterns/ziffers/ziffers_tonnetz";
|
||||
import { ziffers_syncing } from "./documentation/patterns/ziffers/ziffers_syncing";
|
||||
import { synths } from "./documentation/learning/audio_engine/synths";
|
||||
// Setting up the Markdown converter with syntax highlighting
|
||||
import showdown from "showdown";
|
||||
import showdownHighlight from "showdown-highlight";
|
||||
import "highlight.js/styles/atom-one-dark-reasonable.min.css";
|
||||
import { createDocumentationStyle } from "../DOM/DomElements";
|
||||
import { createDocumentationStyle } from "./DomElements";
|
||||
import { filters } from "./documentation/learning/audio_engine/filters";
|
||||
showdown.setFlavor("github");
|
||||
|
||||
type StyleBinding = {
|
||||
type: string;
|
||||
regex: RegExp;
|
||||
replace: (match: string, p1: string) => string;
|
||||
};
|
||||
|
||||
export const key_shortcut = (shortcut: string): string => {
|
||||
return `<kbd class="lg:px-2 lg:py-1.5 px-1 py-1 lg:text-sm text-xs font-semibold text-brightwhite bg-brightblack border border-black rounded-lg">${shortcut}</kbd>`;
|
||||
};
|
||||
@ -54,7 +70,8 @@ export const makeExampleFactory = (application: Editor): Function => {
|
||||
<button class="py-1 text-base px-4 hover:bg-brightmagenta bg-magenta text-selection_foreground inline-block" onclick="navigator.clipboard.writeText(app.api.codeExamples['${codeId}'])">📎 Copy</button>
|
||||
</summary>
|
||||
<pre><code class="hljs language-javascript">${code.trim()}</code></pre>
|
||||
</details> `;
|
||||
</details>
|
||||
`;
|
||||
};
|
||||
return make_example;
|
||||
};
|
||||
@ -153,68 +170,34 @@ export const documentation_factory = (application: Editor) => {
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
|
||||
export const showDocumentation = (app: Editor): void => {
|
||||
const toggleElementVisibility = (elementId: string, shouldHide: boolean): void => {
|
||||
const element = document.getElementById(elementId);
|
||||
if (element) {
|
||||
element.classList.toggle("hidden", shouldHide);
|
||||
}
|
||||
};
|
||||
|
||||
const applyStyleBindings = (style: Record<string, string>, updateContent: (bindings: StyleBinding[]) => void): void => {
|
||||
const bindings: StyleBinding[] = Object.keys(style).map((key) => ({
|
||||
type: "output",
|
||||
regex: new RegExp(`<${key}([^>]*)>`, "g"),
|
||||
replace: (_, p1) => `<${key} class="${style[key]}" ${p1}>`
|
||||
}));
|
||||
updateContent(bindings);
|
||||
};
|
||||
|
||||
const appHidden = document.getElementById("app")?.classList.contains("hidden");
|
||||
if (appHidden) {
|
||||
toggleElementVisibility("app", false);
|
||||
toggleElementVisibility("documentation", true);
|
||||
export const showDocumentation = (app: Editor) => {
|
||||
/**
|
||||
* Shows or hides the documentation based on the current state of the app.
|
||||
* @param app - The Editor instance.
|
||||
*/
|
||||
if (document.getElementById("app")?.classList.contains("hidden")) {
|
||||
document.getElementById("app")?.classList.remove("hidden");
|
||||
document.getElementById("documentation")?.classList.add("hidden");
|
||||
app.exampleIsPlaying = false;
|
||||
} else {
|
||||
toggleElementVisibility("app", true);
|
||||
toggleElementVisibility("documentation", false);
|
||||
const style = createDocumentationStyle(app);
|
||||
applyStyleBindings(style, (bindings: StyleBinding[]) => updateDocumentationContent(app, bindings));
|
||||
document.getElementById("app")?.classList.add("hidden");
|
||||
document.getElementById("documentation")?.classList.remove("hidden");
|
||||
// Load and convert Markdown content from the documentation file
|
||||
let style = createDocumentationStyle(app);
|
||||
|
||||
function update_and_assign(callback: Function) {
|
||||
let bindings = Object.keys(style).map((key) => ({
|
||||
type: "output",
|
||||
regex: new RegExp(`<${key}([^>]*)>`, "g"),
|
||||
//@ts-ignore
|
||||
replace: (match, p1) => `<${key} class="${style[key]}" ${p1}>`,
|
||||
}));
|
||||
callback(bindings)
|
||||
}
|
||||
update_and_assign((e: Object) => updateDocumentationContent(app, e));
|
||||
}
|
||||
|
||||
// Reset the URL to the base URL
|
||||
window.history.pushState({}, '', '/');
|
||||
};
|
||||
|
||||
// export const showDocumentation = (app: Editor) => {
|
||||
// /**
|
||||
// * Shows or hides the documentation based on the current state of the app.
|
||||
// * @param app - The Editor instance.
|
||||
// */
|
||||
// if (document.getElementById("app")?.classList.contains("hidden")) {
|
||||
// document.getElementById("app")?.classList.remove("hidden");
|
||||
// document.getElementById("documentation")?.classList.add("hidden");
|
||||
// app.exampleIsPlaying = false;
|
||||
// } else {
|
||||
// document.getElementById("app")?.classList.add("hidden");
|
||||
// document.getElementById("documentation")?.classList.remove("hidden");
|
||||
// // Load and convert Markdown content from the documentation file
|
||||
// let style = createDocumentationStyle(app);
|
||||
// function update_and_assign(callback: Function) {
|
||||
// let bindings = Object.keys(style).map((key) => ({
|
||||
// type: "output",
|
||||
// regex: new RegExp(`<${key}([^>]*)>`, "g"),
|
||||
// //@ts-ignore
|
||||
// replace: (match, p1) => `<${key} class="${style[key]}" ${p1}>`,
|
||||
// }));
|
||||
// callback(bindings)
|
||||
// }
|
||||
// update_and_assign((e: Object) => updateDocumentationContent(app, e));
|
||||
// }
|
||||
// };
|
||||
|
||||
export const hideDocumentation = () => {
|
||||
/**
|
||||
* Hides the documentation section and shows the main application.
|
||||
@ -249,7 +232,7 @@ export const updateDocumentationContent = (app: Editor, bindings: any) => {
|
||||
|
||||
function _update_and_assign(callback: Function) {
|
||||
const converted_markdown = converter.makeHtml(
|
||||
app.docs[app.currentDocumentationPane]!,
|
||||
app.docs[app.currentDocumentationPane],
|
||||
);
|
||||
callback(converted_markdown)
|
||||
}
|
||||
@ -1,7 +1,19 @@
|
||||
import { type Editor } from "../main";
|
||||
import { type Editor } from "./main";
|
||||
|
||||
export type ElementMap = {
|
||||
[key: string]:
|
||||
| HTMLElement
|
||||
| HTMLButtonElement
|
||||
| HTMLDivElement
|
||||
| HTMLInputElement
|
||||
| HTMLSelectElement
|
||||
| HTMLCanvasElement
|
||||
| HTMLFormElement
|
||||
| HTMLInputElement;
|
||||
};
|
||||
|
||||
export const singleElements = {
|
||||
logo: "topos_logo",
|
||||
topos_logo: "topos-logo",
|
||||
fill_viewer: "fillviewer",
|
||||
load_universe_button: "load-universe-button",
|
||||
download_universe_button: "download-universes",
|
||||
@ -29,12 +41,12 @@ export const singleElements = {
|
||||
line_numbers_checkbox: "show-line-numbers",
|
||||
time_position_checkbox: "show-time-position",
|
||||
tips_checkbox: "show-tips",
|
||||
transport_viewer: "transport_viewer",
|
||||
completion_checkbox: "show-completions",
|
||||
midi_clock_checkbox: "send-midi-clock",
|
||||
midi_channels_scripts: "midi-channels-scripts",
|
||||
midi_clock_ppqn: "midi-clock-ppqn-input",
|
||||
theme_selector: "theme-selector",
|
||||
theme_previewer: "theme-previewer",
|
||||
load_demo_songs: "load-demo-songs",
|
||||
normal_mode_button: "normal-mode",
|
||||
vim_mode_button: "vim-mode",
|
||||
@ -44,26 +56,14 @@ export const singleElements = {
|
||||
error_line: "error_line",
|
||||
hydra_canvas: "hydra-bg",
|
||||
feedback: "feedback",
|
||||
drawings: "drawings",
|
||||
scope: "scope",
|
||||
play_button: "play-button",
|
||||
play_label: "play-label",
|
||||
stop_button: "stop-button",
|
||||
play_icon: "play-icon",
|
||||
pause_icon: "pause-icon",
|
||||
} as const;
|
||||
};
|
||||
|
||||
export type SingleElementsKeys = keyof typeof singleElements;
|
||||
|
||||
export type ElementMap = {
|
||||
[K in SingleElementsKeys]:
|
||||
| HTMLElement
|
||||
| HTMLButtonElement
|
||||
| HTMLDivElement
|
||||
| HTMLInputElement
|
||||
| HTMLSelectElement
|
||||
| HTMLCanvasElement
|
||||
| HTMLFormElement
|
||||
| HTMLInputElement;
|
||||
export const buttonGroups = {
|
||||
play_buttons: ["play-button-1"],
|
||||
stop_buttons: ["stop-button-1"],
|
||||
clear_buttons: ["clear-button-1"],
|
||||
};
|
||||
|
||||
//@ts-ignore
|
||||
@ -28,10 +28,11 @@ import {
|
||||
} from "@codemirror/autocomplete";
|
||||
import { lintKeymap } from "@codemirror/lint";
|
||||
import { Compartment } from "@codemirror/state";
|
||||
import { Editor } from "../main";
|
||||
import { Editor } from "./main";
|
||||
import { EditorView } from "codemirror";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { inlineHoveringTips, toposCompletions, soundCompletions } from "../Docs/inlineHelp";
|
||||
import { inlineHoveringTips } from "./documentation/inlineHelp";
|
||||
import { toposCompletions, soundCompletions } from "./documentation/inlineHelp";
|
||||
import { javascriptLanguage } from "@codemirror/lang-javascript";
|
||||
|
||||
export const getCodeMirrorTheme = (theme: { [key: string]: string }): Extension => {
|
||||
@ -65,29 +66,29 @@ export const getCodeMirrorTheme = (theme: { [key: string]: string }): Extension
|
||||
selection_background = theme["selection_background"];
|
||||
const toposTheme = EditorView.theme({
|
||||
"&": {
|
||||
color: background || "",
|
||||
color: background,
|
||||
backgroundColor: "transparent",
|
||||
fontSize: "24px",
|
||||
fontFamily: "IBM Plex Mono",
|
||||
},
|
||||
".cm-content": {
|
||||
caretColor: cursor || '',
|
||||
caretColor: cursor,
|
||||
fontFamily: "IBM Plex Mono",
|
||||
},
|
||||
".cm-line": {
|
||||
color: `${brightwhite}`,
|
||||
},
|
||||
".cm-cursor, .cm-dropCursor": {
|
||||
borderLeftColor: cursor || 'white',
|
||||
borderLeftColor: cursor,
|
||||
},
|
||||
"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":
|
||||
{
|
||||
backgroundColor: brightwhite || 'black',
|
||||
backgroundColor: brightwhite,
|
||||
border: `1px solid ${brightwhite}`,
|
||||
},
|
||||
".cm-panels": {
|
||||
backgroundColor: selection_background || 'gray',
|
||||
color: red || '',
|
||||
backgroundColor: selection_background,
|
||||
color: red,
|
||||
},
|
||||
".cm-panels.cm-panels-top": { borderBottom: "2px solid black" },
|
||||
".cm-panels.cm-panels-bottom": { borderTop: "2px solid black" },
|
||||
@ -96,30 +97,30 @@ export const getCodeMirrorTheme = (theme: { [key: string]: string }): Extension
|
||||
outline: `1px solid ${magenta}`,
|
||||
},
|
||||
".cm-searchMatch.cm-searchMatch-selected": {
|
||||
backgroundColor: red || '',
|
||||
backgroundColor: red,
|
||||
},
|
||||
".cm-activeLine": {
|
||||
backgroundColor: `rgba(${(parseInt(selection_background!.slice(1, 3), 16))}, ${(parseInt(selection_background!.slice(3, 5), 16))}, ${(parseInt(selection_background!.slice(5, 7), 16))}, 0.25)`,
|
||||
backgroundColor: `rgba(${(parseInt(selection_background.slice(1, 3), 16))}, ${(parseInt(selection_background.slice(3, 5), 16))}, ${(parseInt(selection_background.slice(5, 7), 16))}, 0.25)`,
|
||||
},
|
||||
".cm-selectionMatch": {
|
||||
backgroundColor: `rgba(${(parseInt(selection_background!.slice(1, 3), 16))}, ${(parseInt(selection_background!.slice(3, 5), 16))}, ${(parseInt(selection_background!.slice(5, 7), 16))}, 0.25)`,
|
||||
backgroundColor: `rgba(${(parseInt(selection_background.slice(1, 3), 16))}, ${(parseInt(selection_background.slice(3, 5), 16))}, ${(parseInt(selection_background.slice(5, 7), 16))}, 0.25)`,
|
||||
outline: `1px solid ${brightwhite}`,
|
||||
},
|
||||
"&.cm-focused .cm-matchingBracket": {
|
||||
color: `rgba(${(parseInt(selection_background!.slice(1, 3), 16))}, ${(parseInt(selection_background!.slice(3, 5), 16))}, ${(parseInt(selection_background!.slice(5, 7), 16))}, 0.25)`,
|
||||
color: `rgba(${(parseInt(selection_background.slice(1, 3), 16))}, ${(parseInt(selection_background.slice(3, 5), 16))}, ${(parseInt(selection_background.slice(5, 7), 16))}, 0.25)`,
|
||||
},
|
||||
"&.cm-focused .cm-nonmatchingBracket": {
|
||||
color: yellow || '',
|
||||
color: yellow,
|
||||
},
|
||||
|
||||
".cm-gutters": {
|
||||
//backgroundColor: base00,
|
||||
backgroundColor: "transparent",
|
||||
color: foreground || '',
|
||||
color: foreground,
|
||||
},
|
||||
".cm-activeLineGutter": {
|
||||
backgroundColor: selection_background || '',
|
||||
color: selection_foreground || '',
|
||||
backgroundColor: selection_background,
|
||||
color: selection_foreground,
|
||||
},
|
||||
|
||||
".cm-foldPlaceholder": {
|
||||
@ -128,17 +129,17 @@ export const getCodeMirrorTheme = (theme: { [key: string]: string }): Extension
|
||||
},
|
||||
".cm-tooltip": {
|
||||
border: "none",
|
||||
backgroundColor: background || '',
|
||||
backgroundColor: background,
|
||||
},
|
||||
".cm-tooltip .cm-tooltip-arrow:before": {},
|
||||
".cm-tooltip .cm-tooltip-arrow:after": {
|
||||
borderTopColor: background || '',
|
||||
borderBottomColor: background || '',
|
||||
borderTopColor: background,
|
||||
borderBottomColor: background,
|
||||
},
|
||||
".cm-tooltip-autocomplete": {
|
||||
"& > ul > li[aria-selected]": {
|
||||
backgroundColor: background || '',
|
||||
color: brightwhite || '',
|
||||
backgroundColor: background,
|
||||
color: brightwhite,
|
||||
},
|
||||
},
|
||||
},
|
||||
@ -320,7 +321,7 @@ export const installEditor = (app: Editor) => {
|
||||
),
|
||||
editorSetup,
|
||||
app.themeCompartment.of(
|
||||
getCodeMirrorTheme(app.getColorScheme("Batman")),
|
||||
getCodeMirrorTheme(app.getColorScheme("Tomorrow Night Burns")),
|
||||
// debug
|
||||
),
|
||||
app.chosenLanguage.of(javascript()),
|
||||
@ -343,7 +344,7 @@ export const installEditor = (app: Editor) => {
|
||||
),
|
||||
keymap.of([indentWithTab]),
|
||||
],
|
||||
doc: app.universes[app.selected_universe]!.global.candidate,
|
||||
doc: app.universes[app.selected_universe].global.candidate,
|
||||
});
|
||||
app.view = new EditorView({
|
||||
parent: document.getElementById("editor") as HTMLElement,
|
||||
143
src/Evaluator.ts
@ -1,32 +1,131 @@
|
||||
import type { Editor } from "./main";
|
||||
import type { File } from "./Editor/FileManagement";
|
||||
import type { File } from "./FileManagement";
|
||||
|
||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const codeReplace = (code: string): string => {
|
||||
return code.replace(/->|::/g, "&&");
|
||||
};
|
||||
|
||||
const tryCatchWrapper = async (
|
||||
application: Editor,
|
||||
code: string,
|
||||
): Promise<boolean> => {
|
||||
/**
|
||||
* Wraps the provided code in a try-catch block and executes it.
|
||||
*
|
||||
* @param application - The editor application.
|
||||
* @param code - The code to be executed.
|
||||
* @returns A promise that resolves to a boolean indicating whether the code executed successfully or not.
|
||||
*/
|
||||
|
||||
async function tryCatchWrapper(application: Editor, code: string): Promise<boolean> {
|
||||
try {
|
||||
await new Function(`"use strict"; ${code}`).call(application.api);
|
||||
await new Function(`"use strict"; ${codeReplace(code)}`).call(
|
||||
application.api,
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
application.interface.error_line.innerHTML = error as string;
|
||||
application.api._reportError(error as string);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export async function tryEvaluate(application: Editor, code: File): Promise<void> {
|
||||
const wrappedCode = `let i = ${code.evaluations}; ${code.candidate}`;
|
||||
const isCodeValid = await tryCatchWrapper(application, wrappedCode);
|
||||
if (isCodeValid) {
|
||||
code.committed = code.candidate;
|
||||
} else {
|
||||
console.error("Compilation error!");
|
||||
}
|
||||
}
|
||||
const cache = new Map<string, Function>();
|
||||
const MAX_CACHE_SIZE = 40;
|
||||
|
||||
export async function evaluateOnce(application: Editor, code: File): Promise<void> {
|
||||
const wrappedCode = `let i = ${code.evaluations}; ${code.candidate}`;
|
||||
const isCodeValid = await tryCatchWrapper(application, wrappedCode);
|
||||
if (isCodeValid) {
|
||||
code.committed = code.candidate;
|
||||
} else {
|
||||
console.error("Compilation error!");
|
||||
const addFunctionToCache = (code: string, fn: Function) => {
|
||||
/**
|
||||
* Adds a function to the cache.
|
||||
* @param code - The code associated with the function.
|
||||
* @param fn - The function to be added to the cache.
|
||||
*/
|
||||
if (cache.size >= MAX_CACHE_SIZE) {
|
||||
cache.delete(cache.keys().next().value);
|
||||
}
|
||||
}
|
||||
cache.set(code, fn);
|
||||
};
|
||||
|
||||
export const tryEvaluate = async (
|
||||
application: Editor,
|
||||
code: File,
|
||||
timeout = 5000,
|
||||
): Promise<void> => {
|
||||
/**
|
||||
* Tries to evaluate the provided code within a specified timeout period.
|
||||
* Increments the evaluation count of the code file.
|
||||
* If the code is valid, updates the committed code and adds the evaluated function to the cache.
|
||||
* If the code is invalid, retries the evaluation.
|
||||
* @param application - The editor application.
|
||||
* @param code - The code file to evaluate.
|
||||
* @param timeout - The timeout period in milliseconds (default: 5000).
|
||||
* @returns A Promise that resolves when the evaluation is complete.
|
||||
*/
|
||||
code.evaluations!++;
|
||||
const candidateCode = code.candidate;
|
||||
|
||||
try {
|
||||
const cachedFunction = cache.get(candidateCode);
|
||||
if (cachedFunction) {
|
||||
cachedFunction.call(application.api);
|
||||
} else {
|
||||
const wrappedCode = `let i = ${code.evaluations}; ${candidateCode}`;
|
||||
const isCodeValid = await Promise.race([
|
||||
tryCatchWrapper(application, wrappedCode),
|
||||
delay(timeout),
|
||||
]);
|
||||
|
||||
if (isCodeValid) {
|
||||
code.committed = code.candidate;
|
||||
const newFunction = new Function(
|
||||
`"use strict"; ${codeReplace(wrappedCode)}`,
|
||||
);
|
||||
addFunctionToCache(candidateCode, newFunction);
|
||||
} else {
|
||||
application.api.logOnce("Compilation error!");
|
||||
await evaluate(application, code, timeout);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
application.interface.error_line.innerHTML = error as string;
|
||||
application.api._reportError(error as string);
|
||||
}
|
||||
};
|
||||
|
||||
export const evaluate = async (
|
||||
application: Editor,
|
||||
code: File,
|
||||
timeout = 1000,
|
||||
): Promise<void> => {
|
||||
/**
|
||||
* Evaluates the given code using the provided application and timeout.
|
||||
* @param application The editor application.
|
||||
* @param code The code file to evaluate.
|
||||
* @param timeout The timeout value in milliseconds (default: 1000).
|
||||
* @returns A Promise that resolves when the evaluation is complete.
|
||||
*/
|
||||
|
||||
try {
|
||||
await Promise.race([
|
||||
tryCatchWrapper(application, code.committed as string),
|
||||
delay(timeout),
|
||||
]);
|
||||
if (code.evaluations) code.evaluations++;
|
||||
} catch (error) {
|
||||
application.interface.error_line.innerHTML = error as string;
|
||||
console.log(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const evaluateOnce = async (
|
||||
application: Editor,
|
||||
code: string,
|
||||
): Promise<void> => {
|
||||
/**
|
||||
* Evaluates the code once without any caching or error-handling mechanisms besides the tryCatchWrapper.
|
||||
*
|
||||
* @param application - The application object that contains the Editor API.
|
||||
* @param code - The code to be evaluated.
|
||||
* @returns A promise that resolves when the code has been evaluated.
|
||||
*/
|
||||
await tryCatchWrapper(application, code);
|
||||
};
|
||||
|
||||
@ -1,7 +1,9 @@
|
||||
// import { tutorial_universe } from "./universes/tutorial";
|
||||
import { gzipSync, decompressSync, strFromU8 } from "fflate";
|
||||
import { type Editor } from "../main";
|
||||
// import { examples } from "./examples/excerpts";
|
||||
import { type Editor } from "./main";
|
||||
import { uniqueNamesGenerator, colors, animals } from "unique-names-generator";
|
||||
import { tryEvaluate } from "../Evaluator";
|
||||
import { tryEvaluate } from "./Evaluator";
|
||||
export type Universes = { [key: string]: Universe };
|
||||
|
||||
export interface Universe {
|
||||
@ -179,7 +181,7 @@ export class AppSettings {
|
||||
}
|
||||
|
||||
get_universe() {
|
||||
this.universes["universe_name"];
|
||||
this.universes.universe_name;
|
||||
}
|
||||
|
||||
get data(): Settings {
|
||||
@ -356,7 +358,7 @@ export const loadUniverse = (
|
||||
// Updating the editor View to reflect the selected universe
|
||||
app.updateEditorView();
|
||||
// Evaluating the initialisation script for the selected universe
|
||||
tryEvaluate(app, app.universes[app.selected_universe.toString()]!.init);
|
||||
tryEvaluate(app, app.universes[app.selected_universe.toString()].init);
|
||||
};
|
||||
|
||||
export const openUniverseModal = (): void => {
|
||||
@ -1,6 +1,5 @@
|
||||
import { UserAPI } from "../API/API";
|
||||
import { MidiEvent } from "../Classes/MidiEvent";
|
||||
import { AppSettings } from "../Editor/FileManagement";
|
||||
import { UserAPI } from "../API";
|
||||
import { AppSettings } from "../FileManagement";
|
||||
|
||||
export type MidiNoteEvent = {
|
||||
note: number;
|
||||
@ -65,7 +64,7 @@ export class MidiConnection {
|
||||
constructor(api: UserAPI, settings: AppSettings) {
|
||||
this.api = api;
|
||||
this.settings = settings;
|
||||
this.lastBPM = api.app.clock.bpm;
|
||||
this.lastBPM = api.tempo();
|
||||
this.roundedBPM = this.lastBPM;
|
||||
this.initializeMidiAccess();
|
||||
}
|
||||
@ -105,13 +104,7 @@ export class MidiConnection {
|
||||
this.currentOutputIndex >= 0 &&
|
||||
this.currentOutputIndex < this.midiOutputs.length
|
||||
) {
|
||||
const output = this.midiOutputs[this.currentOutputIndex];
|
||||
if (output) {
|
||||
return output.name;
|
||||
} else {
|
||||
console.error("MIDI output is undefined.");
|
||||
return null;
|
||||
}
|
||||
return this.midiOutputs[this.currentOutputIndex].name;
|
||||
} else {
|
||||
console.error("No MIDI output selected or available.");
|
||||
return null;
|
||||
@ -260,7 +253,7 @@ export class MidiConnection {
|
||||
this.midiClockInput = this.midiInputs[clockInputIndex];
|
||||
this.registerMidiInputListener(clockInputIndex);
|
||||
this.settings.midi_clock_input =
|
||||
this.midiClockInput?.name ?? undefined;
|
||||
this.midiClockInput.name || undefined;
|
||||
}
|
||||
});
|
||||
|
||||
@ -284,7 +277,7 @@ export class MidiConnection {
|
||||
this.currentInputIndex = parseInt(value);
|
||||
this.registerMidiInputListener(this.currentInputIndex);
|
||||
this.settings.default_midi_input =
|
||||
this.midiInputs[this.currentInputIndex]?.name || undefined;
|
||||
this.midiInputs[this.currentInputIndex].name || undefined;
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -298,37 +291,36 @@ export class MidiConnection {
|
||||
const input = this.midiInputs[inputIndex];
|
||||
if (input && !input.onmidimessage) {
|
||||
input.onmidimessage = (event: Event) => {
|
||||
// @ts-ignore
|
||||
const message: MidiEvent = event as MIDIMessageEvent;
|
||||
const message = event as MIDIMessageEvent;
|
||||
/* MIDI CLOCK */
|
||||
if (input.name === this.settings.midi_clock_input) {
|
||||
if (message['data'][0] === 0xf8) {
|
||||
if (message.data[0] === 0xf8) {
|
||||
if (this.skipOnError > 0) {
|
||||
this.skipOnError -= 1;
|
||||
} else {
|
||||
this.onMidiClock(event.timeStamp);
|
||||
}
|
||||
} else if (message["data"]![0] === 0xfa) {
|
||||
} else if (message.data[0] === 0xfa) {
|
||||
console.log("MIDI start received");
|
||||
this.api.stop();
|
||||
this.api.play();
|
||||
} else if (message["data"]![0] === 0xfc) {
|
||||
} else if (message.data[0] === 0xfc) {
|
||||
console.log("MIDI stop received");
|
||||
this.api.pause();
|
||||
} else if (message["data"]![0] === 0xfb) {
|
||||
} else if (message.data[0] === 0xfb) {
|
||||
console.log("MIDI continue received");
|
||||
this.api.play();
|
||||
} else if (message["data"]![0] === 0xfe) {
|
||||
} else if (message.data[0] === 0xfe) {
|
||||
console.log("MIDI active sensing received");
|
||||
}
|
||||
}
|
||||
/* DEFAULT MIDI INPUT */
|
||||
if (input.name === this.settings.default_midi_input) {
|
||||
// If message is one of note ons
|
||||
if (message["data"][0] >= 0x90 && message["data"]![0] <= 0x9f) {
|
||||
const channel = message["data"]![0] - 0x90 + 1;
|
||||
const note = message["data"]![1];
|
||||
const velocity = message["data"]![2];
|
||||
if (message.data[0] >= 0x90 && message.data[0] <= 0x9f) {
|
||||
const channel = message.data[0] - 0x90 + 1;
|
||||
const note = message.data[1];
|
||||
const velocity = message.data[2];
|
||||
|
||||
this.lastNote = {
|
||||
note,
|
||||
@ -369,24 +361,24 @@ export class MidiConnection {
|
||||
}
|
||||
|
||||
// If note off
|
||||
if (message["data"]![0] >= 0x80 && message["data"]![0] <= 0x8f) {
|
||||
const channel = message["data"]![0] - 0x80 + 1;
|
||||
const note = message["data"]![1];
|
||||
if (message.data[0] >= 0x80 && message.data[0] <= 0x8f) {
|
||||
const channel = message.data[0] - 0x80 + 1;
|
||||
const note = message.data[1];
|
||||
this.removeFromActiveNotes(note, channel);
|
||||
}
|
||||
|
||||
// If message is one of CCs
|
||||
if (message["data"]![0] >= 0xb0 && message["data"]![0] <= 0xbf) {
|
||||
const channel = message["data"]![0] - 0xb0 + 1;
|
||||
const control = message["data"]![1];
|
||||
const value = message["data"]![2];
|
||||
if (message.data[0] >= 0xb0 && message.data[0] <= 0xbf) {
|
||||
const channel = message.data[0] - 0xb0 + 1;
|
||||
const control = message.data[1];
|
||||
const value = message.data[2];
|
||||
|
||||
this.lastCC[control] = value;
|
||||
if (this.lastCCInChannel[channel]) {
|
||||
this.lastCCInChannel[channel]![control] = value;
|
||||
this.lastCCInChannel[channel][control] = value;
|
||||
} else {
|
||||
this.lastCCInChannel[channel] = {};
|
||||
this.lastCCInChannel[channel]![control] = value;
|
||||
this.lastCCInChannel[channel][control] = value;
|
||||
}
|
||||
|
||||
//console.log(`CC: ${control} VALUE: ${value} CHANNEL: ${channel}`);
|
||||
@ -586,7 +578,8 @@ export class MidiConnection {
|
||||
if (typeof output === "number") {
|
||||
if (output < 0 || output >= this.midiOutputs.length) {
|
||||
console.error(
|
||||
`Invalid MIDI output index. Index must be in the range 0-${this.midiOutputs.length - 1
|
||||
`Invalid MIDI output index. Index must be in the range 0-${
|
||||
this.midiOutputs.length - 1
|
||||
}.`,
|
||||
);
|
||||
return this.currentOutputIndex;
|
||||
@ -615,7 +608,8 @@ export class MidiConnection {
|
||||
if (typeof input === "number") {
|
||||
if (input < 0 || input >= this.midiInputs.length) {
|
||||
console.error(
|
||||
`Invalid MIDI input index. Index must be in the range 0-${this.midiInputs.length - 1
|
||||
`Invalid MIDI input index. Index must be in the range 0-${
|
||||
this.midiInputs.length - 1
|
||||
}.`,
|
||||
);
|
||||
return -1;
|
||||
|
||||
@ -9,17 +9,6 @@ export interface OSCMessage {
|
||||
export let outputSocket = new WebSocket("ws://localhost:3000");
|
||||
export let inputSocket = new WebSocket("ws://localhost:3001");
|
||||
|
||||
|
||||
outputSocket.onerror = (error: Event) => {
|
||||
console.log("[Topos] Failed to connect to OSC daemon:", error.type);
|
||||
console.log("[Topos] Note: the daemon must be started before Topos");
|
||||
};
|
||||
|
||||
inputSocket.onerror = (error: Event) => {
|
||||
console.log("[Topos] Failed to connect to OSC daemon:", error.type);
|
||||
console.log("[Topos] Note: the daemon must be started before Topos");
|
||||
};
|
||||
|
||||
export let oscMessages: any[] = [];
|
||||
inputSocket.addEventListener("message", (event) => {
|
||||
let data = JSON.parse(event.data);
|
||||
@ -30,7 +19,7 @@ inputSocket.addEventListener("message", (event) => {
|
||||
});
|
||||
|
||||
// @ts-ignore
|
||||
outputSocket.onopen = function(event) {
|
||||
outputSocket.onopen = function (event) {
|
||||
console.log("Connected to WebSocket Server");
|
||||
// Send an OSC-like message
|
||||
outputSocket.send(
|
||||
@ -41,11 +30,11 @@ outputSocket.onopen = function(event) {
|
||||
}),
|
||||
);
|
||||
|
||||
outputSocket.onerror = function(error) {
|
||||
outputSocket.onerror = function (error) {
|
||||
console.log("Websocket Error:", error);
|
||||
};
|
||||
|
||||
outputSocket.onmessage = function(event) {
|
||||
outputSocket.onmessage = function (event) {
|
||||
console.log("Received: ", event.data);
|
||||
};
|
||||
};
|
||||
|
||||
0
src/IO/OSCConnection.ts
Normal file
@ -8,10 +8,7 @@
|
||||
// @ts-ignore
|
||||
import { registerSound, onTriggerSample } from "superdough";
|
||||
|
||||
export const isAudioFile = (filename: string) => {
|
||||
const extension = filename.split('.').slice(-1)[0];
|
||||
return extension !== undefined && ['wav', 'mp3'].includes(extension);
|
||||
};
|
||||
export const isAudioFile = (filename: string) => ['wav', 'mp3'].includes(filename.split('.').slice(-1)[0]);
|
||||
|
||||
interface samplesDBConfig {
|
||||
dbName: string,
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
import { EditorView } from "codemirror";
|
||||
import { vim } from "@replit/codemirror-vim";
|
||||
import { type Editor } from "../main";
|
||||
import colors from "../Editor/colors.json";
|
||||
import { type Editor } from "./main";
|
||||
import colors from "./colors.json";
|
||||
import {
|
||||
documentation_factory,
|
||||
documentation_pages,
|
||||
hideDocumentation,
|
||||
showDocumentation,
|
||||
updateDocumentationContent,
|
||||
} from "../Docs/Documentation";
|
||||
} from "./Documentation";
|
||||
import {
|
||||
type Universe,
|
||||
template_universe,
|
||||
@ -18,14 +18,14 @@ import {
|
||||
share,
|
||||
closeUniverseModal,
|
||||
openUniverseModal,
|
||||
} from "../Editor/FileManagement";
|
||||
import { loadSamples } from "../API/API";
|
||||
import { tryEvaluate } from "../Evaluator";
|
||||
import { inlineHoveringTips } from "../Docs/inlineHelp";
|
||||
} from "./FileManagement";
|
||||
import { loadSamples } from "./API";
|
||||
import { tryEvaluate } from "./Evaluator";
|
||||
import { inlineHoveringTips } from "./documentation/inlineHelp";
|
||||
import { lineNumbers } from "@codemirror/view";
|
||||
import { jsCompletions } from "../Editor/EditorSetup";
|
||||
import { jsCompletions } from "./EditorSetup";
|
||||
import { saveState } from "./WindowBehavior";
|
||||
import { registerSamplesFromDB, samplesDBConfig, uploadSamplesToDB } from "../IO/SampleLoading";
|
||||
import { registerSamplesFromDB, samplesDBConfig, uploadSamplesToDB } from "./IO/SampleLoading";
|
||||
|
||||
export const installInterfaceLogic = (app: Editor) => {
|
||||
// Initialize style
|
||||
@ -50,45 +50,56 @@ export const installInterfaceLogic = (app: Editor) => {
|
||||
const tabs = document.querySelectorAll('[id^="tab-"]');
|
||||
// Iterate over the tabs with an index
|
||||
for (let i = 0; i < tabs.length; i++) {
|
||||
tabs[i]!.addEventListener("click", (event) => {
|
||||
tabs[i].addEventListener("click", (event) => {
|
||||
// Updating the CSS accordingly
|
||||
tabs[i]!.classList.add("bg-foreground");
|
||||
tabs[i]!.classList.add("text-selection_foreground");
|
||||
tabs[i].classList.add("bg-foreground");
|
||||
tabs[i].classList.add("text-selection_foreground");
|
||||
for (let j = 0; j < tabs.length; j++) {
|
||||
if (j != i) tabs[j]!.classList.remove("bg-foreground");
|
||||
if (j != i) tabs[j]!.classList.remove("text-selection_foreground");
|
||||
if (j != i) tabs[j].classList.remove("bg-foreground");
|
||||
if (j != i) tabs[j].classList.remove("text-selection_foreground");
|
||||
}
|
||||
app.currentFile().candidate = app.view.state.doc.toString();
|
||||
|
||||
let tab = event.target as HTMLElement;
|
||||
let tab_id = tab.id.split("-")[1];
|
||||
app.local_index = parseInt(tab_id!);
|
||||
app.local_index = parseInt(tab_id);
|
||||
app.updateEditorView();
|
||||
});
|
||||
}
|
||||
|
||||
app.interface['logo'].addEventListener("click", () => {
|
||||
app.interface.topos_logo.addEventListener("click", () => {
|
||||
hideDocumentation();
|
||||
app.updateKnownUniversesView();
|
||||
openUniverseModal();
|
||||
});
|
||||
|
||||
app.interface['play_button'].addEventListener("click", () => {
|
||||
if (app.isPlaying) {
|
||||
app.clock.pause();
|
||||
} else {
|
||||
app.clock.resume()
|
||||
}
|
||||
updatePlayButton(app);
|
||||
app.buttonElements.play_buttons.forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
if (app.isPlaying) {
|
||||
app.setButtonHighlighting("pause", true);
|
||||
app.isPlaying = !app.isPlaying;
|
||||
app.clock.pause();
|
||||
app.api.MidiConnection.sendStopMessage();
|
||||
} else {
|
||||
app.setButtonHighlighting("play", true);
|
||||
app.isPlaying = !app.isPlaying;
|
||||
app.clock.start();
|
||||
app.api.MidiConnection.sendStartMessage();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
app.interface['stop_button'].addEventListener("click", () => {
|
||||
app.isPlaying = false;
|
||||
app.clock.stop();
|
||||
updatePlayButton(app);
|
||||
app.buttonElements.clear_buttons.forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
app.setButtonHighlighting("clear", true);
|
||||
if (confirm("Do you want to reset the current universe?")) {
|
||||
app.universes[app.selected_universe] =
|
||||
structuredClone(template_universe);
|
||||
app.updateEditorView();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
app.interface.documentation_button.addEventListener("click", () => {
|
||||
showDocumentation(app);
|
||||
});
|
||||
@ -129,13 +140,20 @@ export const installInterfaceLogic = (app: Editor) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.interface.audio_nudge_range.addEventListener("input", () => {
|
||||
// TODO: rebuild this
|
||||
// app.clock.nudge = parseInt(
|
||||
// (app.interface.audio_nudge_range as HTMLInputElement).value,
|
||||
// );
|
||||
});
|
||||
|
||||
app.interface.dough_nudge_range.addEventListener("input", () => {
|
||||
app.dough_nudge = parseInt(
|
||||
(app.interface.dough_nudge_range as HTMLInputElement).value,
|
||||
);
|
||||
});
|
||||
|
||||
app.interface.upload_samples_button.addEventListener("input", async (event: Event) => {
|
||||
app.interface.upload_samples_button.addEventListener("input", async (event) => {
|
||||
let fileInput = event.target as HTMLInputElement;
|
||||
if (!fileInput.files?.length) {
|
||||
return;
|
||||
@ -143,10 +161,10 @@ export const installInterfaceLogic = (app: Editor) => {
|
||||
app.interface.sample_indicator.innerText = "Loading...";
|
||||
app.interface.sample_indicator.classList.add("animate-pulse");
|
||||
await uploadSamplesToDB(samplesDBConfig, fileInput.files).then(() => {
|
||||
registerSamplesFromDB(samplesDBConfig, () => {
|
||||
app.interface.sample_indicator.innerText = "Import samples";
|
||||
app.interface.sample_indicator.classList.remove("animate-pulse");
|
||||
});
|
||||
registerSamplesFromDB(samplesDBConfig, () => {
|
||||
app.interface.sample_indicator.innerText = "Import samples";
|
||||
app.interface.sample_indicator.classList.remove("animate-pulse");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -221,6 +239,14 @@ export const installInterfaceLogic = (app: Editor) => {
|
||||
app.flashBackground("#404040", 200);
|
||||
});
|
||||
|
||||
app.buttonElements.stop_buttons.forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
app.setButtonHighlighting("stop", true);
|
||||
app.isPlaying = false;
|
||||
app.clock.stop();
|
||||
});
|
||||
});
|
||||
|
||||
app.interface.local_button.addEventListener("click", () =>
|
||||
app.changeModeFromInterface("local"),
|
||||
);
|
||||
@ -284,6 +310,7 @@ export const installInterfaceLogic = (app: Editor) => {
|
||||
for (const [key, _] of Object.entries(selected_theme)) {
|
||||
theme_preview += `<p class="inline text-${key} bg-${key}">█</div>`;
|
||||
}
|
||||
app.interface.theme_previewer.innerHTML = theme_preview;
|
||||
});
|
||||
|
||||
app.interface.settings_button.addEventListener("click", () => {
|
||||
@ -309,6 +336,12 @@ export const installInterfaceLogic = (app: Editor) => {
|
||||
|
||||
// @ts-ignore
|
||||
let selected_theme = colors[app.settings.theme as string];
|
||||
let theme_preview = "<div class='ml-6'>";
|
||||
for (const [key, _] of Object.entries(selected_theme)) {
|
||||
theme_preview += `<p class="inline text-${key} bg-${key}">█</p>`;
|
||||
}
|
||||
theme_preview += "</div>";
|
||||
app.interface.theme_previewer.innerHTML = theme_preview;
|
||||
// Populate the font family selector
|
||||
const doughNudgeRange = app.interface.dough_nudge_range as HTMLInputElement;
|
||||
doughNudgeRange.value = app.dough_nudge.toString();
|
||||
@ -409,6 +442,18 @@ export const installInterfaceLogic = (app: Editor) => {
|
||||
});
|
||||
});
|
||||
|
||||
app.interface.time_position_checkbox.addEventListener("change", () => {
|
||||
let timeviewer = document.getElementById("timeviewer") as HTMLElement;
|
||||
let checked = (app.interface.time_position_checkbox as HTMLInputElement)
|
||||
.checked
|
||||
? true
|
||||
: false;
|
||||
app.settings.time_position = checked;
|
||||
checked
|
||||
? timeviewer.classList.remove("hidden")
|
||||
: timeviewer.classList.add("hidden");
|
||||
});
|
||||
|
||||
app.interface.tips_checkbox.addEventListener("change", () => {
|
||||
let checked = (app.interface.tips_checkbox as HTMLInputElement).checked
|
||||
? true
|
||||
@ -464,7 +509,7 @@ export const installInterfaceLogic = (app: Editor) => {
|
||||
// app.settings.load_demo_songs = checked;
|
||||
// });
|
||||
|
||||
app.interface.universe_creator.addEventListener("submit", (event: Event) => {
|
||||
app.interface.universe_creator.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
let data = new FormData(app.interface.universe_creator as HTMLFormElement);
|
||||
@ -483,7 +528,7 @@ export const installInterfaceLogic = (app: Editor) => {
|
||||
}
|
||||
});
|
||||
|
||||
tryEvaluate(app, app.universes[app.selected_universe.toString()]!.init);
|
||||
tryEvaluate(app, app.universes[app.selected_universe.toString()].init);
|
||||
|
||||
documentation_pages.forEach((e) => {
|
||||
let name = `docs_` + e;
|
||||
@ -510,44 +555,4 @@ export const installInterfaceLogic = (app: Editor) => {
|
||||
console.log("Could not find element " + name);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const updatePlayButton = (app: Editor) => {
|
||||
switch (app.clock.state) {
|
||||
case 'stopped':
|
||||
app.interface.play_label.innerText = "Play";
|
||||
updatePlayPauseIcon(app, "play");
|
||||
break;
|
||||
case 'paused':
|
||||
app.interface.play_label.innerText = "Resume";
|
||||
updatePlayPauseIcon(app, "play");
|
||||
break;
|
||||
case 'running':
|
||||
app.interface.play_label.innerText = "Pause";
|
||||
updatePlayPauseIcon(app, "pause");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
export const updatePlayPauseIcon = (app: Editor, state: "play" | "pause"): void => {
|
||||
const { play_icon, pause_icon } = app.interface;
|
||||
|
||||
const isPlayIconHidden = play_icon.classList.contains("hidden");
|
||||
const isPauseIconHidden = pause_icon.classList.contains("hidden");
|
||||
|
||||
if (state === "play" && isPlayIconHidden) {
|
||||
play_icon.classList.remove("hidden");
|
||||
pause_icon.classList.add("hidden");
|
||||
} else if (state === "pause" && isPauseIconHidden) {
|
||||
play_icon.classList.add("hidden");
|
||||
pause_icon.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
export const resetTransportView = (app: Editor) => {
|
||||
requestAnimationFrame(() => {
|
||||
app.interface.transport_viewer.innerHTML = `<span class="text-xl text-neutral">00:00:00</span>`;
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
};
|
||||
@ -1,9 +1,8 @@
|
||||
import { type Editor } from "../main";
|
||||
import { type Editor } from "./main";
|
||||
import { vim } from "@replit/codemirror-vim";
|
||||
import { tryEvaluate } from "../Evaluator";
|
||||
import { hideDocumentation, showDocumentation } from "../Docs/Documentation";
|
||||
import { openSettingsModal, openUniverseModal } from "../Editor/FileManagement";
|
||||
import { resetTransportView, updatePlayButton } from "./UILogic";
|
||||
import { tryEvaluate } from "./Evaluator";
|
||||
import { hideDocumentation, showDocumentation } from "./Documentation";
|
||||
import { openSettingsModal, openUniverseModal } from "./FileManagement";
|
||||
|
||||
export const registerFillKeys = (app: Editor) => {
|
||||
document.addEventListener("keydown", (event) => {
|
||||
@ -54,21 +53,21 @@ export const registerOnKeyDown = (app: Editor) => {
|
||||
|
||||
if (event.ctrlKey && event.key === "s") {
|
||||
event.preventDefault();
|
||||
app.flashBackground("#404040", 200);
|
||||
requestAnimationFrame (() => {
|
||||
updatePlayButton(app);
|
||||
resetTransportView(app);
|
||||
});
|
||||
app.clock.stop()
|
||||
app.setButtonHighlighting("stop", true);
|
||||
app.clock.stop();
|
||||
}
|
||||
|
||||
if (event.ctrlKey && event.key === "p") {
|
||||
event.preventDefault();
|
||||
app.flashBackground("#404040", 200);
|
||||
requestAnimationFrame(() => {
|
||||
updatePlayButton(app);
|
||||
});
|
||||
app.clock.resume()
|
||||
if (app.isPlaying) {
|
||||
app.isPlaying = false;
|
||||
app.setButtonHighlighting("pause", true);
|
||||
app.clock.pause();
|
||||
} else {
|
||||
app.isPlaying = true;
|
||||
app.setButtonHighlighting("play", true);
|
||||
app.clock.start();
|
||||
}
|
||||
}
|
||||
|
||||
// Ctrl + Shift + V: Vim Mode
|
||||
65
src/TransportNode.js
Normal file
@ -0,0 +1,65 @@
|
||||
import { tryEvaluate } from "./Evaluator";
|
||||
const zeroPad = (num, places) => String(num).padStart(places, "0");
|
||||
|
||||
export class TransportNode extends AudioWorkletNode {
|
||||
constructor(context, options, application) {
|
||||
super(context, "transport", options);
|
||||
this.app = application;
|
||||
this.port.addEventListener("message", this.handleMessage);
|
||||
this.port.start();
|
||||
this.timeviewer = document.getElementById("timeviewer");
|
||||
}
|
||||
|
||||
/** @type {(this: MessagePort, ev: MessageEvent<any>) => any} */
|
||||
handleMessage = (message) => {
|
||||
if(message.data) {
|
||||
if (message.data.type === "bang") {
|
||||
if(this.app.clock.running) {
|
||||
if (this.app.settings.send_clock) {
|
||||
this.app.api.MidiConnection.sendMidiClock();
|
||||
}
|
||||
const futureTimeStamp = this.app.clock.convertTicksToTimeposition(
|
||||
this.app.clock.tick
|
||||
);
|
||||
this.app.clock.time_position = futureTimeStamp;
|
||||
this.timeviewer.innerHTML = `${zeroPad(futureTimeStamp.bar, 2)}:${futureTimeStamp.beat + 1
|
||||
}:${zeroPad(futureTimeStamp.pulse, 2)} / ${this.app.clock.bpm}`;
|
||||
if (this.app.exampleIsPlaying) {
|
||||
tryEvaluate(this.app, this.app.example_buffer);
|
||||
} else {
|
||||
tryEvaluate(this.app, this.app.global_buffer);
|
||||
}
|
||||
this.app.clock.incrementTick(message.data.bpm);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
start() {
|
||||
this.port.postMessage({ type: "start" });
|
||||
}
|
||||
|
||||
pause() {
|
||||
this.port.postMessage({ type: "pause" });
|
||||
}
|
||||
|
||||
resume() {
|
||||
this.port.postMessage({ type: "resume" });
|
||||
}
|
||||
|
||||
setBPM(bpm) {
|
||||
this.port.postMessage({ type: "bpm", value: bpm });
|
||||
}
|
||||
|
||||
setPPQN(ppqn) {
|
||||
this.port.postMessage({ type: "ppqn", value: ppqn });
|
||||
}
|
||||
|
||||
setNudge(nudge) {
|
||||
this.port.postMessage({ type: "nudge", value: nudge });
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.port.postMessage({type: "stop" });
|
||||
}
|
||||
}
|
||||
47
src/TransportProcessor.js
Normal file
@ -0,0 +1,47 @@
|
||||
class TransportProcessor extends AudioWorkletProcessor {
|
||||
constructor(options) {
|
||||
super(options);
|
||||
this.port.addEventListener("message", this.handleMessage);
|
||||
this.port.start();
|
||||
this.nudge = 0;
|
||||
this.started = false;
|
||||
this.bpm = 120;
|
||||
this.ppqn = 48;
|
||||
this.currentPulsePosition = 0;
|
||||
}
|
||||
|
||||
handleMessage = (message) => {
|
||||
if (message.data && message.data.type === "ping") {
|
||||
this.port.postMessage(message.data);
|
||||
} else if (message.data.type === "start") {
|
||||
this.started = true;
|
||||
} else if (message.data.type === "pause") {
|
||||
this.started = false;
|
||||
} else if (message.data.type === "stop") {
|
||||
this.started = false;
|
||||
} else if (message.data.type === "bpm") {
|
||||
this.bpm = message.data.value;
|
||||
this.currentPulsePosition = currentTime;
|
||||
} else if (message.data.type === "ppqn") {
|
||||
this.ppqn = message.data.value;
|
||||
this.currentPulsePosition = currentTime;
|
||||
} else if (message.data.type === "nudge") {
|
||||
this.nudge = message.data.value;
|
||||
}
|
||||
};
|
||||
|
||||
process(inputs, outputs, parameters) {
|
||||
if (this.started) {
|
||||
const adjustedCurrentTime = currentTime + this.nudge / 100;
|
||||
const beatNumber = adjustedCurrentTime / (60 / this.bpm);
|
||||
const currentPulsePosition = Math.ceil(beatNumber * this.ppqn);
|
||||
if (currentPulsePosition > this.currentPulsePosition) {
|
||||
this.currentPulsePosition = currentPulsePosition;
|
||||
this.port.postMessage({ type: "bang", bpm: this.bpm });
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor("transport", TransportProcessor);
|
||||
@ -1,9 +1,4 @@
|
||||
import { type Editor } from "../../main";
|
||||
|
||||
const HORIZONTALOFFSETPERCENT = 0.025;
|
||||
const VERTICALOFFSETPERCENT = 0.025;
|
||||
const RADIUSPERCENT = 0.010;
|
||||
const SHIFTPERCENT = 0.025;
|
||||
import { type Editor } from "../main";
|
||||
|
||||
export const drawCircle = (
|
||||
/**
|
||||
@ -22,7 +17,6 @@ export const drawCircle = (
|
||||
// @ts-ignore
|
||||
const canvas: HTMLCanvasElement = app.interface.feedback;
|
||||
const ctx = canvas.getContext("2d");
|
||||
console.log(`Canvas size: ${canvas.width}x${canvas.height}`);
|
||||
if (!ctx) return;
|
||||
|
||||
ctx.beginPath();
|
||||
@ -44,36 +38,38 @@ export const blinkScript = (
|
||||
) => {
|
||||
if (no !== undefined && no < 1 && no > 9) return;
|
||||
const blinkDuration =
|
||||
(app.clock.bpm / 60 / app.clock.time_position.num) * 200;
|
||||
(app.clock.bpm / 60 / app.clock.time_signature[1]) * 200;
|
||||
// @ts-ignore
|
||||
const ctx = app.interface.feedback.getContext("2d");
|
||||
const ctx = app.interface.feedback.getContext("2d"); // Assuming a canvas context
|
||||
|
||||
/**
|
||||
* Draws a circle at a given shift.
|
||||
* @param shift - The pixel distance from the origin.
|
||||
*/
|
||||
const _drawBlinker = (shift: number) => {
|
||||
const horizontalOffsetPercent = HORIZONTALOFFSETPERCENT;
|
||||
const verticalOffsetPercent = VERTICALOFFSETPERCENT;
|
||||
const radiusPercent = RADIUSPERCENT;
|
||||
const horizontalOffset = 50;
|
||||
drawCircle(
|
||||
app,
|
||||
(app.interface.feedback as HTMLCanvasElement).width * horizontalOffsetPercent + shift,
|
||||
(app.interface.feedback as HTMLCanvasElement).height * (1 - verticalOffsetPercent),
|
||||
(app.interface.feedback as HTMLCanvasElement).width * radiusPercent,
|
||||
horizontalOffset + shift,
|
||||
app.interface.feedback.clientHeight - 15,
|
||||
8,
|
||||
"#fdba74",
|
||||
);
|
||||
};
|
||||
|
||||
const _clearBlinker = (shift: number) => {
|
||||
const horizontalOffsetPercent = HORIZONTALOFFSETPERCENT;
|
||||
const verticalOffsetPercent = VERTICALOFFSETPERCENT;
|
||||
const radiusPercent = RADIUSPERCENT;
|
||||
const x = (app.interface.feedback as HTMLCanvasElement).width * horizontalOffsetPercent + shift;
|
||||
const y = (app.interface.feedback as HTMLCanvasElement).height * (1 - verticalOffsetPercent);
|
||||
const radius = (app.interface.feedback as HTMLCanvasElement).width * radiusPercent;
|
||||
/**
|
||||
* Clears the circle at a given shift.
|
||||
* @param shift - The pixel distance from the origin.
|
||||
*/
|
||||
const x = 50 + shift;
|
||||
const y = app.interface.feedback.clientHeight - 15;
|
||||
const radius = 8;
|
||||
ctx.clearRect(x - radius, y - radius, radius * 2, radius * 2);
|
||||
};
|
||||
|
||||
if (script === "local" && no !== undefined) {
|
||||
const shiftPercent = SHIFTPERCENT;
|
||||
const shiftAmount = no * (app.interface.feedback as HTMLCanvasElement).width * shiftPercent;
|
||||
const shiftAmount = no * 25;
|
||||
|
||||
// Clear existing timeout if any
|
||||
if (app.blinkTimeouts[shiftAmount]) {
|
||||
@ -1,3 +1,35 @@
|
||||
export type ShapeObject = {
|
||||
x: number;
|
||||
y: number;
|
||||
x1: number;
|
||||
y1: number;
|
||||
x2: number;
|
||||
y2: number;
|
||||
radius: number;
|
||||
width: number;
|
||||
height: number;
|
||||
fillStyle: string;
|
||||
secondary: string;
|
||||
strokeStyle: string;
|
||||
rotation: number;
|
||||
points: number;
|
||||
outerRadius: number;
|
||||
eyeSize: number;
|
||||
happiness: number;
|
||||
slices: number;
|
||||
gap: number;
|
||||
font: string;
|
||||
fontSize: number;
|
||||
text: string;
|
||||
filter: string;
|
||||
url: string;
|
||||
curve: number;
|
||||
curves: number;
|
||||
stroke: string;
|
||||
eaten: number;
|
||||
hole: number;
|
||||
};
|
||||
|
||||
export const drawBackground = (
|
||||
canvas: HTMLCanvasElement,
|
||||
color: string | number,
|
||||
@ -28,7 +60,7 @@ export const createLinearGradient = (
|
||||
let color = stops[i + 1];
|
||||
if (typeof color === "number")
|
||||
color = `rgb(${color},${stops[i + 2]},${stops[i + 3]})`;
|
||||
gradient.addColorStop(stops[i] as number, color as string);
|
||||
gradient.addColorStop(stops[i] as number, color);
|
||||
}
|
||||
return gradient;
|
||||
};
|
||||
@ -59,7 +91,7 @@ export const createRadialGradient = (
|
||||
let color = stops[i + 1];
|
||||
if (typeof color === "number")
|
||||
color = `rgb(${color},${stops[i + 2]},${stops[i + 3]})`;
|
||||
gradient.addColorStop(stops[i] as number, color as string);
|
||||
gradient.addColorStop(stops[i] as number, color);
|
||||
}
|
||||
return gradient;
|
||||
};
|
||||
@ -84,7 +116,7 @@ export const createConicGradient = (
|
||||
let color = stops[i + 1];
|
||||
if (typeof color === "number")
|
||||
color = `rgb(${color},${stops[i + 2]},${stops[i + 3]})`;
|
||||
gradient.addColorStop(stops[i] as number, color as string);
|
||||
gradient.addColorStop(stops[i] as number, color);
|
||||
}
|
||||
return gradient;
|
||||
};
|
||||
@ -189,11 +221,10 @@ export const drawBalloid = (
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = secondary;
|
||||
// Form the shape from points with straight lines and fill it
|
||||
if (points[0]) {
|
||||
ctx.moveTo(points[0][0] as number, points[0][1] as number);
|
||||
for (let point of points) ctx.lineTo(point[0] as number, point[1] as number);
|
||||
}
|
||||
ctx.moveTo(points[0][0], points[0][1]);
|
||||
for (let point of points) ctx.lineTo(point[0], point[1]);
|
||||
// Close and fill
|
||||
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
// @ts-ignore
|
||||
import { getAnalyser } from "superdough";
|
||||
import { Editor } from "../../main";
|
||||
import { Editor } from "../main";
|
||||
|
||||
export interface OscilloscopeConfig {
|
||||
enabled: boolean;
|
||||
@ -71,7 +71,7 @@ export const runOscilloscope = (
|
||||
|
||||
for (let i = 0; i < numBars; i++) {
|
||||
barHeight = Math.floor(
|
||||
freqDataArray[Math.floor((i * freqDataArray.length) / numBars)]! *
|
||||
freqDataArray[Math.floor((i * freqDataArray.length) / numBars)] *
|
||||
((height / 256) * app.osc.size),
|
||||
);
|
||||
|
||||
@ -139,7 +139,7 @@ export const runOscilloscope = (
|
||||
|
||||
canvasCtx.fillStyle = "rgba(0, 0, 0, 0)";
|
||||
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
|
||||
if (app.clock.time_position.tick % app.osc.refresh == 0) {
|
||||
if (app.clock.time_position.pulse % app.osc.refresh == 0) {
|
||||
canvasCtx.clearRect(
|
||||
-OFFSET_WIDTH,
|
||||
-OFFSET_HEIGHT,
|
||||
@ -150,14 +150,14 @@ export const runOscilloscope = (
|
||||
canvasCtx.lineWidth = app.osc.thickness;
|
||||
|
||||
if (app.osc.color === "random") {
|
||||
if (app.clock.time_position.tick % 16 === 0) {
|
||||
if (app.clock.time_position.pulse % 16 === 0) {
|
||||
canvasCtx.strokeStyle = `hsl(${Math.random() * 360}, 100%, 50%)`;
|
||||
}
|
||||
} else {
|
||||
canvasCtx.strokeStyle = app.osc.color;
|
||||
}
|
||||
const remainingRefreshTime =
|
||||
app.clock.time_position.tick % app.osc.refresh;
|
||||
app.clock.time_position.pulse % app.osc.refresh;
|
||||
const opacityRatio = 1 - remainingRefreshTime / app.osc.refresh;
|
||||
canvasCtx.globalAlpha = opacityRatio;
|
||||
canvasCtx.beginPath();
|
||||
@ -165,9 +165,9 @@ export const runOscilloscope = (
|
||||
let startIndex = 0;
|
||||
for (let i = 1; i < dataArray.length; ++i) {
|
||||
let currentType = null;
|
||||
if (dataArray[i]! >= 0 && dataArray[i - 1]! < 0) {
|
||||
if (dataArray[i] >= 0 && dataArray[i - 1] < 0) {
|
||||
currentType = "negToPos";
|
||||
} else if (dataArray[i]! < 0 && dataArray[i - 1]! >= 0) {
|
||||
} else if (dataArray[i] < 0 && dataArray[i - 1] >= 0) {
|
||||
currentType = "posToNeg";
|
||||
}
|
||||
|
||||
@ -187,8 +187,8 @@ export const runOscilloscope = (
|
||||
drawFrequencyScope(WIDTH, HEIGHT, OFFSET_HEIGHT, OFFSET_WIDTH);
|
||||
} else if (app.osc.mode === "3D") {
|
||||
for (let i = startIndex; i < dataArray.length; i += 2) {
|
||||
const x = (dataArray[i]! * WIDTH * app.osc.size) / 2 + WIDTH / 4;
|
||||
const y = (dataArray[i + 1]! * HEIGHT * app.osc.size) / 2 + HEIGHT / 4;
|
||||
const x = (dataArray[i] * WIDTH * app.osc.size) / 2 + WIDTH / 4;
|
||||
const y = (dataArray[i + 1] * HEIGHT * app.osc.size) / 2 + HEIGHT / 4;
|
||||
i === startIndex ? canvasCtx.moveTo(x, y) : canvasCtx.lineTo(x, y);
|
||||
}
|
||||
} else if (
|
||||
@ -199,7 +199,7 @@ export const runOscilloscope = (
|
||||
const yOffset = HEIGHT / 4;
|
||||
let x = 0;
|
||||
for (let i = startIndex; i < dataArray.length; i++) {
|
||||
const v = dataArray[i]! * 0.5 * HEIGHT * app.osc.size;
|
||||
const v = dataArray[i] * 0.5 * HEIGHT * app.osc.size;
|
||||
const y = v + yOffset;
|
||||
i === startIndex ? canvasCtx.moveTo(x, y) : canvasCtx.lineTo(x, y);
|
||||
x += sliceWidth;
|
||||
@ -210,7 +210,7 @@ export const runOscilloscope = (
|
||||
const xOffset = WIDTH / 4;
|
||||
let y = 0;
|
||||
for (let i = startIndex; i < dataArray.length; i++) {
|
||||
const v = dataArray[i]! * 0.5 * WIDTH * app.osc.size;
|
||||
const v = dataArray[i] * 0.5 * WIDTH * app.osc.size;
|
||||
const x = v + xOffset;
|
||||
i === startIndex ? canvasCtx.moveTo(x, y) : canvasCtx.lineTo(x, y);
|
||||
y += sliceHeight;
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../main";
|
||||
import { outputSocket, inputSocket } from "../IO/OSC";
|
||||
import { type Editor } from "./main";
|
||||
import { outputSocket, inputSocket } from "./IO/OSC";
|
||||
|
||||
const handleResize = (canvas: HTMLCanvasElement) => {
|
||||
if (!canvas) return;
|
||||
@ -38,29 +38,32 @@ export const installWindowBehaviors = (
|
||||
window: Window,
|
||||
preventMultipleTabs: boolean = false,
|
||||
) => {
|
||||
window.addEventListener("resize", () =>
|
||||
handleResize(app.interface.scope as HTMLCanvasElement),
|
||||
);
|
||||
window.addEventListener("resize", () =>
|
||||
handleResize(app.interface.feedback as HTMLCanvasElement),
|
||||
);
|
||||
window.addEventListener("resize", () =>
|
||||
handleResize(app.interface.scope as HTMLCanvasElement),
|
||||
);
|
||||
// window.addEventListener("beforeunload", (event) => {
|
||||
// event.preventDefault();
|
||||
// saveBeforeExit(app);
|
||||
// });
|
||||
handleResize(app.interface.drawings as HTMLCanvasElement),
|
||||
);
|
||||
window.addEventListener("beforeunload", (event) => {
|
||||
event.preventDefault();
|
||||
saveBeforeExit(app);
|
||||
});
|
||||
window.addEventListener("visibilitychange", (event) => {
|
||||
event.preventDefault();
|
||||
saveState(app);
|
||||
});
|
||||
|
||||
if (preventMultipleTabs) {
|
||||
localStorage["openpages"] = Date.now();
|
||||
localStorage.openpages = Date.now();
|
||||
window.addEventListener(
|
||||
"storage",
|
||||
function(e) {
|
||||
function (e) {
|
||||
if (e.key == "openpages") {
|
||||
// Listen if anybody else is opening the same page!
|
||||
localStorage["page_available"] = Date.now();
|
||||
localStorage.page_available = Date.now();
|
||||
}
|
||||
if (e.key == "page_available") {
|
||||
document.getElementById("all")!.classList.add("invisible");
|
||||
@ -6,8 +6,8 @@ import {
|
||||
resolvePitchBend,
|
||||
safeScale,
|
||||
} from "zifferjs";
|
||||
import { SkipEvent } from "../Classes/SkipEvent";
|
||||
import { SoundParams } from "../Classes/SoundEvent";
|
||||
import { SkipEvent } from "./SkipEvent";
|
||||
import { SoundParams } from "./SoundEvent";
|
||||
import { centsToSemitones, edoToSemitones, ratiosToSemitones } from "zifferjs/src/scale";
|
||||
import { safeMod } from "zifferjs/src/utils";
|
||||
|
||||
@ -211,12 +211,12 @@ export class AbstractEvent {
|
||||
* @param func - The function to be applied to the Event
|
||||
* @returns The transformed Event
|
||||
*/
|
||||
return this.modify(func)["update"]();
|
||||
return this.modify(func).update();
|
||||
};
|
||||
|
||||
mod = (value: number): AbstractEvent => {
|
||||
this.values["originalPitch"] = safeMod(this.values["originalPitch"], value);
|
||||
return this["update"]();
|
||||
this.values.originalPitch = safeMod(this.values.originalPitch, value);
|
||||
return this.update();
|
||||
}
|
||||
|
||||
noteLength = (
|
||||
@ -230,18 +230,17 @@ export class AbstractEvent {
|
||||
value = Array.isArray(value) ? value.concat(kwargs) : [value, ...kwargs];
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
this.values["dur"] = value.map((v) =>
|
||||
this.values.dur = value.map((v) =>
|
||||
this.app.clock.convertPulseToSecond(v * 4 * this.app.clock.ppqn),
|
||||
);
|
||||
} else {
|
||||
this.values["dur"] = this.app.clock.convertPulseToSecond(
|
||||
this.values.dur = this.app.clock.convertPulseToSecond(
|
||||
value * 4 * this.app.clock.ppqn,
|
||||
);
|
||||
}
|
||||
if(this["current"]) {
|
||||
// @ts-ignore
|
||||
value = Array.isArray(value) ? value[this["index"]%value.length] : value;
|
||||
this["current"].duration = value;
|
||||
if(this.current) {
|
||||
value = Array.isArray(value) ? value[this.index%value.length] : value;
|
||||
this.current.duration = value;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
@ -254,9 +253,7 @@ export class AbstractEvent {
|
||||
const n: number[] = [];
|
||||
sound.forEach((str) => {
|
||||
const parts = (str as string).split(":");
|
||||
if (parts[0] !== undefined) {
|
||||
s.push(parts[0]);
|
||||
}
|
||||
s.push(parts[0]);
|
||||
if (parts[1]) {
|
||||
n.push(parseInt(parts[1]));
|
||||
}
|
||||
@ -276,7 +273,7 @@ export class AbstractEvent {
|
||||
if (sound.includes(":")) {
|
||||
const vals = sound.split(":");
|
||||
const s = vals[0];
|
||||
const n = parseInt(vals[1] ?? '');
|
||||
const n = parseInt(vals[1]);
|
||||
return {
|
||||
s,
|
||||
n,
|
||||
@ -322,9 +319,9 @@ export abstract class AudibleEvent extends AbstractEvent {
|
||||
}
|
||||
this.values["paramOctave"] = value;
|
||||
if (
|
||||
this.values['key'] &&
|
||||
(this.values['pitch'] || this.values['pitch'] === 0) &&
|
||||
this.values['parsedScale']
|
||||
this.values.key &&
|
||||
(this.values.pitch || this.values.pitch === 0) &&
|
||||
this.values.parsedScale
|
||||
) {
|
||||
return this.update();
|
||||
}
|
||||
@ -343,8 +340,8 @@ export abstract class AudibleEvent extends AbstractEvent {
|
||||
}
|
||||
this.values["key"] = value;
|
||||
if (
|
||||
(this.values['pitch'] || this.values['pitch'] === 0) &&
|
||||
this.values['parsedScale']
|
||||
(this.values.pitch || this.values.pitch === 0) &&
|
||||
this.values.parsedScale
|
||||
) {
|
||||
return this.update();
|
||||
}
|
||||
@ -353,9 +350,9 @@ export abstract class AudibleEvent extends AbstractEvent {
|
||||
};
|
||||
|
||||
defaultPitchKeyScale() {
|
||||
if (!this.values["key"]) this.values["key"] = 60;
|
||||
if (!(this.values["pitch"] || this.values["pitch"] === 0)) this.values["pitch"] = 0;
|
||||
if (!this.values["parsedScale"]) this.values["parsedScale"] = safeScale("major");
|
||||
if (!this.values.key) this.values.key = 60;
|
||||
if (!(this.values.pitch || this.values.pitch === 0)) this.values.pitch = 0;
|
||||
if (!this.values.parsedScale) this.values.parsedScale = safeScale("major");
|
||||
}
|
||||
|
||||
scale = (
|
||||
@ -371,9 +368,9 @@ export abstract class AudibleEvent extends AbstractEvent {
|
||||
value = Array.isArray(value) ? value.concat(kwargs) : [value, ...kwargs];
|
||||
}
|
||||
if (typeof value === "string" || typeof value === "number") {
|
||||
this.values["parsedScale"] = safeScale(value) as number[];
|
||||
this.values.parsedScale = safeScale(value) as number[];
|
||||
} else if (Array.isArray(value)) {
|
||||
this.values["parsedScale"] = value.map((v) => safeScale(v));
|
||||
this.values.parsedScale = value.map((v) => safeScale(v));
|
||||
}
|
||||
this.defaultPitchKeyScale();
|
||||
return this.update();
|
||||
@ -381,7 +378,7 @@ export abstract class AudibleEvent extends AbstractEvent {
|
||||
|
||||
semitones(values: number|number[], ...rest: number[]) {
|
||||
const scaleValues = typeof values === "number" ? [values, ...rest] : values;
|
||||
this.values["parsedScale"] = safeScale(scaleValues);
|
||||
this.values.parsedScale = safeScale(scaleValues);
|
||||
this.defaultPitchKeyScale();
|
||||
return this.update();
|
||||
}
|
||||
@ -389,20 +386,20 @@ export abstract class AudibleEvent extends AbstractEvent {
|
||||
|
||||
cents(values: number|number[], ...rest: number[]) {
|
||||
const scaleValues = typeof values === "number" ? [values, ...rest] : values;
|
||||
this.values["parsedScale"] = safeScale(centsToSemitones(scaleValues));
|
||||
this.values.parsedScale = safeScale(centsToSemitones(scaleValues));
|
||||
this.defaultPitchKeyScale();
|
||||
return this.update();
|
||||
}
|
||||
|
||||
ratios(values: number|number[], ...rest: number[]) {
|
||||
const scaleValues = typeof values === "number" ? [values, ...rest] : values;
|
||||
this.values["parsedScale"] = safeScale(ratiosToSemitones(scaleValues));
|
||||
this.values.parsedScale = safeScale(ratiosToSemitones(scaleValues));
|
||||
this.defaultPitchKeyScale();
|
||||
return this.update();
|
||||
}
|
||||
|
||||
edo(value: number, intervals: string|number[] = new Array(value).fill(1)) {
|
||||
this.values["parsedScale"] = edoToSemitones(value, intervals);
|
||||
this.values.parsedScale = edoToSemitones(value, intervals);
|
||||
this.defaultPitchKeyScale();
|
||||
return this.update();
|
||||
}
|
||||
@ -439,8 +436,8 @@ export abstract class AudibleEvent extends AbstractEvent {
|
||||
|
||||
public invert = (howMany: number = 0) => {
|
||||
if(howMany === 0) return this;
|
||||
if (this.values["note"]) {
|
||||
let notes = [...this.values["note"]];
|
||||
if (this.values.note) {
|
||||
let notes = [...this.values.note];
|
||||
notes = howMany < 0 ? [...notes].reverse() : notes;
|
||||
for (let i = 0; i < Math.abs(howMany); i++) {
|
||||
notes[i % notes.length] += howMany <= 0 ? -12 : 12;
|
||||
@ -471,11 +468,11 @@ export abstract class AudibleEvent extends AbstractEvent {
|
||||
}
|
||||
|
||||
public draw = (lambda: Function) => {
|
||||
lambda(this.values, (this.app.interface.feedback as HTMLCanvasElement).getContext("2d"));
|
||||
lambda(this.values, (this.app.interface.drawings as HTMLCanvasElement).getContext("2d"));
|
||||
return this;
|
||||
}
|
||||
|
||||
public override clear = () => {
|
||||
public clear = () => {
|
||||
this.app.api.clear();
|
||||
return this;
|
||||
}
|
||||
@ -502,7 +499,7 @@ export abstract class AudibleEvent extends AbstractEvent {
|
||||
this.values["note"].push(midiNote);
|
||||
}
|
||||
}
|
||||
if (this.values["bend"].length === 0) delete this.values["bend"];
|
||||
if (this.values.bend.length === 0) delete this.values.bend;
|
||||
} else {
|
||||
const midiNote = freqToMidi(value);
|
||||
if (midiNote % 1 !== 0) {
|
||||
@ -527,8 +524,8 @@ export abstract class AudibleEvent extends AbstractEvent {
|
||||
|
||||
runChain = (): this => {
|
||||
// chainAll is defined using all() in the API
|
||||
if("chainAll" in this && typeof this["chainAll"] === "function") {
|
||||
this.values = this["chainAll"]().values;
|
||||
if("chainAll" in this && typeof this.chainAll === "function") {
|
||||
this.values = this.chainAll().values;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -23,7 +23,7 @@ export class MidiEvent extends AudibleEvent {
|
||||
|
||||
constructor(
|
||||
input: MidiParams,
|
||||
app: Editor,
|
||||
public app: Editor,
|
||||
) {
|
||||
super(app);
|
||||
this.values = input;
|
||||
@ -57,11 +57,11 @@ export class MidiEvent extends AudibleEvent {
|
||||
};
|
||||
|
||||
add = (value: number): this => {
|
||||
this.values["note"] += value;
|
||||
this.values.note += value;
|
||||
return this;
|
||||
};
|
||||
|
||||
override modify = (func: Function): this => {
|
||||
modify = (func: Function): this => {
|
||||
const funcResult = func(this);
|
||||
if (funcResult instanceof Object) {
|
||||
return funcResult;
|
||||
@ -83,7 +83,7 @@ export class MidiEvent extends AudibleEvent {
|
||||
return this;
|
||||
};
|
||||
|
||||
override update = (): this => {
|
||||
update = (): this => {
|
||||
const filteredValues = filterObject(this.values, [
|
||||
"key",
|
||||
"pitch",
|
||||
@ -98,20 +98,20 @@ export class MidiEvent extends AudibleEvent {
|
||||
|
||||
events.forEach((soundEvent) => {
|
||||
const resolvedPitchClass = resolvePitchClass(
|
||||
(soundEvent['key'] || "C4"),
|
||||
(soundEvent['originalPitch'] || soundEvent['pitch'] || 0),
|
||||
(soundEvent['parsedScale'] || soundEvent['scale'] || "MAJOR"),
|
||||
(soundEvent['addedOctave'] || 0)
|
||||
(soundEvent.key || "C4"),
|
||||
(soundEvent.originalPitch || soundEvent.pitch || 0),
|
||||
(soundEvent.parsedScale || soundEvent.scale || "MAJOR"),
|
||||
(soundEvent.addedOctave || 0)
|
||||
);
|
||||
soundEvent['note'] = resolvedPitchClass.note;
|
||||
soundEvent['pitch'] = resolvedPitchClass.pitch;
|
||||
soundEvent['octave'] = resolvedPitchClass.octave;
|
||||
soundEvent.note = resolvedPitchClass.note;
|
||||
soundEvent.pitch = resolvedPitchClass.pitch;
|
||||
soundEvent.octave = resolvedPitchClass.octave;
|
||||
});
|
||||
|
||||
const newArrays = arrayOfObjectsToObjectWithArrays(events) as MidiParams;
|
||||
|
||||
this.values['note'] = maybeAtomic(newArrays.note);
|
||||
if (newArrays.bend) this.values['bend'] = maybeAtomic(newArrays.bend);
|
||||
this.values.note = maybeAtomic(newArrays.note);
|
||||
if (newArrays.bend) this.values.bend = maybeAtomic(newArrays.bend);
|
||||
return this;
|
||||
};
|
||||
|
||||
@ -122,8 +122,8 @@ export class MidiEvent extends AudibleEvent {
|
||||
const note = params.note ? params.note : 60;
|
||||
|
||||
const sustain = params.sustain
|
||||
? params.sustain * event.app.clock.time_position.tick_duration * event.app.api.ppqn()
|
||||
: event.app.clock.time_position.tick_duration * event.app.api.ppqn();
|
||||
? params.sustain * event.app.clock.pulse_duration * event.app.api.ppqn()
|
||||
: event.app.clock.pulse_duration * event.app.api.ppqn();
|
||||
|
||||
const bend = params.bend ? params.bend : undefined;
|
||||
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../main";
|
||||
import { AudibleEvent } from "../Classes/AbstractEvents";
|
||||
import { AudibleEvent } from "./AbstractEvents";
|
||||
import { sendToServer, type OSCMessage } from "../IO/OSC";
|
||||
import {
|
||||
filterObject,
|
||||
@ -292,8 +292,8 @@ export class SoundEvent extends AudibleEvent {
|
||||
self.values["fmi"] = value;
|
||||
} else {
|
||||
let values = value.split(":");
|
||||
self.values["fmi"] = parseFloat(values[0]!);
|
||||
if (values.length > 1) self.values["fmh"] = parseFloat(values[1]!);
|
||||
self.values["fmi"] = parseFloat(values[0]);
|
||||
if (values.length > 1) self.values["fmh"] = parseFloat(values[1]);
|
||||
}
|
||||
return self;
|
||||
},
|
||||
@ -365,7 +365,7 @@ export class SoundEvent extends AudibleEvent {
|
||||
|
||||
constructor(
|
||||
sound: string | string[] | SoundParams,
|
||||
app: Editor,
|
||||
public app: Editor,
|
||||
) {
|
||||
super(app);
|
||||
this.nudge = app.dough_nudge / 100;
|
||||
@ -374,13 +374,25 @@ export class SoundEvent extends AudibleEvent {
|
||||
if (typeof keys === "object" && Symbol.iterator in Object(keys)) {
|
||||
for (const key of keys as string[]) {
|
||||
// Using arrow function to maintain 'this' context
|
||||
this[key] = (value: number) => this.updateValue(keys[0]!, value);
|
||||
this[key] = (value: number) => this.updateValue(keys[0], value);
|
||||
}
|
||||
} else {
|
||||
// @ts-ignore
|
||||
this[methodName] = (...args) => keys(this, ...args);
|
||||
}
|
||||
}
|
||||
|
||||
// for (const [methodName, keys] of Object.entries(SoundEvent.methodMap)) {
|
||||
// if (typeof keys === "object" && Symbol.iterator in Object(keys)) {
|
||||
// for (const key of keys as string[]) {
|
||||
// // @ts-ignore
|
||||
// this[key] = (value: number) => this.updateValue(this, keys[0], value);
|
||||
// }
|
||||
// } else {
|
||||
// // @ts-ignore
|
||||
// this[methodName] = keys;
|
||||
// }
|
||||
// }
|
||||
this.values = this.processSound(sound);
|
||||
}
|
||||
|
||||
@ -388,7 +400,7 @@ export class SoundEvent extends AudibleEvent {
|
||||
// AbstactEvent overrides
|
||||
// ================================================================================
|
||||
|
||||
override modify = (func: Function): this => {
|
||||
modify = (func: Function): this => {
|
||||
const funcResult = func(this);
|
||||
if (funcResult instanceof Object) return funcResult;
|
||||
else {
|
||||
@ -397,7 +409,7 @@ export class SoundEvent extends AudibleEvent {
|
||||
}
|
||||
};
|
||||
|
||||
override update = (): this => {
|
||||
update = (): this => {
|
||||
const filteredValues = filterObject(this.values, [
|
||||
"key",
|
||||
"pitch",
|
||||
@ -412,24 +424,24 @@ export class SoundEvent extends AudibleEvent {
|
||||
]);
|
||||
events.forEach((soundEvent) => {
|
||||
const resolvedPitchClass = resolvePitchClass(
|
||||
(soundEvent['key'] || "C4"),
|
||||
(soundEvent['originalPitch'] || soundEvent['pitch'] || 0),
|
||||
(soundEvent['parsedScale'] || soundEvent['scale'] || "MAJOR"),
|
||||
(soundEvent['paramOctave'] || 0) + (soundEvent['addedOctave'] || 0)
|
||||
(soundEvent.key || "C4"),
|
||||
(soundEvent.originalPitch || soundEvent.pitch || 0),
|
||||
(soundEvent.parsedScale || soundEvent.scale || "MAJOR"),
|
||||
(soundEvent.paramOctave || 0) + (soundEvent.addedOctave || 0)
|
||||
);
|
||||
soundEvent['note'] = resolvedPitchClass.note;
|
||||
soundEvent['freq'] = midiToFreq(resolvedPitchClass.note);
|
||||
soundEvent['pitch'] = resolvedPitchClass.pitch;
|
||||
soundEvent['octave'] = resolvedPitchClass.octave;
|
||||
soundEvent.note = resolvedPitchClass.note;
|
||||
soundEvent.freq = midiToFreq(resolvedPitchClass.note);
|
||||
soundEvent.pitch = resolvedPitchClass.pitch;
|
||||
soundEvent.octave = resolvedPitchClass.octave;
|
||||
});
|
||||
|
||||
const newArrays = arrayOfObjectsToObjectWithArrays(events) as SoundParams;
|
||||
|
||||
this.values['note'] = maybeAtomic(newArrays.note);
|
||||
this.values['freq'] = maybeAtomic(newArrays.freq);
|
||||
this.values['pitch'] = maybeAtomic(newArrays.pitch);
|
||||
this.values['octave'] = maybeAtomic(newArrays.octave);
|
||||
this.values['pitchOctave'] = maybeAtomic(newArrays.pitchOctave);
|
||||
this.values.note = maybeAtomic(newArrays.note);
|
||||
this.values.freq = maybeAtomic(newArrays.freq);
|
||||
this.values.pitch = maybeAtomic(newArrays.pitch);
|
||||
this.values.octave = maybeAtomic(newArrays.octave);
|
||||
this.values.pitchOctave = maybeAtomic(newArrays.pitchOctave);
|
||||
return this;
|
||||
};
|
||||
|
||||
@ -446,13 +458,13 @@ export class SoundEvent extends AudibleEvent {
|
||||
// const filteredEvent = filterObject(event, ["analyze","note","dur","freq","s"]);
|
||||
const filteredEvent = event;
|
||||
// No need for note if there is freq
|
||||
if (filteredEvent['freq']) {
|
||||
delete filteredEvent['note'];
|
||||
if (filteredEvent.freq) {
|
||||
delete filteredEvent.note;
|
||||
}
|
||||
superdough(
|
||||
filteredEvent,
|
||||
0.2,
|
||||
filteredEvent['dur']
|
||||
this.nudge - this.app.clock.deviation,
|
||||
filteredEvent.dur
|
||||
);
|
||||
}
|
||||
};
|
||||
@ -465,19 +477,19 @@ export class SoundEvent extends AudibleEvent {
|
||||
for (const event of events) {
|
||||
const filteredEvent = event;
|
||||
|
||||
let oscAddress = "address" in event ? event['address'] : "/topos";
|
||||
let oscAddress = "address" in event ? event.address : "/topos";
|
||||
oscAddress = oscAddress?.startsWith("/") ? oscAddress : "/" + oscAddress;
|
||||
|
||||
let oscPort = "port" in event ? event['port'] : 57120;
|
||||
let oscPort = "port" in event ? event.port : 57120;
|
||||
|
||||
if (filteredEvent['freq']) {
|
||||
delete filteredEvent['note'];
|
||||
if (filteredEvent.freq) {
|
||||
delete filteredEvent.note;
|
||||
}
|
||||
sendToServer({
|
||||
address: oscAddress,
|
||||
port: oscPort,
|
||||
args: event,
|
||||
timetag: Math.round(Date.now()),
|
||||
timetag: Math.round(Date.now() + (this.nudge - this.app.clock.deviation)),
|
||||
} as OSCMessage);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
import { Chord, Pitch, Rest as ZRest, Ziffers } from "zifferjs";
|
||||
import { Editor } from "../main";
|
||||
import { AbstractEvent } from "../Classes/AbstractEvents";
|
||||
import { SkipEvent } from "../Classes/SkipEvent";
|
||||
import { SoundEvent, SoundParams } from "../Classes/SoundEvent";
|
||||
import { MidiEvent, MidiParams } from "../Classes/MidiEvent";
|
||||
import { RestEvent } from "../Classes/RestEvent";
|
||||
import { AbstractEvent } from "./AbstractEvents";
|
||||
import { SkipEvent } from "./SkipEvent";
|
||||
import { SoundEvent, SoundParams } from "./SoundEvent";
|
||||
import { MidiEvent, MidiParams } from "./MidiEvent";
|
||||
import { RestEvent } from "./RestEvent";
|
||||
import { arrayOfObjectsToObjectWithArrays, isGenerator } from "../Utils/Generic";
|
||||
import { TonnetzSpaces } from "zifferjs/src/tonnetz";
|
||||
import { safeMod } from "zifferjs/src/utils";
|
||||
@ -30,7 +30,7 @@ export class Player extends AbstractEvent {
|
||||
constructor(
|
||||
input: string | number | Generator<number>,
|
||||
options: InputOptions,
|
||||
app: Editor,
|
||||
public app: Editor,
|
||||
zid: string = "",
|
||||
waitTime: number = 0,
|
||||
) {
|
||||
@ -93,7 +93,7 @@ export class Player extends AbstractEvent {
|
||||
|
||||
updateLastCallTime(): void {
|
||||
if (this.notStarted() || this.played) {
|
||||
this.lastCallTime = this.app.clock.grain;
|
||||
this.lastCallTime = this.app.clock.pulses_since_origin;
|
||||
this.played = false;
|
||||
}
|
||||
}
|
||||
@ -121,11 +121,11 @@ export class Player extends AbstractEvent {
|
||||
};
|
||||
|
||||
origin = (): number => {
|
||||
return this.app.clock.grain + 1;
|
||||
return this.app.clock.pulses_since_origin + 1;
|
||||
};
|
||||
|
||||
pulse = (): number => {
|
||||
return this.app.clock.time_position.tick;
|
||||
return this.app.clock.time_position.pulse;
|
||||
};
|
||||
|
||||
beat = (): number => {
|
||||
@ -143,7 +143,7 @@ export class Player extends AbstractEvent {
|
||||
// Check if it's time to play the event
|
||||
areWeThereYet = (): boolean => {
|
||||
// If clock has stopped
|
||||
if (this.app.clock.grain < this.lastCallTime) {
|
||||
if (this.app.clock.pulses_since_origin < this.lastCallTime) {
|
||||
this.app.api.resetAllFromCache();
|
||||
}
|
||||
|
||||
@ -171,11 +171,11 @@ export class Player extends AbstractEvent {
|
||||
this.index = areWeThereYet ? this.index + 1 : this.index;
|
||||
|
||||
if (areWeThereYet && this.notStarted()) {
|
||||
this.initCallTime = this.app.clock.grain;
|
||||
this.initCallTime = this.app.clock.pulses_since_origin;
|
||||
}
|
||||
|
||||
if (this.atTheBeginning()) {
|
||||
this.startCallTime = this.app.clock.grain;
|
||||
this.startCallTime = this.app.clock.pulses_since_origin;
|
||||
}
|
||||
|
||||
return areWeThereYet;
|
||||
@ -191,7 +191,7 @@ export class Player extends AbstractEvent {
|
||||
}
|
||||
}
|
||||
|
||||
public sound(name?: string | string[] | SoundParams | SoundParams[]) {
|
||||
sound(name?: string | string[] | SoundParams | SoundParams[]) {
|
||||
if (this.areWeThereYet()) {
|
||||
this.checkCue();
|
||||
const event = this.next() as Pitch | Chord | ZRest;
|
||||
@ -250,10 +250,9 @@ export class Player extends AbstractEvent {
|
||||
} else {
|
||||
return SkipEvent.createSkipProxy();
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
public midi(value: number | undefined = undefined) {
|
||||
midi(value: number | undefined = undefined) {
|
||||
if (this.areWeThereYet()) {
|
||||
this.checkCue();
|
||||
const event = this.next() as Pitch | Chord | ZRest;
|
||||
@ -283,7 +282,6 @@ export class Player extends AbstractEvent {
|
||||
} else {
|
||||
return SkipEvent.createSkipProxy();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
scale(name: string|number[]) {
|
||||
@ -470,14 +468,13 @@ export class Player extends AbstractEvent {
|
||||
if(typeof value === "string") {
|
||||
const cueTime = this.app.api.cueTimes[value];
|
||||
this.cueName = value;
|
||||
if(cueTime && this.app.clock.grain <= cueTime) {
|
||||
if(cueTime && this.app.clock.pulses_since_origin <= cueTime) {
|
||||
this.waitTime = cueTime;
|
||||
} else {
|
||||
this.waitTime = -1;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
wait(value: number | string | Function) {
|
||||
@ -485,7 +482,7 @@ export class Player extends AbstractEvent {
|
||||
if(typeof value === "string") {
|
||||
const cueTime = this.app.api.cueTimes[value];
|
||||
this.cueName = value;
|
||||
if(cueTime && this.app.clock.grain <= cueTime) {
|
||||
if(cueTime && this.app.clock.pulses_since_origin <= cueTime) {
|
||||
this.waitTime = cueTime;
|
||||
} else if(this.atTheBeginning()){
|
||||
this.waitTime = -1;
|
||||
@ -521,7 +518,7 @@ export class Player extends AbstractEvent {
|
||||
return this;
|
||||
}
|
||||
if (this.atTheBeginning() && this.notStarted()) {
|
||||
const origin = this.app.clock.grain;
|
||||
const origin = this.app.clock.pulses_since_origin;
|
||||
if (origin > 0) {
|
||||
const syncName = typeof value === "function" ? value.name : value;
|
||||
const syncPattern = this.app.api.patternCache.get(syncName) as Player;
|
||||
|
||||
@ -1,218 +0,0 @@
|
||||
// @ts-ignore
|
||||
import { ClockNode } from "./ClockNode";
|
||||
import TransportProcessor from "./ClockProcessor?worker&url";
|
||||
import { Editor } from "../main";
|
||||
|
||||
export interface TimePosition {
|
||||
bpm: number; ppqn: number; time: number;
|
||||
tick: number; beat: number; bar: number;
|
||||
num: number; den: number; grain: number;
|
||||
tick_duration: number;
|
||||
}
|
||||
|
||||
export class Clock {
|
||||
ctx: AudioContext;
|
||||
transportNode: ClockNode | null;
|
||||
time_position: TimePosition;
|
||||
startTime: number | null = null;
|
||||
elapsedTime: number = 0;
|
||||
state: 'running' | 'paused' | 'stopped' = 'stopped';
|
||||
|
||||
constructor(
|
||||
public app: Editor,
|
||||
ctx: AudioContext,
|
||||
) {
|
||||
this.time_position = {
|
||||
bpm: 0,
|
||||
time: 0,
|
||||
ppqn: 0,
|
||||
tick: 0,
|
||||
beat: 0,
|
||||
bar: 0,
|
||||
num: 0,
|
||||
den: 0,
|
||||
grain: 0,
|
||||
tick_duration: 0,
|
||||
};
|
||||
this.transportNode = null;
|
||||
this.ctx = ctx;
|
||||
ctx.audioWorklet
|
||||
.addModule(TransportProcessor)
|
||||
.then((e) => {
|
||||
this.transportNode = new ClockNode(ctx, {}, this.app);
|
||||
this.transportNode.connect(ctx.destination);
|
||||
return e;
|
||||
})
|
||||
.catch((e) => {
|
||||
console.log("Error loading TransportProcessor.js:", e);
|
||||
});
|
||||
}
|
||||
|
||||
public play(): void {
|
||||
if (this.state !== 'running') {
|
||||
this.elapsedTime = 0;
|
||||
this.state = 'running';
|
||||
}
|
||||
this.startTime = performance.now();
|
||||
this.app.api.MidiConnection.sendStartMessage();
|
||||
this.transportNode?.start();
|
||||
}
|
||||
|
||||
public pause(): void {
|
||||
this.state = 'paused';
|
||||
if (this.startTime !== null) {
|
||||
this.elapsedTime += performance.now() - this.startTime;
|
||||
this.startTime = null;
|
||||
}
|
||||
this.app.api.MidiConnection.sendStopMessage();
|
||||
this.transportNode?.pause();
|
||||
}
|
||||
|
||||
public resume(): void {
|
||||
if (this.state === 'stopped' || this.state === 'paused') {
|
||||
this.startTime = performance.now();
|
||||
this.state = 'running';
|
||||
this.app.api.MidiConnection.sendStartMessage();
|
||||
this.transportNode?.start();
|
||||
} else if (this.state === 'running') {
|
||||
this.state = 'paused';
|
||||
if (this.startTime !== null) {
|
||||
this.elapsedTime += performance.now() - this.startTime;
|
||||
this.startTime = null;
|
||||
}
|
||||
this.app.api.MidiConnection.sendStopMessage();
|
||||
this.transportNode?.pause();
|
||||
}
|
||||
}
|
||||
|
||||
public stop(): void {
|
||||
if (this.startTime !== null) {
|
||||
this.elapsedTime += performance.now() - this.startTime;
|
||||
this.startTime = null;
|
||||
}
|
||||
this.state = 'stopped';
|
||||
this.app.api.MidiConnection.sendStopMessage();
|
||||
this.transportNode?.stop();
|
||||
}
|
||||
|
||||
get grain(): number {
|
||||
return this.time_position.grain;
|
||||
}
|
||||
|
||||
get ticks_before_new_bar(): number {
|
||||
/**
|
||||
* This function returns the number of ticks separating the current moment
|
||||
* from the beginning of the next bar.
|
||||
*
|
||||
* @returns number of ticks until next bar
|
||||
*/
|
||||
const ticksMissingFromBeat = this.time_position.ppqn - this.time_position.tick;
|
||||
const beatsMissingFromBar = this.beats_per_bar - this.time_position.beat;
|
||||
return beatsMissingFromBar * this.time_position.ppqn + ticksMissingFromBeat;
|
||||
}
|
||||
|
||||
get next_beat_in_ticks(): number {
|
||||
/**
|
||||
* This function returns the number of ticks separating the current moment
|
||||
* from the beginning of the next beat.
|
||||
*
|
||||
* @returns number of ticks until next beat
|
||||
*/
|
||||
return this.time_position.grain + this.time_position.tick;
|
||||
}
|
||||
|
||||
get beats_per_bar(): number {
|
||||
/**
|
||||
* Returns the number of beats per bar.
|
||||
*/
|
||||
return this.time_position.num;
|
||||
}
|
||||
|
||||
get beats_since_origin(): number {
|
||||
/**
|
||||
* Returns the number of beats since the origin.
|
||||
*
|
||||
* @returns number of beats since origin
|
||||
*/
|
||||
return Math.floor(this.time_position.tick / this.ppqn)
|
||||
}
|
||||
|
||||
get bpm(): number {
|
||||
return this.time_position.bpm;
|
||||
}
|
||||
|
||||
set bpm(bpm: number) {
|
||||
if (bpm > 0 && this.time_position.bpm !== bpm) {
|
||||
this.transportNode?.setBPM(bpm);
|
||||
}
|
||||
}
|
||||
|
||||
get ppqn(): number {
|
||||
return this.time_position.ppqn;
|
||||
}
|
||||
|
||||
set ppqn(ppqn: number) {
|
||||
if (ppqn > 0 && this.ppqn !== ppqn) {
|
||||
this.transportNode?.setPPQN(ppqn);
|
||||
}
|
||||
}
|
||||
|
||||
public nextTickFrom(time: number, nudge: number): number {
|
||||
/**
|
||||
* Compute the time remaining before the next clock tick.
|
||||
* @param time - audio context currentTime
|
||||
* @param nudge - nudge in the future (in seconds)
|
||||
* @returns remainingTime
|
||||
*/
|
||||
const pulseDuration = this.time_position.tick_duration;
|
||||
const nudgedTime = time + nudge;
|
||||
const nextTickTime = Math.ceil(nudgedTime / pulseDuration) * pulseDuration;
|
||||
const remainingTime = nextTickTime - nudgedTime;
|
||||
|
||||
return remainingTime;
|
||||
}
|
||||
|
||||
public convertTicksToTimeposition(n: number): TimePosition {
|
||||
/**
|
||||
* TODO: probably incorrect
|
||||
*/
|
||||
const ppqn = this.time_position.ppqn;
|
||||
const bpm = this.time_position.bpm;
|
||||
const num = this.time_position.num;
|
||||
const den = this.time_position.den;
|
||||
const tick = n % ppqn;
|
||||
const grain = n;
|
||||
const beat = Math.floor(n / ppqn) % num;
|
||||
const bar = Math.floor(n / ppqn / num);
|
||||
const time = n * this.time_position.tick_duration;
|
||||
const tick_duration = this.time_position.tick_duration;
|
||||
return { bpm, ppqn, time, tick, beat, bar, num, den, grain, tick_duration };
|
||||
}
|
||||
|
||||
public convertPulseToSecond(n: number): number {
|
||||
/**
|
||||
* Converts a pulse to a second.
|
||||
*/
|
||||
return n * this.time_position.tick_duration;
|
||||
}
|
||||
|
||||
|
||||
public setSignature(num: number, den: number): void {
|
||||
this.transportNode?.setSignature(num, den);
|
||||
}
|
||||
|
||||
public getElapsed(): number {
|
||||
if (this.startTime === null) {
|
||||
return this.elapsedTime;
|
||||
} else {
|
||||
return this.elapsedTime + (performance.now() - this.startTime);
|
||||
}
|
||||
}
|
||||
|
||||
public getTimeDeviation(grain: number, tick_duration: number): number {
|
||||
const idealTime = grain * tick_duration;
|
||||
const elapsedTime = this.getElapsed();
|
||||
const timeDeviation = elapsedTime - idealTime;
|
||||
return timeDeviation;
|
||||
}
|
||||
}
|
||||
53
src/clock/ClockNode.d.ts
vendored
@ -1,53 +0,0 @@
|
||||
export class TransportNode {
|
||||
constructor(context: AudioContext, something, app: Editor);
|
||||
|
||||
/**
|
||||
* Starts the clock.
|
||||
*/
|
||||
start(): void;
|
||||
|
||||
/**
|
||||
* Stops the clock.
|
||||
*/
|
||||
stop(): void;
|
||||
|
||||
connect(destionation: AudioNode);
|
||||
|
||||
setNudge(nudge: number): void;
|
||||
|
||||
setPPQN(ppq: number): void;
|
||||
|
||||
setBPM(bpm: number): void;
|
||||
|
||||
pause(): void;
|
||||
|
||||
|
||||
/**
|
||||
* Resets the clock to its initial state.
|
||||
*/
|
||||
reset(): void;
|
||||
|
||||
/**
|
||||
* Sets the interval at which the clock updates.
|
||||
* @param interval The interval in milliseconds.
|
||||
*/
|
||||
setInterval(interval: number): void;
|
||||
|
||||
/**
|
||||
* Gets the current time of the clock.
|
||||
* @returns The current time as a number.
|
||||
*/
|
||||
getTime(): number;
|
||||
}
|
||||
|
||||
export interface ClockNodeConfig {
|
||||
/**
|
||||
* The initial time for the clock.
|
||||
*/
|
||||
startTime?: number;
|
||||
|
||||
/**
|
||||
* The interval in milliseconds at which the clock should update.
|
||||
*/
|
||||
updateInterval?: number;
|
||||
}
|
||||
@ -1,80 +0,0 @@
|
||||
import { tryEvaluate } from "../Evaluator";
|
||||
|
||||
export class ClockNode extends AudioWorkletNode {
|
||||
|
||||
constructor(context, options, application) {
|
||||
super(context, "transport", options);
|
||||
this.port.addEventListener("message", this.handleMessage);
|
||||
this.port.start();
|
||||
this.app = application;
|
||||
this.domUpdateFrequency = this.app.clock.ppqn;
|
||||
}
|
||||
|
||||
/** @type {(this: MessagePort, ev: MessageEvent<any>) => any} */
|
||||
handleMessage = (message) => {
|
||||
let clock = this.app.clock;
|
||||
if (message.data.type === "time") {
|
||||
clock.time_position = {
|
||||
bpm: message.data.bpm,
|
||||
ppqn: message.data.ppqn,
|
||||
time: message.data.time,
|
||||
tick: message.data.tick,
|
||||
beat: message.data.beat,
|
||||
bar: message.data.bar,
|
||||
num: message.data.num,
|
||||
den: message.data.den,
|
||||
grain: message.data.grain,
|
||||
tick_duration: message.data.tick_duration,
|
||||
}
|
||||
this.app.settings.send_clock ?? this.app.api.MidiConnection.sendMidiClock();
|
||||
this.updateTransportViewer();
|
||||
tryEvaluate(
|
||||
this.app,
|
||||
this.app.exampleIsPlaying
|
||||
? this.app.example_buffer
|
||||
: this.app.global_buffer
|
||||
);
|
||||
}
|
||||
};
|
||||
updateTransportViewer() {
|
||||
const { bar, beat, tick } = this.app.clock.time_position;
|
||||
const paddedBar = String(bar).padStart(2, '0');
|
||||
const paddedBeat = String(beat).padStart(2, '0');
|
||||
const paddedTick = String(tick).padStart(2, '0');
|
||||
requestAnimationFrame(() => {
|
||||
this.app.interface.transport_viewer.innerHTML = `<span class="text-xl text-neutral">${paddedBar}:${paddedBeat}:${paddedTick}</span>`;
|
||||
});
|
||||
}
|
||||
|
||||
start() {
|
||||
this.port.postMessage({ type: "start" });
|
||||
}
|
||||
|
||||
pause() {
|
||||
this.port.postMessage({ type: "pause" });
|
||||
}
|
||||
|
||||
resume() {
|
||||
this.port.postMessage({ type: "resume" });
|
||||
}
|
||||
|
||||
setBPM(bpm) {
|
||||
this.port.postMessage({ type: "bpm", value: bpm });
|
||||
}
|
||||
|
||||
setPPQN(ppqn) {
|
||||
this.port.postMessage({ type: "ppqn", value: ppqn });
|
||||
}
|
||||
|
||||
setSignature(num, den) {
|
||||
this.port.postMessage({ type: "timeSignature", num: num, den: den });
|
||||
}
|
||||
|
||||
setNudge(nudge) {
|
||||
this.port.postMessage({ type: "nudge", value: nudge });
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.port.postMessage({ type: "stop" });
|
||||
}
|
||||
}
|
||||
@ -1,100 +0,0 @@
|
||||
class TransportProcessor extends AudioWorkletProcessor {
|
||||
constructor(options) {
|
||||
super(options);
|
||||
this.port.addEventListener("message", this.handleMessage);
|
||||
this.bpm = 120;
|
||||
this.nudge = 0;
|
||||
this.started = false;
|
||||
this.ppqn = 48 * 2;
|
||||
this.timeSignature = [4, 4];
|
||||
this.port.start();
|
||||
this.currentPulsePosition = 0;
|
||||
this.startTime = 0;
|
||||
this.pauseTime = 0;
|
||||
this.grain = 0;
|
||||
this.totalPauseTime = 0;
|
||||
}
|
||||
|
||||
handleMessage = (message) => {
|
||||
if (message.data && message.data.type === "ping") {
|
||||
this.port.postMessage(message.data);
|
||||
} else if (message.data.type === "start") {
|
||||
this.started = true;
|
||||
if (this.pauseTime) {
|
||||
this.totalPauseTime += currentTime - this.pauseTime;
|
||||
this.pauseTime = null;
|
||||
} else {
|
||||
this.startTime = currentTime
|
||||
}
|
||||
} else if (message.data.type === "pause") {
|
||||
this.started = false;
|
||||
this.pauseTime = currentTime;
|
||||
} else if (message.data.type === "stop") {
|
||||
this.started = false;
|
||||
this.startTime = 0;
|
||||
this.pauseTime = 0;
|
||||
this.totalPauseTime = 0;
|
||||
this.currentPulsePosition = 0;
|
||||
this.grain = 0;
|
||||
} else if (message.data.type === "bpm") {
|
||||
this.bpm = message.data.value;
|
||||
this.startTime = currentTime;
|
||||
this.currentPulsePosition = 0;
|
||||
} else if (message.data.type === "ppqn") {
|
||||
this.ppqn = message.data.value;
|
||||
this.startTime = currentTime;
|
||||
this.currentPulsePosition = 0;
|
||||
} else if (message.data.type === "timeSignature") {
|
||||
this.timeSignature = [
|
||||
message.data.num,
|
||||
message.data.den
|
||||
]
|
||||
} else if (message.data.type === "nudge") {
|
||||
this.nudge = message.data.value;
|
||||
} else if (message.data.type === "timeSignature") {
|
||||
this.timeSignature = message.data.value;
|
||||
}
|
||||
};
|
||||
|
||||
process() {
|
||||
if (this.started) {
|
||||
const adjustedCurrentTime = (currentTime - this.startTime) + this.nudge / 100;
|
||||
const beatNumber = adjustedCurrentTime / (60 / this.bpm);
|
||||
const currentPulsePosition = Math.round(beatNumber * this.ppqn);
|
||||
|
||||
if (currentPulsePosition > this.currentPulsePosition) {
|
||||
this.grain += 1;
|
||||
this.currentPulsePosition = currentPulsePosition;
|
||||
|
||||
// Calculate current tick, beat, and bar
|
||||
const ticksPerBeat = this.ppqn;
|
||||
const beatsPerBar = this.timeSignature[0];
|
||||
const ticksPerBar = ticksPerBeat * beatsPerBar;
|
||||
|
||||
const currentTick = this.currentPulsePosition % ticksPerBeat;
|
||||
const currentBeat = Math.floor(this.currentPulsePosition / ticksPerBeat) % beatsPerBar;
|
||||
const currentBar = Math.floor(this.currentPulsePosition / ticksPerBar);
|
||||
|
||||
this.port.postMessage({
|
||||
bpm: this.bpm,
|
||||
ppqn: this.ppqn,
|
||||
type: 'time',
|
||||
//time: currentTime,
|
||||
time: adjustedCurrentTime,
|
||||
tick: currentTick,
|
||||
beat: currentBeat,
|
||||
bar: currentBar,
|
||||
bpm: this.bpm,
|
||||
num: this.timeSignature[0],
|
||||
den: this.timeSignature[1],
|
||||
grain: this.grain,
|
||||
tick_duration: 60 / this.bpm / this.ppqn,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor("transport", TransportProcessor);
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const atelier = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory, key_shortcut } from "../Documentation";
|
||||
import { makeExampleFactory, key_shortcut } from "../../Documentation";
|
||||
|
||||
export const code = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -31,8 +31,8 @@ The code you enter in any of the scripts is evaluated in strict mode. This tells
|
||||
There are some techniques to keep code short and tidy. Don't try to write the shortest possible code! Use shortcuts when it makes sense. Take a look at the following examples:
|
||||
|
||||
${makeExample(
|
||||
"Shortening your if conditions",
|
||||
`
|
||||
"Shortening your if conditions",
|
||||
`
|
||||
// The && symbol (overriden by :: in Topos) is very often used for conditions!
|
||||
beat(.75) :: snd('linnhats').n([1,4,5].beat()).out()
|
||||
beat(1) :: snd('bd').out()
|
||||
@ -42,42 +42,42 @@ beat(1) :: snd('bd').out()
|
||||
//// beat(1) :: snd('bd').out()
|
||||
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"More complex conditions using ?",
|
||||
`
|
||||
"More complex conditions using ?",
|
||||
`
|
||||
// The ? symbol can be used to write a if/true/false condition
|
||||
beat(4) ? snd('kick').out() : beat(2) :: snd('snare').out()
|
||||
// (true) ? log('very true') : log('very false')
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Using not and other short symbols",
|
||||
`
|
||||
"Using not and other short symbols",
|
||||
`
|
||||
// The ! symbol can be used to reverse a condition
|
||||
beat(4) ? snd('kick').out() : beat(2) :: snd('snare').out()
|
||||
!beat(2) :: beat(0.5) :: snd('clap').out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
# About crashes and bugs
|
||||
|
||||
Things will crash! It's part of the show! You will learn progressively to avoid mistakes and to write safer code. Do not hesitate to kill the page or to stop the transport if you feel overwhelmed by an algorithm blowing up. There is no safeguard to stop you from doing most things. This is to ensure that you have all the available possible room to write bespoke code and experiment with your ideas through code.
|
||||
|
||||
${makeExample(
|
||||
"This example will crash! Who cares?",
|
||||
`
|
||||
"This example will crash! Who cares?",
|
||||
`
|
||||
// This is crashing. See? No harm!
|
||||
qjldfqsdklqsjdlkqjsdlqkjdlksjd
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
`;
|
||||
};
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
// @ts-ignore
|
||||
export const interaction = (application: Editor): string => {
|
||||
@ -1,4 +1,4 @@
|
||||
import { key_shortcut, makeExampleFactory } from "../Documentation";
|
||||
import { key_shortcut, makeExampleFactory } from "../../Documentation";
|
||||
import { type Editor } from "../../main";
|
||||
import topos_arch from "./topos_arch.svg";
|
||||
import many_universes from "./many_universes.svg";
|
||||
@ -38,24 +38,24 @@ Every Topos session is composed of **local**, **global** and **init** scripts. T
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Calling scripts to form a musical piece",
|
||||
`
|
||||
"Calling scripts to form a musical piece",
|
||||
`
|
||||
beat(1) :: script(1) // Calling local script n°1
|
||||
flip(4) :: beat(.5) :: script(2) // Calling script n°2
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Script execution can become musical too!",
|
||||
`
|
||||
"Script execution can become musical too!",
|
||||
`
|
||||
// Use algorithms to pick a script.
|
||||
beat(1) :: script([1, 3, 5].pick())
|
||||
flip(4) :: beat([.5, .25].beat(16)) :: script(
|
||||
[5, 6, 7, 8].beat())
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
### Navigating the interface
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { key_shortcut } from "../Documentation";
|
||||
import { key_shortcut } from "../../Documentation";
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const shortcuts = (app: Editor): string => {
|
||||
let makeExample = makeExampleFactory(app);
|
||||
@ -69,12 +69,12 @@ By pressing the ${key_shortcut(
|
||||
)} when playing this example:
|
||||
|
||||
${makeExample(
|
||||
"Claping twice as fast with fill",
|
||||
`
|
||||
"Claping twice as fast with fill",
|
||||
`
|
||||
beat(fill() ? 1/4 : 1/2)::sound('cp').out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
`;
|
||||
};
|
||||
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 20 KiB |
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const mouse = (app: Editor): string => {
|
||||
let makeExample = makeExampleFactory(app);
|
||||
@ -16,8 +16,8 @@ You can get the current position of the mouse on the screen by using the followi
|
||||
- <ic>mouseY()</ic>: the vertical position of the mouse on the screen (as a floating point number).
|
||||
|
||||
${makeExample(
|
||||
"Vibrato controlled by mouse",
|
||||
`
|
||||
"Vibrato controlled by mouse",
|
||||
`
|
||||
beat(.25) :: sound('sine')
|
||||
.note([0,4,5,10,11,15,16]
|
||||
.palindrome()
|
||||
@ -27,8 +27,8 @@ beat(.25) :: sound('sine')
|
||||
.pan(r(0, 1))
|
||||
.room(0.35).size(4).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
<br>
|
||||
|
||||
@ -39,15 +39,15 @@ Current mouse position can also be used to generate notes:
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Using the mouse to output a note!",
|
||||
`
|
||||
"Using the mouse to output a note!",
|
||||
`
|
||||
beat(.25) :: sound('sine')
|
||||
.lpf(7000)
|
||||
.delay(0.5).delayt(1/6).delayfb(0.2)
|
||||
.note(noteX())
|
||||
.room(0.35).size(4).out()`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Mouse and Arrays
|
||||
|
||||
@ -58,14 +58,14 @@ You can use the mouse to explore the valuesq contained in an Array:
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Taking values out of an Array with the mouse",
|
||||
`
|
||||
"Taking values out of an Array with the mouse",
|
||||
`
|
||||
log([1,2,3,4].mouseX())
|
||||
log([4,5,6,7].mouseY())
|
||||
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
@ -1,6 +1,6 @@
|
||||
import { makeExampleFactory, key_shortcut } from "../Documentation";
|
||||
import { makeExampleFactory, key_shortcut } from "../../Documentation";
|
||||
import { type Editor } from "../../main";
|
||||
import { examples } from "../excerpts";
|
||||
import { examples } from "../../examples/excerpts";
|
||||
|
||||
export const introduction = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -940,7 +940,7 @@ const completionDatabase: CompletionDatabase = {
|
||||
description: "Noise amount in the signal (0-1)",
|
||||
example: "sound('triangle').noise(.25).out()",
|
||||
},
|
||||
} as const;
|
||||
};
|
||||
|
||||
export const inlineHoveringTips = hoverTooltip(
|
||||
(view: any, pos: any, side: any) => {
|
||||
@ -962,7 +962,8 @@ export const inlineHoveringTips = hoverTooltip(
|
||||
) {
|
||||
return { dom: document.createElement("div") };
|
||||
}
|
||||
let completion = completionDatabase[text.slice(start - from, end - from)]!;
|
||||
let completion =
|
||||
completionDatabase[text.slice(start - from, end - from)] || {};
|
||||
let divContent = `
|
||||
<h1 class="text-brightwhite text-base pb-1">${completion.name} [<em class="text-white">${completion.category}</em>]</h1>
|
||||
<p class="text-base pl-4">${completion.description}</p>
|
||||
@ -985,13 +986,13 @@ export const toposCompletions = (context: CompletionContext) => {
|
||||
from: word.from,
|
||||
options: Object.keys(completionDatabase).map((key) => ({
|
||||
label: key,
|
||||
type: completionDatabase[key]!.category,
|
||||
type: completionDatabase[key].category,
|
||||
info: () => {
|
||||
let div = document.createElement("div");
|
||||
div.innerHTML = `
|
||||
<h1 class="text-brightwhite text-base pb-1">${completionDatabase[key]!.name} [<em class="text-white">${completionDatabase[key]!.category}</em>]</h1>
|
||||
<p class="text-base pl-4">${completionDatabase[key]!.description}</p>
|
||||
<div class="overflow-hidden overflow-scroll rounded px-2 ml-4 mt-2 bg-neutral-800"><code class="text-sm">${completionDatabase[key]!.example}</code></div>
|
||||
<h1 class="text-brightwhite text-base pb-1">${completionDatabase[key].name} [<em class="text-white">${completionDatabase[key].category}</em>]</h1>
|
||||
<p class="text-base pl-4">${completionDatabase[key].description}</p>
|
||||
<div class="overflow-hidden overflow-scroll rounded px-2 ml-4 mt-2 bg-neutral-800"><code class="text-sm">${completionDatabase[key].example}</code></div>
|
||||
`;
|
||||
div.classList.add("px-4", "py-2", "rounded-lg", "w-92");
|
||||
return div;
|
||||
@ -999,7 +1000,6 @@ export const toposCompletions = (context: CompletionContext) => {
|
||||
})),
|
||||
};
|
||||
}
|
||||
return null
|
||||
};
|
||||
|
||||
export const soundCompletions = (context: CompletionContext) => {
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const amplitude = (application: Editor): string => {
|
||||
// @ts-ignore
|
||||
@ -17,11 +17,11 @@ Controlling the volume is probably the most important concept you need to know a
|
||||
| <ic>dbgain</ic> | db | Attenuation in dB from <ic>-inf</ic> to <ic>+10</ic> (acts as a sound mixer fader).|
|
||||
|
||||
${makeExample(
|
||||
"Velocity manipulated by a counter",
|
||||
`
|
||||
"Velocity manipulated by a counter",
|
||||
`
|
||||
beat(.5)::snd('cp').vel($(1)%10 / 10).out()`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Amplitude Enveloppe
|
||||
|
||||
@ -38,8 +38,8 @@ beat(.5)::snd('cp').vel($(1)%10 / 10).out()`,
|
||||
Note that the **sustain** value is not a duration but an amplitude value (how loud). The other values are the time for each stage to take place. Here is a fairly complete example using the <ic>sawtooth</ic> basic waveform.
|
||||
|
||||
${makeExample(
|
||||
"Simple synthesizer",
|
||||
`
|
||||
"Simple synthesizer",
|
||||
`
|
||||
register("smooth", x => x.cutoff(r(100,500))
|
||||
.lpadsr(usaw(1/8) * 8, 0.05, .125, 0, 0)
|
||||
.gain(r(0.25, 0.4)).adsr(0, r(.2,.4), r(0,0.5), 0)
|
||||
@ -51,15 +51,15 @@ beat(.25)::sound('sawtooth')
|
||||
.note([50,57,55,60].add(12).beat(1.5))
|
||||
.smooth().out();
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
Sometimes, using a full ADSR envelope is a bit overkill. There are other simpler controls to manipulate the envelope like the <ic>.ad</ic> method:
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Replacing .adsr by .ad",
|
||||
`
|
||||
"Replacing .adsr by .ad",
|
||||
`
|
||||
register("smooth", x => x.cutoff(r(100,500))
|
||||
.lpadsr(usaw(1/8) * 8, 0.05, .125, 0, 0)
|
||||
.gain(r(0.25, 0.4)).ad(0, 0.25)
|
||||
@ -71,8 +71,8 @@ beat(.25)::sound('sawtooth')
|
||||
.note([50,57,55,60].add(12).beat(1.5))
|
||||
.smooth().out();
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
`;
|
||||
};
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const audio_basics = (application: Editor): string => {
|
||||
// @ts-ignore
|
||||
@ -17,13 +17,13 @@ Use the <ic>sound(name: string)</ic> function to play a sound. You can also writ
|
||||
Whatever you choose, the syntax stays the same. See the following example:
|
||||
|
||||
${makeExample(
|
||||
"Playing sounds is easy",
|
||||
`
|
||||
"Playing sounds is easy",
|
||||
`
|
||||
beat(1) && sound('bd').out()
|
||||
beat(0.5) && sound('hh').out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
These commands, in plain english, can be translated to:
|
||||
|
||||
@ -33,13 +33,13 @@ These commands, in plain english, can be translated to:
|
||||
Let's make this example a bit more complex:
|
||||
|
||||
${makeExample(
|
||||
"Adding some effects",
|
||||
`
|
||||
"Adding some effects",
|
||||
`
|
||||
beat(1) && sound('bd').coarse(0.25).room(0.5).orbit(2).out();
|
||||
beat(0.5) && sound('hh').delay(0.25).delaytime(0.125).out();
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
Now, it translates as follows:
|
||||
|
||||
@ -54,13 +54,13 @@ If you remove <ic>beat</ic> instruction, you will end up with a deluge of kick d
|
||||
To play a sound, you always need the <ic>.out()</ic> method at the end of your chain. THis method tells **Topos** to send the chain to the audio engine. The <ic>.out</ic> method can take an optional argument to send the sound to a numbered effect bus, from <ic>0</ic> to <ic>n</ic> :
|
||||
|
||||
${makeExample(
|
||||
"Using the .out method",
|
||||
`
|
||||
"Using the .out method",
|
||||
`
|
||||
// Playing a clap on the third bus (0-indexed)
|
||||
beat(1)::sound('cp').out(2)
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
Try to remove <ic>.out</ic>. You will see that no sound is playing at all!
|
||||
|
||||
@ -69,16 +69,16 @@ Try to remove <ic>.out</ic>. You will see that no sound is playing at all!
|
||||
- Sounds are **composed** by adding qualifiers/parameters that modify the sound or synthesizer you have picked (_e.g_ <ic>sound('...').blabla(...)..something(...).out()</ic>. Think of it as _audio chains_.
|
||||
|
||||
${makeExample(
|
||||
"Complex sonic object",
|
||||
`
|
||||
"Complex sonic object",
|
||||
`
|
||||
beat(1) :: sound('pad').n(1)
|
||||
.begin(rand(0, 0.4))
|
||||
.freq([50,52].beat())
|
||||
.size(0.9).room(0.9)
|
||||
.velocity(0.25)
|
||||
.pan(usine()).release(2).out()`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Picking a specific sound
|
||||
|
||||
@ -102,12 +102,12 @@ If you choose the sound <ic>kick</ic>, you are asking for the first sample in th
|
||||
|
||||
The <ic>.n(number)</ic> method can be used to pick a sample from the currently selected sample folder. For instance, the following script will play a random sample from the _kick_ folder:
|
||||
${makeExample(
|
||||
"Picking a sample",
|
||||
`
|
||||
"Picking a sample",
|
||||
`
|
||||
beat(1) && sound('kick').n([1,2,3,4,5,6,7,8].pick()).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
You can also use the <ic>:</ic> to pick a sample number directly from the <ic>sound</ic> function:
|
||||
|
||||
@ -122,12 +122,12 @@ beat(1) && sound('kick:3').out()
|
||||
You can use any number to pick a sound. Don't be afraid of using a number too big. If the number exceeds the number of available samples, it will simply wrap around and loop infinitely over the folder. Let's demonstrate this by using the mouse over a very large sample folder:
|
||||
|
||||
${makeExample(
|
||||
"Picking a sample... with the mouse!",
|
||||
`
|
||||
"Picking a sample... with the mouse!",
|
||||
`
|
||||
// Move your mouse to change the sample being used!
|
||||
beat(.25) && sound('ST09').n(Math.floor(mouseX())).out()`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
The <ic>.n</ic> method is also used for synthesizers but it behaves differently. When using a synthesizer, this method can help you determine the number of harmonics in your waveform. See the **Synthesizers** section to learn more about this.
|
||||
@ -150,8 +150,8 @@ There is a special method to choose the _orbit_ that your sound is going to use:
|
||||
You can play a sound _dry_ and another sound _wet_. Take a look at this example where the reverb is only affecting one of the sounds:
|
||||
|
||||
${makeExample(
|
||||
"Dry and wet",
|
||||
`
|
||||
"Dry and wet",
|
||||
`
|
||||
|
||||
// This sound is dry
|
||||
beat(1)::sound('hh').out()
|
||||
@ -159,23 +159,23 @@ beat(1)::sound('hh').out()
|
||||
// This sound is wet (reverb)
|
||||
beat(2)::sound('cp').orbit(2).room(0.5).size(8).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## The art of chaining
|
||||
|
||||
Learning to create complex chains is very important when using **Topos**. It can take some time to learn all the possible parameters. Don't worry, it's actually rather easy to learn.
|
||||
|
||||
${makeExample(
|
||||
"Complex chain",
|
||||
`
|
||||
"Complex chain",
|
||||
`
|
||||
beat(0.25) && sound('fhh')
|
||||
.sometimes(s=>s.speed([2, 0.5].pick()))
|
||||
.room(0.9).size(0.9).gain(1)
|
||||
.cutoff(usine(1/2) * 5000)
|
||||
.out()`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
Most audio parameters can be used both for samples and synthesizers. This is quite unconventional if you are familiar with a more traditional music software.
|
||||
`;
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const distortion = (application: Editor): string => {
|
||||
// @ts-ignore
|
||||
@ -18,13 +18,13 @@ Three additional effects that are easy enough to understand. These effects are d
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Crunch... crunch... crunch!",
|
||||
`
|
||||
"Crunch... crunch... crunch!",
|
||||
`
|
||||
beat(.5)::snd('pad').coarse($(1) % 16).clip(.5).out(); // Comment me
|
||||
beat(.5)::snd('pad').crush([16, 8, 4].beat(2)).clip(.5).out()
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
`;
|
||||
};
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const effects = (application: Editor): string => {
|
||||
// @ts-ignore
|
||||
@ -24,12 +24,12 @@ For that reason, it is often a good idea to set fixed reverb values per orbit. D
|
||||
| <ic>roomdim</ic> | | Reverb lowpass frequency at -60db (in hertz) |
|
||||
|
||||
${makeExample(
|
||||
"Clapping in the cavern",
|
||||
`
|
||||
"Clapping in the cavern",
|
||||
`
|
||||
beat(2)::snd('cp').room(0.5).size(4).out()
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
## Delay
|
||||
|
||||
@ -42,13 +42,13 @@ A good sounding delay unit that can go into feedback territory. Use it without m
|
||||
| <ic>delayfeedback</ic> | delayfb | Delay feedback (between <ic>0</ic> and <ic>1</ic>) |
|
||||
|
||||
${makeExample(
|
||||
"Who doesn't like delay?",
|
||||
`
|
||||
"Who doesn't like delay?",
|
||||
`
|
||||
beat(2)::snd('cp').delay(0.5).delaytime(0.75).delayfb(0.8).out()
|
||||
beat(4)::snd('snare').out()
|
||||
beat(1)::snd('kick').out()`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Phaser
|
||||
|
||||
@ -60,16 +60,16 @@ beat(1)::snd('kick').out()`,
|
||||
| <ic>phaserCenter</ic> | <ic>phascenter</ic> | Phaser center frequency (default to 1000) |
|
||||
|
||||
${makeExample(
|
||||
"Super cool phaser lick",
|
||||
`
|
||||
"Super cool phaser lick",
|
||||
`
|
||||
rhythm(.5, 7, 8)::sound('wt_stereo')
|
||||
.phaser(0.75).phaserSweep(3000)
|
||||
.phaserCenter(1500).phaserDepth(1)
|
||||
.note([0, 1, 2, 3, 4, 5, 6].scale('pentatonic', 50).beat(0.25))
|
||||
.room(0.5).size(4).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Distorsion, saturation, destruction
|
||||
|
||||
@ -83,29 +83,29 @@ Three additional effects that are easy enough to understand. These effects are d
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Crunch... crunch... crunch!",
|
||||
`
|
||||
"Crunch... crunch... crunch!",
|
||||
`
|
||||
beat(.5)::snd('pad').coarse($(1) % 16).clip(.5).out(); // Comment me
|
||||
beat(.5)::snd('pad').crush([16, 8, 4].beat(2)).clip(.5).out()
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
## Vibrato
|
||||
|
||||
You can also add some amount of vibrato to the sound using the <ic>vib</ic> and <ic>vibmod</ic> methods. These can turn any oscillator into something more lively and/or into a sound effect when used with a high amount of modulation.
|
||||
|
||||
${makeExample(
|
||||
"Different vibrato settings",
|
||||
`
|
||||
"Different vibrato settings",
|
||||
`
|
||||
tempo(140);
|
||||
beat(1) :: sound('triangle')
|
||||
.freq(400).release(0.2)
|
||||
.vib([1/2, 1, 2, 4].beat())
|
||||
.vibmod([1,2,4,8].beat(2))
|
||||
.out()`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Compression
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const filters = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -13,10 +13,10 @@ Filters can be applied to both synthesizers and samples. They are used to shape
|
||||
- **bandpass filter**: filters the low and high frequencies around a frequency band, keeping what's in the middle.
|
||||
|
||||
${makeExample(
|
||||
"Filtering the high frequencies of an oscillator",
|
||||
`beat(.5) :: sound('sawtooth').cutoff(50 + usine(1/8) * 2000).out()`,
|
||||
true,
|
||||
)}
|
||||
"Filtering the high frequencies of an oscillator",
|
||||
`beat(.5) :: sound('sawtooth').cutoff(50 + usine(1/8) * 2000).out()`,
|
||||
true,
|
||||
)}
|
||||
|
||||
These filters all come with their own set of parameters. Note that we are describing the parameters of the three different filter types here. Choose the right parameters depending on the filter type you are using:
|
||||
|
||||
@ -29,10 +29,10 @@ These filters all come with their own set of parameters. Note that we are descri
|
||||
| <ic>resonance</ic> | <ic>lpq</ic> | resonance of the lowpass filter (0-1) |
|
||||
|
||||
${makeExample(
|
||||
"Filtering a bass",
|
||||
`beat(.5) :: sound('jvbass').lpf([250,1000,8000].beat()).out()`,
|
||||
true,
|
||||
)}
|
||||
"Filtering a bass",
|
||||
`beat(.5) :: sound('jvbass').lpf([250,1000,8000].beat()).out()`,
|
||||
true,
|
||||
)}
|
||||
|
||||
### Highpass filter
|
||||
|
||||
@ -42,10 +42,10 @@ ${makeExample(
|
||||
| <ic>hresonance</ic> | <ic>hpq</ic> | resonance of the highpass filter (0-1) |
|
||||
|
||||
${makeExample(
|
||||
"Filtering a noise source",
|
||||
`beat(.5) :: sound('gtr').hpf([250,1000, 2000, 3000, 4000].beat()).end(0.5).out()`,
|
||||
true,
|
||||
)}
|
||||
"Filtering a noise source",
|
||||
`beat(.5) :: sound('gtr').hpf([250,1000, 2000, 3000, 4000].beat()).end(0.5).out()`,
|
||||
true,
|
||||
)}
|
||||
|
||||
### Bandpass filter
|
||||
|
||||
@ -55,10 +55,10 @@ ${makeExample(
|
||||
| <ic>bandq</ic> | <ic>bpq</ic> | resonance of the bandpass filter (0-1) |
|
||||
|
||||
${makeExample(
|
||||
"Sweeping the filter on the same guitar sample",
|
||||
`beat(.5) :: sound('gtr').bandf(100 + usine(1/8) * 4000).end(0.5).out()`,
|
||||
true,
|
||||
)}
|
||||
"Sweeping the filter on the same guitar sample",
|
||||
`beat(.5) :: sound('gtr').bandf(100 + usine(1/8) * 4000).end(0.5).out()`,
|
||||
true,
|
||||
)}
|
||||
|
||||
Alternatively, <ic>lpf</ic>, <ic>hpf</ic> and <ic>bpf</ic> can take a second argument, the **resonance**.
|
||||
|
||||
@ -69,10 +69,10 @@ You can also use the <ic>ftype</ic> method to change the filter type (order). Th
|
||||
- <ic>ftype(type: string)</ic>: sets the filter type (order), either <ic>12db</ic> or <ic>24db</ic>.
|
||||
|
||||
${makeExample(
|
||||
"Filtering a bass",
|
||||
`beat(.5) :: sound('jvbass').ftype(['12db', '24db'].beat(4)).lpf([250,1000,8000].beat()).out()`,
|
||||
true,
|
||||
)}
|
||||
"Filtering a bass",
|
||||
`beat(.5) :: sound('jvbass').ftype(['12db', '24db'].beat(4)).lpf([250,1000,8000].beat()).out()`,
|
||||
true,
|
||||
)}
|
||||
|
||||
## Filter envelopes
|
||||
|
||||
@ -91,12 +91,12 @@ The examples we have studied so far are static. They filter the sound around a f
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Filtering a sawtooth wave dynamically",
|
||||
`beat(.5) :: sound('sawtooth').note([48,60].beat())
|
||||
"Filtering a sawtooth wave dynamically",
|
||||
`beat(.5) :: sound('sawtooth').note([48,60].beat())
|
||||
.cutoff(5000).lpa([0.05, 0.25, 0.5].beat(2))
|
||||
.lpenv(-8).lpq(10).out()`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
### Highpass envelope
|
||||
|
||||
@ -111,12 +111,12 @@ ${makeExample(
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Let's use another filter using the same example",
|
||||
`beat(.5) :: sound('sawtooth').note([48,60].beat())
|
||||
"Let's use another filter using the same example",
|
||||
`beat(.5) :: sound('sawtooth').note([48,60].beat())
|
||||
.hcutoff(1000).hpa([0.05, 0.25, 0.5].beat(2))
|
||||
.hpenv(8).hpq(10).out()`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
### Bandpass envelope
|
||||
|
||||
@ -131,14 +131,14 @@ ${makeExample(
|
||||
|
||||
|
||||
${makeExample(
|
||||
"And the bandpass filter, just for fun",
|
||||
`beat(.5) :: sound('sawtooth').note([48,60].beat())
|
||||
"And the bandpass filter, just for fun",
|
||||
`beat(.5) :: sound('sawtooth').note([48,60].beat())
|
||||
.bandf([500,1000,2000].beat(2))
|
||||
.bpa([0.25, 0.125, 0.5].beat(2) * 4)
|
||||
.bpenv(-4).release(2).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
`;
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const sampler = (application: Editor): string => {
|
||||
// @ts-ignore
|
||||
@ -28,8 +28,8 @@ The sampler is a rather complex beast. There is a lot you can do by manipulating
|
||||
Let's apply some of these methods naïvely. We will then break everything using simpler examples.
|
||||
|
||||
${makeExample(
|
||||
"Complex sampling duties",
|
||||
`
|
||||
"Complex sampling duties",
|
||||
`
|
||||
// Using some of the modifiers described above :)
|
||||
beat(.5)::snd('pad').begin(0.2)
|
||||
.speed([1, 0.9, 0.8].beat(4))
|
||||
@ -38,8 +38,8 @@ beat(.5)::snd('pad').begin(0.2)
|
||||
.room(0.8).size(0.5)
|
||||
.clip(1).out()
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
|
||||
## Playback speed / pitching samples
|
||||
@ -47,37 +47,37 @@ beat(.5)::snd('pad').begin(0.2)
|
||||
Let's play with the <ic>speed</ic> parameter to control the pitch of sample playback:
|
||||
|
||||
${makeExample(
|
||||
"Controlling the playback speed",
|
||||
`
|
||||
"Controlling the playback speed",
|
||||
`
|
||||
beat(0.5)::sound('notes')
|
||||
.speed([1,2,3,4].palindrome().beat(0.5)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
It also works by using negative values. It reverses the playback:
|
||||
|
||||
${makeExample(
|
||||
"Playing samples backwards",
|
||||
`
|
||||
"Playing samples backwards",
|
||||
`
|
||||
beat(0.5)::sound('notes')
|
||||
.speed(-[1,2,3,4].palindrome().beat(0.5)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
Of course you can play melodies using samples:
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Playing melodies using samples",
|
||||
`
|
||||
"Playing melodies using samples",
|
||||
`
|
||||
beat(0.5)::sound('notes')
|
||||
.room(0.5).size(4)
|
||||
.note([0, 2, 3, 4, 5].scale('minor', 50).beat(0.5)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Panning
|
||||
|
||||
@ -85,14 +85,14 @@ To pan samples, use the <ic>.pan</ic> method with a number between <ic>0</ic> an
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Playing melodies using samples",
|
||||
`
|
||||
"Playing melodies using samples",
|
||||
`
|
||||
beat(0.25)::sound('notes')
|
||||
.room(0.5).size(4).pan(r(0, 1))
|
||||
.note([0, 2, 3, 4, 5].scale('minor', 50).beat(0.25)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
## Looping over a sample
|
||||
@ -101,29 +101,29 @@ Using <ic>loop</ic> (<ic>1</ic> for looping), <ic>loopBegin</ic> and <ic>loopEnd
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Granulation using loop",
|
||||
`
|
||||
"Granulation using loop",
|
||||
`
|
||||
beat(0.25)::sound('fikea').loop(1)
|
||||
.lpf(ir(2000, 5000))
|
||||
.loopBegin(0).loopEnd(r(0, 1))
|
||||
.room(0.5).size(4).pan(r(0, 1))
|
||||
.note([0, 2, 3, 4, 5].scale('minor', 50).beat(0.25)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Stretching a sample
|
||||
|
||||
The <ic>stretch</ic> parameter can help you to stretch long samples like amen breaks:
|
||||
|
||||
${makeExample(
|
||||
"Playing an amen break",
|
||||
`
|
||||
"Playing an amen break",
|
||||
`
|
||||
// Note that stretch has the same value as beat
|
||||
beat(4) :: sound('amen1').n(11).stretch(4).out()
|
||||
beat(1) :: sound('kick').shape(0.35).out()`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
## Cutting samples
|
||||
|
||||
@ -132,43 +132,43 @@ Sometimes, you will find it necessary to cut a sample. It can be because the sam
|
||||
Know about the <ic>begin</ic> and <ic>end</ic> parameters. They are not related to the sampler itself, but to the length of the event you are playing. Let's cut the granular example:
|
||||
|
||||
${makeExample(
|
||||
"Cutting a sample using end",
|
||||
`
|
||||
"Cutting a sample using end",
|
||||
`
|
||||
beat(0.25)::sound('notes')
|
||||
.end(usine(1/2)/0.5)
|
||||
.room(0.5).size(4).pan(r(0, 1))
|
||||
.note([0, 2, 3, 4, 5].scale('minor', 50).beat(0.25)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
You can also use <ic>clip</ic> to cut the sample everytime a new sample comes in:
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Cutting a sample using end",
|
||||
`
|
||||
"Cutting a sample using end",
|
||||
`
|
||||
beat(0.125)::sound('notes')
|
||||
.cut(1)
|
||||
.room(0.5).size(4).pan(r(0, 1))
|
||||
.note([0, 2, 3, 4, 5].scale('minor', 50).beat(0.125)
|
||||
+ [-12,12].beat()).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Adding vibrato to samples
|
||||
|
||||
You can add vibrato to any sample using <ic>vib</ic> and <ic>vibmod</ic>:
|
||||
|
||||
${makeExample(
|
||||
"Adding vibrato to a sample",
|
||||
`
|
||||
"Adding vibrato to a sample",
|
||||
`
|
||||
|
||||
beat(1)::sound('fhang').vib([1, 2, 4].bar()).vibmod([0.5, 2].beat()).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
`;
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const synths = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory, key_shortcut } from "../Documentation";
|
||||
import { makeExampleFactory, key_shortcut } from "../../Documentation";
|
||||
|
||||
export const midi = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -22,22 +22,22 @@ Your web browser is capable of sending and receiving MIDI information through th
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Listing MIDI outputs",
|
||||
`
|
||||
"Listing MIDI outputs",
|
||||
`
|
||||
midi_outputs()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>midi_output(output_name: string)</ic>: enter your desired output to connect to it.
|
||||
|
||||
${makeExample(
|
||||
"Changing MIDI output",
|
||||
`
|
||||
"Changing MIDI output",
|
||||
`
|
||||
midi_output("MIDI Rocket-Trumpet")
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
That's it! You are now ready to play with MIDI.
|
||||
|
||||
@ -48,69 +48,69 @@ The most basic MIDI event is the note. MIDI notes traditionally take three param
|
||||
- <ic>midi(note: number|object)</ic>: send a MIDI Note. This function is quite bizarre. It can be written and used in many different ways. You can pass form one up to three arguments in different forms.
|
||||
|
||||
${makeExample(
|
||||
"MIDI note using one parameter: note",
|
||||
`
|
||||
"MIDI note using one parameter: note",
|
||||
`
|
||||
// Configure your MIDI first!
|
||||
// => midi_output("MIDI Bus 1")
|
||||
rhythm(.5, 5, 8) :: midi(50).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"MIDI note using three parameters: note, velocity, channel",
|
||||
`
|
||||
"MIDI note using three parameters: note, velocity, channel",
|
||||
`
|
||||
// MIDI Note 50, Velocity 50 + LFO, Channel 0
|
||||
rhythm(.5, 5, 8) :: midi(50, 50 + usine(.5) * 20, 0).out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"MIDI note by passing an object",
|
||||
`
|
||||
"MIDI note by passing an object",
|
||||
`
|
||||
// MIDI Note 50, Velocity 50 + LFO, Channel 0
|
||||
rhythm(.5, 5, 8) :: midi({note: 50, velocity: 50 + usine(.5) * 20, channel: 0}).out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
We can now have some fun and starting playing a small piano piece:
|
||||
|
||||
${makeExample(
|
||||
"Playing some piano",
|
||||
`
|
||||
"Playing some piano",
|
||||
`
|
||||
tempo(80) // Setting a default BPM
|
||||
beat(.5) && midi(36 + [0,12].beat()).sustain(0.02).out()
|
||||
beat(.25) && midi([64, 76].pick()).sustain(0.05).out()
|
||||
beat(.75) && midi([64, 67, 69].beat()).sustain(0.05).out()
|
||||
beat(.25) && midi([64, 67, 69].beat() + 24).sustain(0.05).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Control and Program Changes
|
||||
|
||||
- <ic>control_change({control: number, value: number, channel: number})</ic>: send a MIDI Control Change. This function takes a single object argument to specify the control message (_e.g._ <ic>control_change({control: 1, value: 127, channel: 1})</ic>).
|
||||
|
||||
${makeExample(
|
||||
"Imagine that I am tweaking an hardware synthesizer!",
|
||||
`
|
||||
"Imagine that I am tweaking an hardware synthesizer!",
|
||||
`
|
||||
control_change({control: [24,25].pick(), value: irand(1,120), channel: 1})
|
||||
control_change({control: [30,35].pick(), value: irand(1,120) / 2, channel: 1})
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>program_change(program: number, channel: number)</ic>: send a MIDI Program Change. This function takes two arguments to specify the program and the channel (_e.g._ <ic>program_change(1, 1)</ic>).
|
||||
|
||||
${makeExample(
|
||||
"Crashing old synthesizers: a hobby",
|
||||
`
|
||||
"Crashing old synthesizers: a hobby",
|
||||
`
|
||||
program_change([1,2,3,4,5,6,7,8].pick(), 1)
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
## System Exclusive Messages
|
||||
@ -119,44 +119,44 @@ program_change([1,2,3,4,5,6,7,8].pick(), 1)
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Nobody can say that we don't support Sysex messages!",
|
||||
`
|
||||
"Nobody can say that we don't support Sysex messages!",
|
||||
`
|
||||
sysex(0x90, 0x40, 0x7f)
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Clock
|
||||
|
||||
- <ic>midi_clock()</ic>: send a MIDI Clock message. This function is used to synchronize Topos with other MIDI devices or DAWs.
|
||||
|
||||
${makeExample(
|
||||
"Tic, tac, tic, tac...",
|
||||
`
|
||||
"Tic, tac, tic, tac...",
|
||||
`
|
||||
beat(.25) && midi_clock() // Sending clock to MIDI device from the global buffer
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Using midi with ziffers
|
||||
|
||||
Ziffers offers some shorthands for defining channels within the patterns. See Ziffers for more information.
|
||||
|
||||
${makeExample(
|
||||
"Using midi with ziffers",
|
||||
`
|
||||
"Using midi with ziffers",
|
||||
`
|
||||
z1('0 2 e 5 2 q 4 2').midi().port(2).channel(4).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Setting the channel within the pattern",
|
||||
`
|
||||
"Setting the channel within the pattern",
|
||||
`
|
||||
z1('(0 2 e 5 2):0 (4 2):1').midi().out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
`;
|
||||
};
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const osc = (application: Editor): string => {
|
||||
// @ts-ignore
|
||||
@ -24,52 +24,52 @@ Send an **OSC** message to the server from another application or device at the
|
||||
You can access the last 1000 messages using the <ic>getOsc()</ic> function without any argument. This is raw data, you will need to parse it yourself:
|
||||
|
||||
${makeExample(
|
||||
"Reading the last OSC messages",
|
||||
`
|
||||
"Reading the last OSC messages",
|
||||
`
|
||||
beat(1)::getOsc()
|
||||
// 0 : {data: Array(2), address: '/lala'}
|
||||
// 1 : {data: Array(2), address: '/lala'}
|
||||
// 2 : {data: Array(2), address: '/lala'}`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
### Filtered messages
|
||||
|
||||
The <ic>getOsc()</ic> can receive an address filter as an argument. This will return only the messages that match the filter:
|
||||
|
||||
${makeExample(
|
||||
"Reading the last OSC messages (filtered)",
|
||||
`
|
||||
"Reading the last OSC messages (filtered)",
|
||||
`
|
||||
beat(1)::getOsc("/lala")
|
||||
// 0 : (2) [89, 'bob']
|
||||
// 1 : (2) [84, 'bob']
|
||||
// 2 : (2) [82, 'bob']
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Output
|
||||
|
||||
Once the server is loaded, you are ready to send an **OSC** message:
|
||||
|
||||
${makeExample(
|
||||
"Sending a simple OSC message",
|
||||
`
|
||||
"Sending a simple OSC message",
|
||||
`
|
||||
beat(1)::sound('cp').speed(2).vel(0.5).osc()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
This is a simple **OSC** message that will inherit all the properties of the sound. You can also send customized OSC messages using the <ic>osc()</ic> function:
|
||||
|
||||
${makeExample(
|
||||
"Sending a customized OSC message",
|
||||
`
|
||||
"Sending a customized OSC message",
|
||||
`
|
||||
// osc(address, port, ...message)
|
||||
osc('/my/osc/address', 5000, 1, 2, 3)
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
`;
|
||||
};
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const loading_samples = (application: Editor): string => {
|
||||
// @ts-ignore
|
||||
@ -12,36 +12,36 @@ Topos is exposing the <ic>samples</ic> function that you can use to load your ow
|
||||
Samples are loaded on-the-fly from the web. Topos is a web application living in the browser. It is running in a sandboxed environment. Thus, it cannot have access to the files stored on your local system. Loading samples requires building a _map_ of the audio files, where a name is associated to a specific file:
|
||||
|
||||
${makeExample(
|
||||
"Loading samples from a map",
|
||||
`samples({
|
||||
"Loading samples from a map",
|
||||
`samples({
|
||||
bd: ['bd/BT0AADA.wav','bd/BT0AAD0.wav'],
|
||||
sd: ['sd/rytm-01-classic.wav','sd/rytm-00-hard.wav'],
|
||||
hh: ['hh27/000_hh27closedhh.wav','hh/000_hh3closedhh.wav'],
|
||||
}, 'github:tidalcycles/Dirt-Samples/master/');`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
This example is loading two samples from each folder declared in the original repository (in the <ic>strudel.json</ic> file). You can then play with them using the syntax you are already used to:
|
||||
|
||||
${makeExample(
|
||||
"Playing with the loaded samples",
|
||||
`rhythm(.5, 5, 8)::sound('bd').n(ir(1,2)).end(1).out()
|
||||
"Playing with the loaded samples",
|
||||
`rhythm(.5, 5, 8)::sound('bd').n(ir(1,2)).end(1).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
Internally, Topos is loading samples using a different technique where sample maps are directly taken from the previously mentioned <ic>strudel.json</ic> file that lives in each repository:
|
||||
|
||||
${makeExample(
|
||||
"This is how Topos is loading its own samples",
|
||||
`
|
||||
"This is how Topos is loading its own samples",
|
||||
`
|
||||
// Visit the concerned repos and search for 'strudel.json'
|
||||
samples("github:tidalcycles/Dirt-Samples/master");
|
||||
samples("github:Bubobubobubobubo/Dough-Samples/main");
|
||||
samples("github:Bubobubobubobubo/Dough-Amiga/main");
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
To learn more about the audio sample loading mechanism, please refer to [this page](https://strudel.tidalcycles.org/learn/samples) written by Felix Roos who has implemented the sample loading mechanism. The API is absolutely identic in Topos!
|
||||
|
||||
@ -50,16 +50,16 @@ To learn more about the audio sample loading mechanism, please refer to [this pa
|
||||
You can load samples coming from [Freesound](https://freesound.org/) using the [Shabda](https://shabda.ndre.gr/) API. To do so, study the following example:
|
||||
|
||||
${makeExample(
|
||||
"Loading samples from shabda",
|
||||
`
|
||||
"Loading samples from shabda",
|
||||
`
|
||||
// Prepend the sample you want with 'shabda:'
|
||||
samples("shabda:ocean")
|
||||
|
||||
// Use the sound without 'shabda:'
|
||||
beat(1)::sound('ocean').clip(1).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
You can also use the <ic>.n</ic> attribute like usual to load a different sample.
|
||||
`;
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const sample_banks = (application: Editor): string => {
|
||||
// @ts-ignore
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const samples_to_markdown = (
|
||||
application: Editor,
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const cyclical_time = (app: Editor): string => {
|
||||
// @ts-ignore
|
||||
@ -16,17 +16,17 @@ Time as a cycle. A cycle can be quite long (a few bars) or very short (a few pul
|
||||
- <ic>offset</ic>: offset (in beats) to apply. An offset of <ic>0.5</ic> will return true against the beat.
|
||||
|
||||
${makeExample(
|
||||
"Using different mod values",
|
||||
`
|
||||
"Using different mod values",
|
||||
`
|
||||
// This code is alternating between different mod values
|
||||
beat([1,1/2,1/4,1/8].beat(2)) :: sound('hat').n(0).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Some sort of ringtone",
|
||||
`
|
||||
"Some sort of ringtone",
|
||||
`
|
||||
// Blip generator :)
|
||||
let blip = (freq) => {
|
||||
return sound('wt_piano')
|
||||
@ -41,16 +41,16 @@ beat(1/3) :: blip(400).pan(r(0,1)).out();
|
||||
flip(3) :: beat(1/6) :: blip(800).pan(r(0,1)).out();
|
||||
beat([1,0.75].beat(2)) :: blip([50, 100].beat(2)).pan(r(0,1)).out();
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Beat can match multiple values",
|
||||
`
|
||||
"Beat can match multiple values",
|
||||
`
|
||||
beat([.5, 1.25])::sound('hat').out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
- <ic>pulse(n: number | number[] = 1, offset: number = 1)</ic>: return true every _n_ pulses. A pulse is the tiniest possible rhythmic value.
|
||||
- <ic>number</ic>: if <ic>number = 1</ic>, the function will return <ic>true</ic> every pulse. Lists can be used too.
|
||||
@ -58,21 +58,21 @@ beat([.5, 1.25])::sound('hat').out()
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Intriguing rhythms",
|
||||
`
|
||||
"Intriguing rhythms",
|
||||
`
|
||||
pulse([24, 16])::sound('hat').ad(0, .02).out()
|
||||
pulse([48, [36,24].dur(4, 1)])::sound('fhardkick').ad(0, .1).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
${makeExample(
|
||||
"pulse is the OG rhythmic function in Topos",
|
||||
`
|
||||
"pulse is the OG rhythmic function in Topos",
|
||||
`
|
||||
pulse([48, 24, 16].beat(4)) :: sound('linnhats').out()
|
||||
beat(1)::snd(['bd', '808oh'].beat(1)).out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
|
||||
- <ic>bar(n: number | number[] = 1, offset: number = 1)</ic>: return true every _n_ bars.
|
||||
@ -80,37 +80,37 @@ beat(1)::snd(['bd', '808oh'].beat(1)).out()
|
||||
- <ic>offset</ic>: offset (in bars) to apply.
|
||||
|
||||
${makeExample(
|
||||
"Four beats per bar: proof",
|
||||
`
|
||||
"Four beats per bar: proof",
|
||||
`
|
||||
bar(1)::sound('kick').out()
|
||||
beat(1)::sound('hat').speed(2).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Offsetting beat and bar",
|
||||
`
|
||||
"Offsetting beat and bar",
|
||||
`
|
||||
bar(1)::sound('kick').out()
|
||||
beat(1)::sound('hat').speed(2).out()
|
||||
beat(1, 0.5)::sound('hat').speed(4).out()
|
||||
bar(1, 0.5)::sound('sn').out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
- <ic>onbeat(...n: number[])</ic>: The <ic>onbeat</ic> function allows you to lock on to a specific beat from the clock to execute code. It can accept multiple arguments. It's usage is very straightforward and not hard to understand. You can pass either integers or floating point numbers. By default, topos is using a <ic>4/4</ic> bar meaning that you can target any of these beats (or in-between) with this function.
|
||||
|
||||
${makeExample(
|
||||
"Some simple yet detailed rhythms",
|
||||
`
|
||||
"Some simple yet detailed rhythms",
|
||||
`
|
||||
onbeat(1,2,3,4)::snd('kick').out() // Bassdrum on each beat
|
||||
onbeat(2,4)::snd('snare').n([8,4].beat(4)).out() // Snare on acccentuated beats
|
||||
onbeat(1.5,2.5,3.5, 3.75)::snd('hat').gain(r(0.9,1.1)).out() // Cool high-hats
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## XOX Style sequencers
|
||||
|
||||
@ -119,32 +119,32 @@ onbeat(1.5,2.5,3.5, 3.75)::snd('hat').gain(r(0.9,1.1)).out() // Cool high-hats
|
||||
- <ic>duration: number</ic>: an optional duration (in beats) like <ic>1</ic> or </ic>4</ic>. It can be patterned.
|
||||
|
||||
${makeExample(
|
||||
"Sequence built using a classic XOX sequencer style",
|
||||
`
|
||||
"Sequence built using a classic XOX sequencer style",
|
||||
`
|
||||
seq('xoxo')::sound('fhardkick').out()
|
||||
seq('ooxo')::sound('fsoftsnare').out()
|
||||
seq('xoxo', 0.25)::sound('fhh').out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Another sequence using more complex parameters",
|
||||
`
|
||||
"Another sequence using more complex parameters",
|
||||
`
|
||||
seq('xoxooxxoo', [0.5, 0.25].dur(2, 1))::sound('fhardkick').out()
|
||||
seq('ooxo', [1, 2].bar())::sound('fsoftsnare').speed(0.5).out()
|
||||
seq(['xoxoxoxx', 'xxoo'].bar())::sound('fhh').out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>fullseq(expr: string, duration: number = 0.5): boolean</ic> : a variant. Will return <ic>true</ic> or <ic>false</ic> for a whole period, depending on the symbol. Useful for long structure patterns.
|
||||
- <ic>expr: string</ic>: any string composed of <ic>x</ic> or <ic>o</ic> like so: <ic>"xooxoxxoxoo"</ic>.
|
||||
- <ic>duration: number</ic>: an optional duration (in beats) like <ic>1</ic> or </ic>4</ic>. It can be patterned.
|
||||
|
||||
${makeExample(
|
||||
"Long structured patterns",
|
||||
`
|
||||
"Long structured patterns",
|
||||
`
|
||||
function simplePat() {
|
||||
log('Simple pattern playing!')
|
||||
seq('xoxooxxoo', [0.5, 0.25].dur(2, 1))::sound('fhardkick').out()
|
||||
@ -159,8 +159,8 @@ function complexPat() {
|
||||
}
|
||||
fullseq('xooxooxx', 4) ? simplePat() : complexPat()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
|
||||
@ -171,8 +171,8 @@ We included a bunch of popular rhythm generators in Topos such as the euclidian
|
||||
|
||||
- <ic>rhythm(divisor: number, pulses: number, length: number, rotate: number): boolean</ic>: generates <ic>true</ic> or <ic>false</ic> values from an euclidian rhythm sequence. This is another version of <ic>euclid</ic> that does not take an iterator.
|
||||
${makeExample(
|
||||
"rhythm is a beginner friendly rhythmic function!",
|
||||
`
|
||||
"rhythm is a beginner friendly rhythmic function!",
|
||||
`
|
||||
rhythm(.5, 4, 8)::sound('sine')
|
||||
.fmi(2)
|
||||
.room(0.5).size(8)
|
||||
@ -181,38 +181,38 @@ rhythm(.5, 7, 8)::sound('sine')
|
||||
.freq(125).ad(0, .2).out()
|
||||
rhythm(.5, 3, 8)::sound('sine').freq(500).ad(0, .5).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
- <ic>oneuclid(pulses: number, length: number, rotate: number): boolean</ic>: generates <ic>true</ic> or <ic>false</ic> values from an euclidian rhythm sequence. This is another version of <ic>euclid</ic> that does not take an iterator.
|
||||
${makeExample(
|
||||
"Using oneuclid to create a rhythm without iterators",
|
||||
`
|
||||
"Using oneuclid to create a rhythm without iterators",
|
||||
`
|
||||
// Change speed using bpm
|
||||
bpm(250)
|
||||
oneuclid(5, 9) :: snd('kick').out()
|
||||
oneuclid(7,16) :: snd('east').end(0.5).n(irand(3,5)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>bin(iterator: number, n: number): boolean</ic>: a binary rhythm generator. It transforms the given number into its binary representation (_e.g_ <ic>34</ic> becomes <ic>100010</ic>). It then returns a boolean value based on the iterator in order to generate a rhythm.
|
||||
- <ic>binrhythm(divisor: number, n: number): boolean: boolean</ic>: iterator-less version of the binary rhythm generator.
|
||||
|
||||
${makeExample(
|
||||
"Change the integers for a surprise rhythm!",
|
||||
`
|
||||
"Change the integers for a surprise rhythm!",
|
||||
`
|
||||
bpm(135);
|
||||
beat(.5) && bin($(1), 12) && snd('kick').n([4,9].beat(1.5)).out()
|
||||
beat(.5) && bin($(2), 34) && snd('snare').n([3,5].beat(1)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"binrhythm for fast cool binary rhythms!",
|
||||
`
|
||||
"binrhythm for fast cool binary rhythms!",
|
||||
`
|
||||
let a = 0;
|
||||
a = beat(4) ? irand(1,20) : a;
|
||||
binrhythm(.5, 6) && snd(['kick', 'snare'].beat(0.5)).n(11).out()
|
||||
@ -221,34 +221,34 @@ binrhythm([.5, .25].beat(1), 30) && snd('wt_granular').n(a)
|
||||
.adsr(0, r(.1, .4), 0, 0).freq([50, 60, 72].beat(4))
|
||||
.room(1).size(1).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Submarine jungle music",
|
||||
`
|
||||
"Submarine jungle music",
|
||||
`
|
||||
bpm(145);
|
||||
beat(.5) && bin($(1), 911) && snd('ST69').n([2,3,4].beat())
|
||||
.delay(0.125).delayt(0.25).end(0.25).speed(1/3)
|
||||
.room(1).size(1).out()
|
||||
beat(.5) && sound('amencutup').n(irand(2,7)).shape(0.3).out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
If you don't find it spicy enough, you can add some more probabilities to your rhythms by taking advantage of the probability functions. See the functions documentation page to learn more about them.
|
||||
|
||||
${makeExample(
|
||||
"Probablistic drums in one line!",
|
||||
`
|
||||
"Probablistic drums in one line!",
|
||||
`
|
||||
prob(60)::beat(.5) && euclid($(1), 5, 8) && snd('kick').out()
|
||||
prob(60)::beat(.5) && euclid($(2), 3, 8) && snd('mash')
|
||||
.n([1,2,3].beat(1))
|
||||
.pan(usine(1/4)).out()
|
||||
prob(80)::beat(.5) && sound(['hh', 'hat'].pick()).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
import pulses from "./pulses.svg";
|
||||
|
||||
export const linear_time = (app: Editor): string => {
|
||||
@ -22,12 +22,12 @@ export const linear_time = (app: Editor): string => {
|
||||
There is a tiny widget at the bottom right of the screen showing you the current BPM and the status of the transport. You can turn it on or off in the settings menu.
|
||||
|
||||
${makeExample(
|
||||
"Printing the transport",
|
||||
`
|
||||
"Printing the transport",
|
||||
`
|
||||
log(\`\$\{cbar()}\, \$\{cbeat()\}, \$\{cpulse()\}\`)
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
### BPM and PPQN
|
||||
|
||||
@ -64,8 +64,8 @@ These values are **extremely useful** to craft more complex syntax or to write m
|
||||
You can use time primitives as conditionals. The following example will play a pattern A for 2 bars and a pattern B for 2 bars:
|
||||
|
||||
${makeExample(
|
||||
"Manual mode: using time primitives!",
|
||||
`
|
||||
"Manual mode: using time primitives!",
|
||||
`
|
||||
// Manual time condition
|
||||
if((cbar() % 4) > 1) {
|
||||
beat(2) && sound('kick').out()
|
||||
@ -83,8 +83,8 @@ if((cbar() % 4) > 1) {
|
||||
// This is always playing no matter what happens
|
||||
beat([.5, .5, 1, .25].beat(0.5)) :: sound('shaker').out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Time Warping
|
||||
|
||||
@ -94,8 +94,8 @@ Time generally flows from the past to the future. However, you can manipulate it
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Time is now super elastic!",
|
||||
`
|
||||
"Time is now super elastic!",
|
||||
`
|
||||
// Obscure Shenanigans - Bubobubobubo
|
||||
beat([1/4,1/8,1/16].beat(8)):: sound('sine')
|
||||
.freq([100,50].beat(16) + 50 * ($(1)%10))
|
||||
@ -108,14 +108,14 @@ flip(3) :: beat([.25,.5].beat(.5)) :: sound('dr')
|
||||
// Jumping back and forth in time
|
||||
beat(.25) :: warp([12, 48, 24, 1, 120, 30].pick())
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>beat_warp(beat: number)</ic>: this function jumps to the _n_ beat of the clock. The first beat is <ic>1</ic>.
|
||||
|
||||
${makeExample(
|
||||
"Jumping back and forth with beats",
|
||||
`
|
||||
"Jumping back and forth with beats",
|
||||
`
|
||||
// Resonance bliss - Bubobubobubo
|
||||
beat(.25)::snd('arpy')
|
||||
.note(30 + [0,3,7,10].beat())
|
||||
@ -126,44 +126,44 @@ beat([.25,.125].beat(2))::snd('arpy')
|
||||
.cutoff(usine(.5) * 5000).resonance(20).gain(0.3)
|
||||
.end(0.8).room(0.9).size(0.9).n(3).out();
|
||||
beat(.5) :: snd('arpy').note(
|
||||
[30, 33, 35].repeat(4).beat(1) - [12,0].beat(0.5)).out()
|
||||
[30, 33, 35].repeatAll(4).beat(1) - [12,0].beat(0.5)).out()
|
||||
// Comment me to stop warping!
|
||||
beat(1) :: beat_warp([2,4,5,10,11].pick())
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Transport-based rhythm generators
|
||||
|
||||
- <ic>onbeat(...n: number[])</ic>: The <ic>onbeat</ic> function allows you to lock on to a specific beat from the clock to execute code. It can accept multiple arguments. It's usage is very straightforward and not hard to understand. You can pass either integers or floating point numbers. By default, topos is using a <ic>4/4</ic> bar meaning that you can target any of these beats (or in-between) with this function.
|
||||
|
||||
${makeExample(
|
||||
"Some simple yet detailed rhythms",
|
||||
`
|
||||
"Some simple yet detailed rhythms",
|
||||
`
|
||||
onbeat(1,2,3,4)::snd('kick').out() // Bassdrum on each beat
|
||||
onbeat(2,4)::snd('snare').n([8,4].beat(4)).out() // Snare on acccentuated beats
|
||||
onbeat(1.5,2.5,3.5, 3.75)::snd('hat').gain(r(0.9,1.1)).out() // Cool high-hats
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Let's do something more complex",
|
||||
`
|
||||
"Let's do something more complex",
|
||||
`
|
||||
onbeat(0.5, 2, 3, 3.75)::snd('kick').n(2).out()
|
||||
onbeat(2, [1.5, 3, 4].pick(), 4)::snd('snare').n(8).out()
|
||||
beat([.25, 1/8].beat(1.5))::snd('hat').n(2)
|
||||
.gain(rand(0.4, 0.7)).end(0.05)
|
||||
.pan(usine()).out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
- <ic>oncount(beats: number[], meter: number)</ic>: This function is similar to <ic>onbeat</ic> but it allows you to specify a custom number of beats as the last argument.
|
||||
|
||||
${makeExample(
|
||||
"Using oncount to create more variation in the rhythm",
|
||||
`
|
||||
"Using oncount to create more variation in the rhythm",
|
||||
`
|
||||
z1('1/16 (0 2 3 4)+(0 2 4 6)').scale('pentatonic').sound('sawtooth')
|
||||
.cutoff([400,500,1000,2000].beat(1))
|
||||
.lpadsr(2, 0, .2, 0, 0)
|
||||
@ -171,20 +171,20 @@ z1('1/16 (0 2 3 4)+(0 2 4 6)').scale('pentatonic').sound('sawtooth')
|
||||
onbeat(1,1.5,2,3,4) :: sound('bd').gain(2.0).out()
|
||||
oncount([1,3,5.5,7,7.5,8],8) :: sound('hh').gain(irand(1.0,4.0)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Using oncount to create rhythms with a custom meter",
|
||||
`
|
||||
tempo(200)
|
||||
"Using oncount to create rhythms with a custom meter",
|
||||
`
|
||||
bpm(200)
|
||||
oncount([1, 5, 9, 13],16) :: sound('808bd').n(4).shape(0.5).gain(1.0).out()
|
||||
oncount([5, 6, 13],16) :: sound('shaker').room(0.25).gain(0.9).out()
|
||||
oncount([2, 3, 3.5, 6, 7, 10, 15],16) :: sound('hh').n(8).gain(0.8).out()
|
||||
oncount([1, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16],16) :: sound('hh').out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../../main";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
|
||||
export const long_forms = (app: Editor): string => {
|
||||
// @ts-ignore
|
||||
@ -14,23 +14,23 @@ Now you know how to play some basic rhythms but in any case, you are stuck in a
|
||||
- **Use the nine local scripts as containers** for sections of your composition. When you start playing with **Topos**, it's easy to forget that there are multiple scripts you can play with. Each script can store a different section or part from your composition. Here is a simple example:
|
||||
|
||||
${makeExample(
|
||||
"Eight bars per section",
|
||||
`
|
||||
"Eight bars per section",
|
||||
`
|
||||
// Playing each script for 8 bars in succession
|
||||
script([1,2,3,4].bar(8))
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
You can also give a specific duration to each section using <ic>.dur</ic>:
|
||||
|
||||
${makeExample(
|
||||
"N beats per section",
|
||||
`
|
||||
"N beats per section",
|
||||
`
|
||||
script([1,2,3,4].dur(8, 2, 16, 4))
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- **Use universes as well**. Transitions between universes are _seamless_, instantaneous. Just switch to different content if you ever hit the limitations of the current _universe_.
|
||||
|
||||
@ -40,42 +40,42 @@ script([1,2,3,4].dur(8, 2, 16, 4))
|
||||
- <ic>ratio: number = 50</ic>: this argument is ratio expressed in %. It determines how much of the period should be true or false. A ratio of <ic>75</ic> means that 75% of the period will be true. A ratio of <ic>25</ic> means that 25% of the period will be true.
|
||||
|
||||
${makeExample(
|
||||
"Two beats of silence, two beats of playing",
|
||||
`
|
||||
"Two beats of silence, two beats of playing",
|
||||
`
|
||||
flip(4) :: beat(1) :: snd('kick').out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Clapping on the edge",
|
||||
`
|
||||
"Clapping on the edge",
|
||||
`
|
||||
flip(2.5, 10) :: beat(.25) :: snd('cp').out()
|
||||
flip(2.5, 75) :: beat(.25) :: snd('click')
|
||||
.speed(2).end(0.2).out()
|
||||
flip(2.5) :: beat(.5) :: snd('bd').out()
|
||||
beat(.25) :: sound('hat').end(0.1).cutoff(1200).pan(usine(1/4)).out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Good old true and false",
|
||||
`
|
||||
"Good old true and false",
|
||||
`
|
||||
if (flip(4, 75)) {
|
||||
beat(1) :: snd('kick').out()
|
||||
} else {
|
||||
beat(.5) :: snd('snare').out()
|
||||
}
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
<ic>flip</ic> is extremely powerful and is used internally for a lot of other Topos functions. You can also use it to think about **longer durations** spanning over multiple bars. Here is a silly composition that is using <ic>flip</ic> to generate a 4 bars long pattern.
|
||||
|
||||
${makeExample(
|
||||
"Clunky algorithmic rap music",
|
||||
`
|
||||
"Clunky algorithmic rap music",
|
||||
`
|
||||
// Rap God VS Lil Wild -- Adel Faure
|
||||
if (flip(8)) {
|
||||
// Playing this part for two bars
|
||||
@ -93,24 +93,24 @@ if (flip(8)) {
|
||||
beat(.5)::snd('diphone').end(0.5).n([1,2,3,4].pick()).out()
|
||||
}
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
You can use it everywhere to spice things up, including as a method parameter picker:
|
||||
|
||||
${makeExample(
|
||||
"flip is great for parameter variation",
|
||||
`
|
||||
"flip is great for parameter variation",
|
||||
`
|
||||
beat(.5)::snd(flip(2) ? 'kick' : 'hat').out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>flipbar(n: number = 1)</ic>: this method works just like <ic>flip</ic> but counts in bars instead of beats. It allows you to think about even larger time cycles. You can also pair it with regular <ic>flip</ic> for writing complex and long-spanning algorithmic beats.
|
||||
|
||||
${makeExample(
|
||||
"Thinking music over bars",
|
||||
`
|
||||
"Thinking music over bars",
|
||||
`
|
||||
let roomy = (n) => n.room(1).size(1).cutoff(500 + usaw(1/8) * 5000);
|
||||
function a() {
|
||||
beat(1) && roomy(sound('kick')).out()
|
||||
@ -122,24 +122,24 @@ function b() {
|
||||
flipbar(2) && a()
|
||||
flipbar(3) && b()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
${makeExample(
|
||||
"Alternating over four bars",
|
||||
`
|
||||
"Alternating over four bars",
|
||||
`
|
||||
flipbar(2)
|
||||
? beat(.5) && snd(['kick', 'hh'].beat(1)).out()
|
||||
: beat(.5) && snd(['east', 'east:2'].beat(1)).out()
|
||||
`,
|
||||
false,
|
||||
)};
|
||||
false,
|
||||
)};
|
||||
|
||||
|
||||
- <ic>onbar(bars: number | number[], n: number)</ic>: The second argument, <ic>n</ic>, is used to divide the time in a period of <ic>n</ic> consecutive bars. The first argument should be a bar number or a list of bar numbers to play on. For example, <ic>onbar([1, 4], 5)</ic> will return <ic>true</ic> on bar <ic>1</ic> and <ic>4</ic> but return <ic>false</ic> the rest of the time. You can easily divide time that way.
|
||||
|
||||
${makeExample(
|
||||
"Using onbar for filler drums",
|
||||
`
|
||||
"Using onbar for filler drums",
|
||||
`
|
||||
tempo(150);
|
||||
// Only play on the third and fourth bar of the cycle.
|
||||
onbar([3,4], 4)::beat(.25)::snd('hh').out();
|
||||
@ -155,8 +155,8 @@ if (onbar([1,2], 4)) {
|
||||
rhythm(.5, 1, 7) :: snd('jvbass').n(2).out();
|
||||
rhythm(.5, 2, 7) :: snd('snare').n(3).out();
|
||||
}`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
`;
|
||||
};
|
||||
|
Before Width: | Height: | Size: 8.4 KiB After Width: | Height: | Size: 8.4 KiB |
@ -1,4 +1,4 @@
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { makeExampleFactory } from "../../../Documentation";
|
||||
import { type Editor } from "../../../main";
|
||||
import times from "./times.svg";
|
||||
|
||||
|
Before Width: | Height: | Size: 5.0 KiB After Width: | Height: | Size: 5.0 KiB |
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { key_shortcut, makeExampleFactory } from "../Documentation";
|
||||
import { key_shortcut, makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const bonus = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -14,16 +14,16 @@ Some features have been included as a bonus. These features are often about patt
|
||||
The editor theme can be changed using the <ic>theme</ic> and <ic>randomTheme</ic> functions. The following example will use a random color scheme for every beat:
|
||||
|
||||
${makeExample(
|
||||
"Random theme on each beat",
|
||||
`
|
||||
"Random theme on each beat",
|
||||
`
|
||||
beat(1)::randomTheme()
|
||||
`, true)}
|
||||
|
||||
You can also pick a theme using the <ic>theme</ic> function with a string as only argument:
|
||||
|
||||
${makeExample(
|
||||
"Picking a theme",
|
||||
`
|
||||
"Picking a theme",
|
||||
`
|
||||
beat(1)::theme("Batman")
|
||||
`, true)}
|
||||
|
||||
@ -36,27 +36,27 @@ beat(1)::theme("Batman")
|
||||
[Hydra](https://hydra.ojack.xyz/?sketch_id=mahalia_1) is a popular live-codable video synthesizer developed by [Olivia Jack](https://ojack.xyz/) and other contributors. It follows an analog synthesizer patching metaphor to encourage live coding complex shaders. Being very easy to use, extremely powerful and also very rewarding to use, Hydra has become a popular choice for adding visuals into a live code performance.
|
||||
|
||||
${makeExample(
|
||||
"Hydra integration",
|
||||
`beat(4) :: hydra.osc(3, 0.5, 2).out()`,
|
||||
true,
|
||||
)}
|
||||
"Hydra integration",
|
||||
`beat(4) :: hydra.osc(3, 0.5, 2).out()`,
|
||||
true,
|
||||
)}
|
||||
|
||||
Close the documentation to see the effect: ${key_shortcut(
|
||||
"Ctrl+D",
|
||||
)}! **Boom, all shiny!**
|
||||
"Ctrl+D",
|
||||
)}! **Boom, all shiny!**
|
||||
|
||||
Be careful not to call <ic>hydra</ic> too often as it can impact performances. You can use any rhythmical function like <ic>beat()</ic> function to limit the number of function calls. You can write any Topos code like <ic>[1,2,3].beat()</ic> to bring some life and movement in your Hydra sketches.
|
||||
|
||||
Stopping **Hydra** is simple:
|
||||
|
||||
${makeExample(
|
||||
"Stopping Hydra",
|
||||
`
|
||||
"Stopping Hydra",
|
||||
`
|
||||
beat(4) :: stop_hydra() // this one
|
||||
beat(4) :: hydra.hush() // or this one
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
### Changing the resolution
|
||||
@ -64,10 +64,10 @@ beat(4) :: hydra.hush() // or this one
|
||||
You can change Hydra resolution using this simple method:
|
||||
|
||||
${makeExample(
|
||||
"Changing Hydra resolution",
|
||||
`hydra.setResolution(1024, 768)`,
|
||||
true,
|
||||
)}
|
||||
"Changing Hydra resolution",
|
||||
`hydra.setResolution(1024, 768)`,
|
||||
true,
|
||||
)}
|
||||
|
||||
### Documentation
|
||||
|
||||
@ -87,8 +87,8 @@ ${makeExample("Hydra namespace", `hydra.voronoi(20).out()`, true)}
|
||||
Topos embeds a small <ic>.gif</ic> picture player with a small API. GIFs are automatically fading out after the given duration. Look at the following example:
|
||||
|
||||
${makeExample(
|
||||
"Playing many gifs",
|
||||
`
|
||||
"Playing many gifs",
|
||||
`
|
||||
beat(0.25)::gif({
|
||||
url:v('gif')[$(1)%6], // Any URL will do!
|
||||
opacity: r(0.5, 1), // Opacity (0-1)
|
||||
@ -100,7 +100,7 @@ beat(0.25)::gif({
|
||||
posX: ir(1,1200), // CSS Horizontal Position
|
||||
posY: ir(1, 800), // CSS Vertical Position
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
`;
|
||||
};
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const oscilloscope = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -10,18 +10,18 @@ You can turn on the oscilloscope to generate interesting visuals or to inspect a
|
||||
You need to manually feed the scope with the sounds you want to inspect:
|
||||
|
||||
${makeExample(
|
||||
"Feeding a sine to the oscilloscope",
|
||||
`
|
||||
"Feeding a sine to the oscilloscope",
|
||||
`
|
||||
beat(1)::sound('sine').freq(200).ad(0, .2).scope().out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
Here is a layout of the scope configuration options:
|
||||
|
||||
${makeExample(
|
||||
"Oscilloscope configuration",
|
||||
`
|
||||
"Oscilloscope configuration",
|
||||
`
|
||||
scope({
|
||||
enabled: true, // off by default
|
||||
color: "#fdba74", // any valid CSS color or "random"
|
||||
@ -35,12 +35,12 @@ scope({
|
||||
refresh: 1 // refresh rate (in pulses)
|
||||
})
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Demo with multiple scope mode",
|
||||
`
|
||||
"Demo with multiple scope mode",
|
||||
`
|
||||
rhythm(.5, [4,5].dur(4*3, 4*1), 8)::sound('fhardkick').out()
|
||||
beat(0.25)::sound('square').freq([
|
||||
[250, 250/2, 250/4].pick(),
|
||||
@ -56,8 +56,8 @@ scope({enabled: true, thickness: 8,
|
||||
color: ['purple', 'green', 'random'].beat(),
|
||||
size: 0.5, fftSize: 2048})
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
Note that these values can be patterned as well! You can transform the oscilloscope into its own light show if you want. The picture is not stable anyway so you won't have much use of it for precision work :)
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const synchronisation = (app: Editor): string => {
|
||||
// @ts-ignore
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { key_shortcut, makeExampleFactory } from "../Documentation";
|
||||
import { key_shortcut, makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const visualization = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -18,13 +18,10 @@ While Topos is mainly being developed as a live coding environment for algorithm
|
||||
[Hydra](https://hydra.ojack.xyz/?sketch_id=mahalia_1) is a popular live-codable video synthesizer developed by [Olivia Jack](https://ojack.xyz/) and other contributors. It follows an analog synthesizer patching metaphor to encourage live coding complex shaders. Being very easy to use, extremely powerful and also very rewarding to use, Hydra has become a popular choice for adding visuals into a live code performance.
|
||||
|
||||
${makeExample(
|
||||
"Hydra integration",
|
||||
`
|
||||
loadHydra() // Load Hydra first!
|
||||
beat(4) :: hydra.osc(3, 0.5, 2).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
"Hydra integration",
|
||||
`beat(4) :: hydra.osc(3, 0.5, 2).out()`,
|
||||
false,
|
||||
)}
|
||||
|
||||
Close the documentation to see the effect: ${key_shortcut(
|
||||
"Ctrl+D",
|
||||
@ -35,22 +32,23 @@ Be careful not to call <ic>hydra</ic> too often as it can impact performances. Y
|
||||
Stopping **Hydra** is simple:
|
||||
|
||||
${makeExample(
|
||||
"Stopping Hydra",
|
||||
`
|
||||
"Stopping Hydra",
|
||||
`
|
||||
beat(4) :: stop_hydra() // this one
|
||||
beat(4) :: hydra.hush() // or this one
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
### Changing the resolution
|
||||
|
||||
You can change Hydra resolution using this simple method:
|
||||
|
||||
${makeExample(
|
||||
"Changing Hydra resolution",
|
||||
`hydra.setResolution(1024, 768)`,
|
||||
false,
|
||||
)}
|
||||
"Changing Hydra resolution",
|
||||
`hydra.setResolution(1024, 768)`,
|
||||
false,
|
||||
)}
|
||||
|
||||
### Hydra documentation
|
||||
|
||||
@ -70,8 +68,8 @@ ${makeExample("Hydra namespace", `hydra.voronoi(20).out()`, true)}
|
||||
Topos embeds a small <ic>.gif</ic> picture player with a small API. GIFs are automatically fading out after the given duration. Look at the following example:
|
||||
|
||||
${makeExample(
|
||||
"Playing many gifs",
|
||||
`
|
||||
"Playing many gifs",
|
||||
`
|
||||
beat(0.25)::gif({
|
||||
url:v('gif')[$(1)%6], // Any URL will do!
|
||||
opacity: r(0.5, 1), // Opacity (0-1)
|
||||
@ -83,8 +81,8 @@ beat(0.25)::gif({
|
||||
posX: ir(1,1200), // CSS Horizontal Position
|
||||
posY: ir(1, 800), // CSS Vertical Position
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
## Canvas live coding
|
||||
|
||||
@ -97,8 +95,8 @@ In addition to the standard Canvas API, Topos also includes some pre-defined sha
|
||||
* <ic>draw(f: Function)</ic> - Draws to a canvas with the given function.
|
||||
|
||||
${makeExample(
|
||||
"Drawing to canvas",
|
||||
`
|
||||
"Drawing to canvas",
|
||||
`
|
||||
beat(0.5) && clear() && draw(context => {
|
||||
context.fillStyle = 'red';
|
||||
|
||||
@ -119,30 +117,30 @@ beat(0.5) && clear() && draw(context => {
|
||||
context.fill();
|
||||
})
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Using draw with events and shapes",
|
||||
`
|
||||
"Using draw with events and shapes",
|
||||
`
|
||||
beat(0.25) && sound("bass1:5").pitch(rI(1,6)).draw(x => {
|
||||
donut(x.pitch)
|
||||
}).out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
|
||||
${makeExample(
|
||||
"Using draw with ziffers and shapes",
|
||||
`
|
||||
"Using draw with ziffers and shapes",
|
||||
`
|
||||
z1("1/8 (0 2 1 4)+(2 1)").sound("sine").ad(0.05,.25).clear()
|
||||
.draw(x => {
|
||||
pie({slices:7,eaten:(7-x.pitch-1),fillStyle:"green", rotate: 250})
|
||||
}).log("pitch").out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
* <ic<image(url, x, y, width, height, rotation)</ic> - Draws an image to a canvas.
|
||||
|
||||
@ -152,7 +150,7 @@ ${makeExample(
|
||||
beat(0.5) && clear() && image("http://localhost:8000/topos_frog.svg",200,200+epulse()%15)
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
)}
|
||||
|
||||
* <ic>clear()</ic> - Clears the canvas.
|
||||
* <ic>background(fill: string)</ic> - Sets the background color, image or gradient.
|
||||
@ -168,22 +166,22 @@ Text can be drawn to canvas using the <ic>drawText()</ic> function. The function
|
||||
* <ic>drawText(text, fontSize, rotation, font, x, y)</ic> - Draws text to a canvas.
|
||||
|
||||
${makeExample(
|
||||
"Writing to canvas",
|
||||
`
|
||||
"Writing to canvas",
|
||||
`
|
||||
beat(0.5) && clear() && drawText("Hello world!", 100, 0, "Arial", 100, 100)
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
* <ic>randomChar(number, min, max)</ic> - Returns a number of random characters from given unicode range.
|
||||
|
||||
${makeExample(
|
||||
"Drawing random characters to canvas",
|
||||
`
|
||||
"Drawing random characters to canvas",
|
||||
`
|
||||
beat(0.5) && clear() && drawText(randomChar(10,1000,2000),30)
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
* <ic>emoji(size)</ic> - Returns a random emojis as text.
|
||||
|
||||
@ -197,7 +195,7 @@ ${makeExample(
|
||||
beat(0.5) && clear() && drawText({x: 10, y: epulse()%700, text: food(50)})
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
)}
|
||||
|
||||
* <ic>expression(size)</ic> - Returns a random expression emojis as text.
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
import { type Editor } from "../../main";
|
||||
|
||||
export const chaining = (application: Editor): string => {
|
||||
@ -9,12 +9,12 @@ export const chaining = (application: Editor): string => {
|
||||
You might have noticed that **Topos** is using chains a lot. Chains are a very common pattern when programming, especially when you deal with objets that can be composed from many changing properties. Method chaining is used by many objects but mostly by <ic>sound()</ic> and <ic>midi()</ic>. It looks like this:
|
||||
|
||||
${makeExample(
|
||||
"Method chaining",
|
||||
`
|
||||
"Method chaining",
|
||||
`
|
||||
beat(1)::sound('bd').speed(2).lpf(500).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
Method chains become fun if you add just a little bit of complexity to them. You can start to add conditions, start to register complex chains to be re-used later on, etc.. We will not remind you how to write basic chains. The whole documentation is full of examples! Let's explore more delicate patterns!
|
||||
|
||||
@ -23,22 +23,22 @@ Method chains become fun if you add just a little bit of complexity to them. You
|
||||
You can use the <ic>register(...args)</ic> function to... register a chain that you would like to re-use later on.
|
||||
|
||||
${makeExample(
|
||||
"Re-creating a classic Tidal function",
|
||||
`
|
||||
"Re-creating a classic Tidal function",
|
||||
`
|
||||
// Playing with extreme panning and playback rate
|
||||
register('juxrev', n=>n.pan([0, 1]).speed([1, -1]))
|
||||
|
||||
// Using our new abstraction
|
||||
beat(1)::sound('fhh').juxrev().out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
This is an extremely powerful construct. For example, you can use it to create synthesizer presets and reuse them later on. You can also define parameters for your registered functions. For example:
|
||||
|
||||
${makeExample(
|
||||
"Creating synth presets",
|
||||
`
|
||||
"Creating synth presets",
|
||||
`
|
||||
// Registering a specific synth architecture
|
||||
register('sub', (n,x=4,y=80)=>n.ad(0, .25)
|
||||
.fmi(x).pan([0, 1])
|
||||
@ -51,16 +51,16 @@ register('sub', (n,x=4,y=80)=>n.ad(0, .25)
|
||||
rhythm(.25, [6, 8].beat(), 12)::sound('sine')
|
||||
.note([0, 2, 4, 5].scale('minor', 50).beat(0.5))
|
||||
.sub(8).out()`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Registering chain for all events
|
||||
|
||||
The chain can also be registered automatically for all events. This is useful if you want to add a specific effect to all your events.
|
||||
|
||||
${makeExample(
|
||||
"Registering chain to all events at once",
|
||||
`
|
||||
"Registering chain to all events at once",
|
||||
`
|
||||
z0("h 9 ^ <7 5 3 1>")
|
||||
.sound("sine")
|
||||
.out()
|
||||
@ -71,28 +71,28 @@ z1("0 4 3 2")
|
||||
|
||||
all(x=>x.room(1).delay(rI(0,0.5)))
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Logging values from the chain
|
||||
|
||||
You can use the <ic>log()</ic> function to print values from the current event. This can be useful to debug your code. Useful parameters to log could be **note**, **pitch**, **dur**, **octave** etc...
|
||||
|
||||
${makeExample(
|
||||
"Logging values from the chain",
|
||||
`
|
||||
"Logging values from the chain",
|
||||
`
|
||||
beat(1) :: sound("sine").pitch(rI(1,6)).log("note").out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Logging values from ziffers pattern",
|
||||
`
|
||||
"Logging values from ziffers pattern",
|
||||
`
|
||||
z1("0 3 2 5").scale("rocritonic").sound("sine").log("pitch","note","key").out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Conditional chaining
|
||||
|
||||
@ -101,17 +101,17 @@ There are cases when you don't always want to apply one or many elements that ar
|
||||
All functions from the sound object can be used to modify the event, for example:
|
||||
|
||||
${makeExample(
|
||||
"Modifying sound events with probabilities",
|
||||
`
|
||||
"Modifying sound events with probabilities",
|
||||
`
|
||||
beat(.5) && sound('fhh')
|
||||
.odds(1/4, s => s.speed(irand(1,4)))
|
||||
.rarely(s => s.room(0.5).size(8).speed(0.5))
|
||||
.out()`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
${makeExample(
|
||||
"Chance to play a random note",
|
||||
`
|
||||
"Chance to play a random note",
|
||||
`
|
||||
rhythm(.5, 3, 8) && sound('pluck').note(38).out()
|
||||
beat(.5) && sound('pluck').note(60)
|
||||
.often(s => s.note(57))
|
||||
@ -119,8 +119,8 @@ beat(.5) && sound('pluck').note(60)
|
||||
.note(62)
|
||||
.room(0.5).size(3)
|
||||
.out()`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
There is a growing collection of probability and chance methods you can use:
|
||||
|
||||
@ -145,14 +145,14 @@ There is a growing collection of probability and chance methods you can use:
|
||||
The conditional chaining also applies to MIDI. Values can also be incremented using <ic>+=</ic> notation.
|
||||
|
||||
${makeExample(
|
||||
"Modifying midi events with probabilities",
|
||||
`beat(.5) && midi(60).channel(1)
|
||||
"Modifying midi events with probabilities",
|
||||
`beat(.5) && midi(60).channel(1)
|
||||
.odds(1/4, n => n.channel(2))
|
||||
.often(n => n.note+=4)
|
||||
.sometimes(s => s.velocity(irand(50,100)))
|
||||
.out()`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
## Ziffers
|
||||
|
||||
@ -165,8 +165,8 @@ Ziffers patterns can be chained to <ic>sound()</ic> and <ic>midi()</ic> as well.
|
||||
* <ic>midi()</ic> - for outputting pattern as MIDI (See **MIDI**)
|
||||
|
||||
${makeExample(
|
||||
"Ziffer player using a sound chain and probabilities!",
|
||||
`
|
||||
"Ziffer player using a sound chain and probabilities!",
|
||||
`
|
||||
z1('s 0 5 7 0 3 7 0 2 7 0 1 7 0 1 6 5 4 3 2')
|
||||
.octave([0, 1].beat(2) - 1)
|
||||
.scale('pentatonic').sound('pluck')
|
||||
@ -174,7 +174,7 @@ z1('s 0 5 7 0 3 7 0 2 7 0 1 7 0 1 6 5 4 3 2')
|
||||
.odds(1/2, n => n.speed(0.5))
|
||||
.room(0.5).size(0.5).out()
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
`;
|
||||
};
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const functions = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -15,20 +15,20 @@ You can control scripts programatically. This is the core concept of Topos after
|
||||
- <ic>copy_script(from: number, to: number)</ic>: copies a local script denoted by its number to another local script. **This is a destructive operation!**
|
||||
|
||||
${makeExample(
|
||||
"Calling a script! The most important feature!",
|
||||
`
|
||||
"Calling a script! The most important feature!",
|
||||
`
|
||||
beat(1) :: script(1)
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Calling mutliple scripts at the same time.",
|
||||
`
|
||||
"Calling mutliple scripts at the same time.",
|
||||
`
|
||||
beat(1) :: script(1, 3, 5)
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
## Math functions
|
||||
|
||||
@ -49,9 +49,36 @@ There are some very useful scaling methods taken from **SuperCollider**. You can
|
||||
- <ic>curve: number</ic>: <ic>0</ic> is linear, <ic>< 0</ic> is concave, negatively curved, <ic>> 0</ic> is convex, positively curved
|
||||
|
||||
${makeExample(
|
||||
"Scaling an LFO",
|
||||
`usine(1/2).linlin(0, 1, 0, 100)`,
|
||||
true,
|
||||
)}
|
||||
"Scaling an LFO",
|
||||
`usine(1/2).linlin(0, 1, 0, 100)`,
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
|
||||
## Delay functions
|
||||
|
||||
- <ic>delay(ms: number, func: Function): void</ic>: Delays the execution of a function by a given number of milliseconds.
|
||||
|
||||
${makeExample(
|
||||
"Phased woodblocks",
|
||||
`
|
||||
// Some very low-budget version of phase music
|
||||
beat(.5) :: delay(usine(.125) * 80, () => sound('east').out())
|
||||
beat(.5) :: delay(50, () => sound('east').out())
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>delayr(ms: number, nb: number, func: Function): void</ic>: Delays the execution of a function by a given number of milliseconds, repeated a given number of times.
|
||||
|
||||
${makeExample(
|
||||
"Another woodblock texture",
|
||||
`
|
||||
beat(1) :: delayr(50, 4, () => sound('east').speed([0.5,.25].beat()).out())
|
||||
flip(2) :: beat(2) :: delayr(150, 4, () => sound('east').speed([0.5,.25].beat() * 4).out())
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
`;
|
||||
};
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const generators = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -15,8 +15,8 @@ Once the generator is cached the values will be returned from the named cache ev
|
||||
The resulted values can be played using either <ic>pitch()</ic> or <ic>freq()</ic> or as Ziffers patterns. When playing the values using <ic>pitch()</ic> different scales and chained methods can be used to alter the result, for example <ic>mod(value: number)</ic> to limit the integer range or <ic>scale(name: string)</ic> etc. to change the resulting note.
|
||||
|
||||
${makeExample(
|
||||
"Simple looping generator function",
|
||||
`
|
||||
"Simple looping generator function",
|
||||
`
|
||||
function* simple() {
|
||||
let x = 0;
|
||||
while (x < 12) {
|
||||
@ -27,12 +27,12 @@ function* simple() {
|
||||
|
||||
beat(.25) && sound("triangle").pitch(cache("simple",simple())).scale("minor").out()
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
${makeExample(
|
||||
"Infinite frequency generator",
|
||||
`
|
||||
"Infinite frequency generator",
|
||||
`
|
||||
function* poly(x=0) {
|
||||
while (true) {
|
||||
const s = Math.tan(x/10)+Math.sin(x/20);
|
||||
@ -43,14 +43,14 @@ ${makeExample(
|
||||
|
||||
beat(.125) && sound("triangle").freq(cache("mathyshit",poly())).out()
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
When you want to dance with a dynamical system in controlled musical chaos, Topos is waiting for you:
|
||||
|
||||
${makeExample(
|
||||
"Truly scale free chaos inspired by Lorentz attractor",
|
||||
`
|
||||
"Truly scale free chaos inspired by Lorentz attractor",
|
||||
`
|
||||
function* strange(x = 0.1, y = 0, z = 0, rho = 28, beta = 8 / 3, zeta = 10) {
|
||||
while (true) {
|
||||
const dx = 10 * (y - x);
|
||||
@ -71,8 +71,8 @@ ${makeExample(
|
||||
.adsr(.15,.1,.1,.1)
|
||||
.log("freq").out()
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
${makeExample(
|
||||
"Henon and his discrete music",
|
||||
@ -100,8 +100,8 @@ ${makeExample(
|
||||
)};
|
||||
|
||||
${makeExample(
|
||||
"1970s fractal dream",
|
||||
`
|
||||
"1970s fractal dream",
|
||||
`
|
||||
function* rossler(x = 0.1, y = 0.1, z = 0.1, a = 0.2, b = 0.2, c = 5.7) {
|
||||
while (true) {
|
||||
const dx = - y - z;
|
||||
@ -122,8 +122,8 @@ ${makeExample(
|
||||
.adsr(0,.1,.1,.1)
|
||||
.log("freq").out()
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
true,
|
||||
)};
|
||||
|
||||
|
||||
## OEIS integer sequences
|
||||
@ -145,7 +145,7 @@ ${makeExample(
|
||||
.gain(1).out()
|
||||
`,
|
||||
true,
|
||||
)};
|
||||
)};
|
||||
|
||||
## Using generators with Ziffers
|
||||
|
||||
@ -153,7 +153,7 @@ Alternatively generators can be used with Ziffers to generate longer patterns. I
|
||||
|
||||
${makeExample(
|
||||
"Ziffers patterns using a generator functions",
|
||||
`
|
||||
`
|
||||
function* poly(x) {
|
||||
while (true) {
|
||||
yield 64 * Math.pow(x, 6) - 480 * Math.pow(x, 4) + 720 * Math.pow(x, 2);
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const lfos = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -14,46 +14,46 @@ Low Frequency Oscillators (_LFOs_) are an important piece in any digital audio w
|
||||
- <ic>usine(freq: number = 1, phase: number = 0): number</ic>: returns a sinusoïdal oscillation between <ic>0</ic> and <ic>1</ic>. The <ic>u</ic> stands for _unipolar_.
|
||||
|
||||
${makeExample(
|
||||
"Modulating the speed of a sample player using a sine LFO",
|
||||
`beat(.25) && snd('cp').speed(1 + usine(0.25) * 2).out()`,
|
||||
true,
|
||||
)};
|
||||
"Modulating the speed of a sample player using a sine LFO",
|
||||
`beat(.25) && snd('cp').speed(1 + usine(0.25) * 2).out()`,
|
||||
true,
|
||||
)};
|
||||
|
||||
- <ic>triangle(freq: number = 1, phase: number = 0): number</ic>: returns a triangle oscillation between <ic>-1</ic> and <ic>1</ic>.
|
||||
- <ic>utriangle(freq: number = 1, phase: number = 0): number</ic>: returns a triangle oscillation between <ic>0</ic> and <ic>1</ic>. The <ic>u</ic> stands for _unipolar_.
|
||||
|
||||
${makeExample(
|
||||
"Modulating the speed of a sample player using a triangle LFO",
|
||||
`beat(.25) && snd('cp').speed(1 + utriangle(0.25) * 2).out()`,
|
||||
true,
|
||||
)}
|
||||
"Modulating the speed of a sample player using a triangle LFO",
|
||||
`beat(.25) && snd('cp').speed(1 + utriangle(0.25) * 2).out()`,
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>saw(freq: number = 1, phase: number = 0): number</ic>: returns a sawtooth-like oscillation between <ic>-1</ic> and <ic>1</ic>.
|
||||
- <ic>usaw(freq: number = 1, phase: number = 0): number</ic>: returns a sawtooth-like oscillation between <ic>0</ic> and <ic>1</ic>. The <ic>u</ic> stands for _unipolar_.
|
||||
|
||||
${makeExample(
|
||||
"Modulating the speed of a sample player using a saw LFO",
|
||||
`beat(.25) && snd('cp').speed(1 + usaw(0.25) * 2).out()`,
|
||||
true,
|
||||
)}
|
||||
"Modulating the speed of a sample player using a saw LFO",
|
||||
`beat(.25) && snd('cp').speed(1 + usaw(0.25) * 2).out()`,
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>square(freq: number = 1, duty: number = .5): number</ic>: returns a square wave oscillation between <ic>-1</ic> and <ic>1</ic>. You can also control the duty cycle using the <ic>duty</ic> parameter.
|
||||
- <ic>usquare(freq: number = 1, duty: number = .5): number</ic>: returns a square wave oscillation between <ic>0</ic> and <ic>1</ic>. The <ic>u</ic> stands for _unipolar_. You can also control the duty cycle using the <ic>duty</ic> parameter.
|
||||
|
||||
${makeExample(
|
||||
"Modulating the speed of a sample player using a square LFO",
|
||||
`beat(.25) && snd('cp').speed(1 + usquare(0.25, 0, 0.25) * 2).out()`,
|
||||
true,
|
||||
)};
|
||||
"Modulating the speed of a sample player using a square LFO",
|
||||
`beat(.25) && snd('cp').speed(1 + usquare(0.25, 0, 0.25) * 2).out()`,
|
||||
true,
|
||||
)};
|
||||
|
||||
- <ic>noise(times: number = 1)</ic>: returns a random value between -1 and 1.
|
||||
- <ic>unoise(times: number = 1)</ic>: returns a random value between 0 and 1.
|
||||
|
||||
${makeExample(
|
||||
"Modulating the speed of a sample player using noise",
|
||||
`beat(.25) && snd('cp').speed(1 + noise() * 2).out()`,
|
||||
true,
|
||||
)};
|
||||
"Modulating the speed of a sample player using noise",
|
||||
`beat(.25) && snd('cp').speed(1 + noise() * 2).out()`,
|
||||
true,
|
||||
)};
|
||||
|
||||
`;
|
||||
};
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const patterns = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -10,24 +10,24 @@ export const patterns = (application: Editor): string => {
|
||||
It means that the following:
|
||||
|
||||
${makeExample(
|
||||
"Boring kick",
|
||||
`
|
||||
"Boring kick",
|
||||
`
|
||||
beat(1)::sound('kick').out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
can be turned into something more interesting like this easily:
|
||||
|
||||
${makeExample(
|
||||
"Less boring kick",
|
||||
`
|
||||
"Less boring kick",
|
||||
`
|
||||
let c = [1,2].dur(3, 1)
|
||||
beat([1, 0.5, 0.25].dur(0.75, 0.25, 1) / c)::sound(['kick', 'fsoftsnare'].beat(0.75))
|
||||
.ad(0, .25).shape(usine(1/2)*0.5).speed([1, 2, 4].beat(0.5)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
**Topos** comes with a lot of array methods to deal with musical patterns of increasing complexity. Some knowledge of patterns and how to use them will help you to break out of simple loops and repeating structures. The most basic JavaScript data structure is the [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). Topos is extending it with custom methods to describe patterns that evolve over time. These methods can often be chained to compose more complex expressions: <ic>[1, 2, 3].repeatOdd(5).palindrome().beat()</ic>.
|
||||
@ -37,18 +37,18 @@ beat([1, 0.5, 0.25].dur(0.75, 0.25, 1) / c)::sound(['kick', 'fsoftsnare'].beat(0
|
||||
- <ic>beat(division: number)</ic>: this method will return the next value in the list every _n_ pulses. By default, <ic>1</ic> equals to one beat but integer and floating point number values are supported as well. This method is extremely powerful and can be used for many different purposes. Check out the examples.
|
||||
|
||||
${makeExample(
|
||||
"Light drumming",
|
||||
`
|
||||
"Light drumming",
|
||||
`
|
||||
// Every bar, use a different rhythm
|
||||
beat([1, 0.75].beat(4)) :: sound('cp').out()
|
||||
beat([0.5, 1].beat(4)) :: sound('kick').out()
|
||||
beat(2)::snd('snare').shape(.5).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
${makeExample(
|
||||
"Using beat to create arpeggios",
|
||||
`
|
||||
"Using beat to create arpeggios",
|
||||
`
|
||||
// Arpeggio using pulse divisions
|
||||
beat([.5, .25].beat(0.5)) :: sound('sine')
|
||||
.lpf(100+usine(1/4)*400).lpad(2, 0, .25)
|
||||
@ -62,25 +62,25 @@ beat([.5, .25].beat(0.5)) :: sound('sine')
|
||||
.delayfb(0.5)
|
||||
.out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
${makeExample(
|
||||
"Cool ambiance",
|
||||
`
|
||||
"Cool ambiance",
|
||||
`
|
||||
beat(.5) :: snd(['kick', 'hat'].beat(0.5)).out()
|
||||
beat([2,4].beat(2)) :: snd('shaker').delay(.5).delayfb(.75).delayt(0.125).out()
|
||||
flip(2)::beat(1)::snd('froomy').out()
|
||||
flip(4)::beat(2)::snd('pad').n(2).shape(.5)
|
||||
.orbit(2).room(0.9).size(0.9).release(0.5).out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
- <ic>bar(value: number = 1)</ic>: returns the next value every bar (if <ic>value = 1</ic>). Using a larger value will return the next value every <ic>n</ic> bars.
|
||||
|
||||
${makeExample(
|
||||
"A simple drumbeat in no time!",
|
||||
`
|
||||
"A simple drumbeat in no time!",
|
||||
`
|
||||
beat(1)::sound(['kick', 'hat', 'snare', 'hat'].beat()).out()
|
||||
beat([1/4, 1/2].dur(1.5, 0.5))::sound(['jvbass', 'fikea'].bar())
|
||||
.ad(0, .25).room(0.5).size(2).resonance(0.15).lpf(
|
||||
@ -88,12 +88,12 @@ beat([1/4, 1/2].dur(1.5, 0.5))::sound(['jvbass', 'fikea'].bar())
|
||||
* [1, 2].bar())
|
||||
.out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Using beat and bar in the same example",
|
||||
`
|
||||
"Using beat and bar in the same example",
|
||||
`
|
||||
beat(2)::snd('snare').out()
|
||||
beat([1, 0.5].beat()) :: sound(['bass3'].bar())
|
||||
.freq(100).n([12, 14].bar())
|
||||
@ -102,13 +102,13 @@ beat([1, 0.5].beat()) :: sound(['bass3'].bar())
|
||||
.speed([1,2,3].beat())
|
||||
.out()
|
||||
`,
|
||||
)}
|
||||
)}
|
||||
|
||||
- <ic>dur(...list: numbers[])</ic> : keeps the same value for a duration of <ic>n</ic> beats corresponding to the <ic>nth</ic> number of the list you provide.
|
||||
|
||||
${makeExample(
|
||||
"Holding a value for n beats",
|
||||
`
|
||||
"Holding a value for n beats",
|
||||
`
|
||||
// The second note is kept for twice as long
|
||||
beat(0.5)::sound('notes').n([1,2].dur(1, 2))
|
||||
.room(0.5).size(8).delay(0.125).delayt(1/8)
|
||||
@ -117,12 +117,12 @@ beat(0.5)::sound('notes').n([1,2].dur(1, 2))
|
||||
beat(1)::sound(['kick', 'fsnare'].dur(3, 1))
|
||||
.n([0,3].dur(3, 1)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Patterning with ternary statements",
|
||||
`
|
||||
"Patterning with ternary statements",
|
||||
`
|
||||
const dada = flipbar(2) ? [0,[3,5,-1].bar(3),2,3] : [9,8,9,6]
|
||||
beat(0.5) :: sound('wt_hvoice:3')
|
||||
.pitch(dada.beat(0.5))
|
||||
@ -136,8 +136,8 @@ beat(1) :: sound('kick').n(4).out()
|
||||
onbeat([0.5,0.8].beat(1),2) :: sound('snare').out()
|
||||
onbeat(0.5,0.8,1,1.5,2,2.5,3,4) :: sound('hh').out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Iteration using a counter
|
||||
|
||||
@ -145,130 +145,130 @@ onbeat(0.5,0.8,1,1.5,2,2.5,3,4) :: sound('hh').out()
|
||||
- <ic>$(name,limit?,step?)</ic>: shorter alias for the counter.
|
||||
|
||||
${makeExample(
|
||||
"Using counter to iterate over a list",
|
||||
`
|
||||
"Using counter to iterate over a list",
|
||||
`
|
||||
beat(0.5) :: sound("bd").gain(line(0,1,0.01).$("ramp")).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Manipulating notes and scales
|
||||
|
||||
- <ic>pitch()</ic>: convert a list of integers to pitch classes
|
||||
|
||||
${makeExample(
|
||||
"Converting a list of integers to pitch classes using key and scale",
|
||||
`
|
||||
"Converting a list of integers to pitch classes using key and scale",
|
||||
`
|
||||
beat(0.25) :: snd('sine')
|
||||
.pitch([0,1,2,3,4,6,7,8].beat(0.125))
|
||||
.key(["F4","F3"].beat(2.0))
|
||||
.scale("minor").ad(0, .25).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>semitones(number[], ...args?)</ic>: Create scale from semitone intervals.
|
||||
|
||||
${makeExample(
|
||||
"Play pitches from scale created from semitone intervals",
|
||||
`
|
||||
"Play pitches from scale created from semitone intervals",
|
||||
`
|
||||
beat(1) :: sound('gtr').pitch([0, 4, 3, 2].beat()).key(64)
|
||||
.semitones(1, 1, 3, 1, 1, 2, 3).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>cents(number[], ...args?)</ic>: Create scale from cent intervals.
|
||||
|
||||
${makeExample(
|
||||
"Play pitches from scale created from cent intervals",
|
||||
`
|
||||
"Play pitches from scale created from cent intervals",
|
||||
`
|
||||
rhythm([0.5,0.25].beat(1),14,16) :: sound('pluck')
|
||||
.stretch(ir(1,5)).pitch(ir(0,6)).key(57)
|
||||
.stretch(iR(1,5)).pitch(iR(0,6)).key(57)
|
||||
.cents(120,270,540,670,785,950,1215).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>ratios(number[], ...args?)</ic>: Create scale from ratios.
|
||||
|
||||
${makeExample(
|
||||
"Play pitches from scale created from ratios",
|
||||
`
|
||||
"Play pitches from scale created from ratios",
|
||||
`
|
||||
rhythm([0.5,0.25].beat(0.25),5,7) :: sound('east:3')
|
||||
.pitch([0,1,2,3,4,5,6,7,8,9,10,11].beat(0.25)).key(67)
|
||||
.ratios(2/11,4/11,6/11,8/11,10/11,11/11).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>edo(number, scale?: string|number[])</ic>: Create scale from equal divisions of the octave. Creates chromatic scale by default.
|
||||
|
||||
${makeExample(
|
||||
"Play pitches from scale created from equal divisions of the octave",
|
||||
`
|
||||
"Play pitches from scale created from equal divisions of the octave",
|
||||
`
|
||||
z0("e bd bd <bd bd [bd bd] [bd bd bd bd]>").sound().out()
|
||||
flipbar(1) :: rhythm(.25,14,16) :: sound("ST10:30").stretch(3).gain(0.5)
|
||||
.pitch([0,10,r(20,40),r(100,200),r(-200,200),r(200,300),200,r(3,666)].beat([1.0,0.5,0.25].bar(6)))
|
||||
.octave(r(-6,6))
|
||||
.edo(666,"rocritonic")
|
||||
.out()
|
||||
rhythm(2.0,26,32) :: sound("ST20").n([22,5,24,34,31,5,11,19].pick()).stretch(ir(1,6))
|
||||
.pitch(ir(127,300))
|
||||
rhythm(2.0,26,32) :: sound("ST20").n([22,5,24,34,31,5,11,19].pick()).stretch(rI(1,6))
|
||||
.pitch(rI(127,300))
|
||||
.edo(666)
|
||||
.out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
- <ic>scale(scale: string, base note: number)</ic>: Map each element of the list to the closest note of the slected scale. [0, 2, 3, 5 ].scale("major", 50) returns [50, 52, <ic>54</ic>, 55]. You can use western scale names like (Major, Minor, Minor pentatonic ...) or [zeitler](https://ianring.com/musictheory/scales/traditions/zeitler) scale names. Alternatively you can also use the integers as used by Ian Ring in his [study of scales](https://ianring.com/musictheory/scales/).
|
||||
|
||||
${makeExample(
|
||||
"Mapping the note array to the E3 major scale",
|
||||
`
|
||||
"Mapping the note array to the E3 major scale",
|
||||
`
|
||||
beat(1) :: snd('gtr')
|
||||
.note([0, 5, 2, 1, 7].scale("Major", 52).beat())
|
||||
.out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>scaleArp(scale: string, mask: number)</ic>: extrapolate a custom-masked scale from each list elements. [0].scale("major", 3) returns [0,2,4]. <ic>scaleArp</ic> supports the same scales as <ic>scale</ic>.
|
||||
|
||||
${makeExample(
|
||||
"Extrapolate a 3-elements Mixolydian scale from 2 notes",
|
||||
`
|
||||
"Extrapolate a 3-elements Mixolydian scale from 2 notes",
|
||||
`
|
||||
beat(1) :: snd('gtr')
|
||||
.note([0, 5].scaleArp("mixolydian", 3).beat() + 50)
|
||||
.out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Iteration using the mouse
|
||||
|
||||
- <ic>mouseX()</ic> / <ic>mouseY()</ic>: divides the screen in <ic>n</ic> zones and returns the value corresponding to the mouse position on screen.</ic>
|
||||
|
||||
${makeExample(
|
||||
"Controlling an arpeggio (octave and note) with mouse",
|
||||
`
|
||||
"Controlling an arpeggio (octave and note) with mouse",
|
||||
`
|
||||
beat(0.25)::sound('wt_piano')
|
||||
.note([0,2,3,4,5,7,8,9,11,12].scale(
|
||||
'minor', 30 + [0,12,24].mouseY()).mouseX())
|
||||
.room(0.5).size(4).lpad(-2, .2).lpf(500, 0.3)
|
||||
.ad(0, .2).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Simple data operations
|
||||
|
||||
- <ic>palindrome()</ic>: Concatenates a list with the same list in reverse.
|
||||
|
||||
${makeExample(
|
||||
"Palindrome filter sweep",
|
||||
`
|
||||
"Palindrome filter sweep",
|
||||
`
|
||||
beat([1,.5,.25].beat()) :: snd('wt_stereo')
|
||||
.speed([1, 0.5, 0.25])
|
||||
.pan(r(0, 1)).freq([100,200,300].beat(0.25))
|
||||
@ -277,15 +277,15 @@ beat([1,.5,.25].beat()) :: snd('wt_stereo')
|
||||
.lpf([500,1000,2000,4000].palindrome().beat())
|
||||
.lpad(4, 0, .25).sustain(0.125).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>random(index: number)</ic>: pick a random element in the given list.
|
||||
- <ic>rand(index: number)</ic>: shorter alias for the same method.
|
||||
|
||||
${makeExample(
|
||||
"Sipping some gasoline at the robot bar",
|
||||
`
|
||||
"Sipping some gasoline at the robot bar",
|
||||
`
|
||||
// rand, random and pick are doing the same thing!
|
||||
beat(1)::snd('fhardkick').shape(0.5)
|
||||
.ad(0, .1).lpf(500).db(-12).out()
|
||||
@ -296,69 +296,69 @@ beat([.5, 1].rand() / 2) :: snd(
|
||||
.lpf([5000,3000,2000].pick())
|
||||
.end(0.5).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>pick()</ic>: pick a random element in the list.
|
||||
|
||||
${makeExample(
|
||||
"Picking values in lists",
|
||||
`
|
||||
"Picking values in lists",
|
||||
`
|
||||
beat(0.25)::sound(['ftabla', 'fwood'].pick())
|
||||
.speed([1,2,3,4].pick()).ad(0, .125).n(ir(1,10))
|
||||
.room(0.5).size(1).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>degrade(amount: number)</ic>: removes _n_% of the list elements. Lists can be degraded as long as one element remains. The amount of degradation is given as a percentage.
|
||||
|
||||
${makeExample(
|
||||
"Amen break suffering from data loss",
|
||||
`
|
||||
"Amen break suffering from data loss",
|
||||
`
|
||||
// Tweak the value to degrade this amen break even more!
|
||||
beat(.25)::snd('amencutup').n([1,2,3,4,5,6,7,8,9].degrade(20).loop($(1))).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>repeat(amount: number)</ic>: repeat every list elements _n_ times.
|
||||
- <ic>repeatEven(amount: number)</ic>: repeat every pair element of the list _n_ times.
|
||||
- <ic>repeatOdd(amount: number)</ic>: repeat every odd element of the list _n_ times.
|
||||
|
||||
${makeExample(
|
||||
"Repeating samples a given number of times",
|
||||
`
|
||||
"Repeating samples a given number of times",
|
||||
`
|
||||
beat(.25)::sound('amencutup').n([1,2,3,4,5,6,7,8].repeat(4).beat(.25)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>loop(index: number)</ic>: loop takes one argument, the _index_. It allows you to iterate over a list using an iterator such as a counter. This is super useful to control how you are accessing values in a list without relying on a temporal method such as <ic>.beat()</ic> or </ic>.bar()</ic>.
|
||||
|
||||
${makeExample(
|
||||
"Don't you know how to count up to 5?",
|
||||
`
|
||||
"Don't you know how to count up to 5?",
|
||||
`
|
||||
beat(1) :: sound('numbers').n([1,2,3,4,5].loop($(3, 10, 2))).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>shuffle(): this</ic>: shuffles a list! Simple enough!
|
||||
|
||||
${makeExample(
|
||||
"Shuffling a list for extra randomness",
|
||||
`
|
||||
"Shuffling a list for extra randomness",
|
||||
`
|
||||
beat(1) :: sound('numbers').n([1,2,3,4,5].shuffle().loop($(1)).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>rotate(steps: number)</ic>: rotate a list to the right _n_ times. The last value become the first, rinse and repeat.
|
||||
|
||||
${makeExample(
|
||||
"To make things more complex... here you go",
|
||||
`
|
||||
"To make things more complex... here you go",
|
||||
`
|
||||
beat(.25) :: snd('sine').fmi([1.99, 2])
|
||||
.ad(0, .125).lpf(500+r(1,400))
|
||||
.lpad(usine()*8, 0, .125)
|
||||
@ -369,21 +369,21 @@ beat(.25) :: snd('sine').fmi([1.99, 2])
|
||||
.beat(.25)) // while the index changes
|
||||
.out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Filtering
|
||||
|
||||
- <ic>unique()</ic>: filter a list to remove repeated values.
|
||||
|
||||
${makeExample(
|
||||
"Demonstrative filtering. Final list is [100, 200]",
|
||||
`
|
||||
"Demonstrative filtering. Final list is [100, 200]",
|
||||
`
|
||||
// Remove unique and 100 will repeat four times!
|
||||
beat(1)::snd('sine').sustain(0.1).freq([100,100,100,100,200].unique().beat()).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
## Simple math operations
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const probabilities = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -13,12 +13,12 @@ There are some simple functions to play with probabilities.
|
||||
- <ic>irand(min: number, max:number)</ic>: returns a random integer between <ic>min</ic> and <ic>max</ic>. Shorthands <ic>ir()</ic> or <ic>rI()</ic>.
|
||||
|
||||
${makeExample(
|
||||
"Bleep bloop, what were you expecting?",
|
||||
`
|
||||
"Bleep bloop, what were you expecting?",
|
||||
`
|
||||
rhythm(0.125, 10, 16) :: sound('sid').n(4).note(50 + irand(50, 62) % 8).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
|
||||
- <ic>prob(p: number)</ic>: return <ic>true</ic> _p_% of time, <ic>false</ic> in other cases.
|
||||
@ -26,14 +26,14 @@ rhythm(0.125, 10, 16) :: sound('sid').n(4).note(50 + irand(50, 62) % 8).out()
|
||||
|
||||
|
||||
${makeExample(
|
||||
"The Teletype experience!",
|
||||
`
|
||||
"The Teletype experience!",
|
||||
`
|
||||
prob(50) :: script(1);
|
||||
prob(60) :: script(2);
|
||||
prob(80) :: script(toss() ? script(3) : script(4))
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
- <ic>seed(val: number|string)</ic>: sets the seed of the random number generator. You can use a number or a string. The same seed will always return the same sequence of random numbers.
|
||||
|
||||
@ -59,28 +59,28 @@ By default chance operators will be evaluated 48 times within a beat. You can ch
|
||||
Examples:
|
||||
|
||||
${makeExample(
|
||||
"Using chance operators",
|
||||
`
|
||||
"Using chance operators",
|
||||
`
|
||||
rarely() :: sound('hh').out(); // Rarely 48 times is still a lot
|
||||
rarely(4) :: sound('bd').out(); // Rarely in 4 beats is bit less
|
||||
rarely(8) :: sound('east').out(); // Rarely in 8 beats is even less
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Using chance with other operators",
|
||||
`
|
||||
"Using chance with other operators",
|
||||
`
|
||||
frequently() :: beat(1) :: sound('kick').out();
|
||||
often() :: beat(0.5) :: sound('hh').out();
|
||||
sometimes() :: onbeat(1,3) :: sound('snare').out();
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Using chance with chaining",
|
||||
`
|
||||
"Using chance with chaining",
|
||||
`
|
||||
beat(0.5) && sound("bd")
|
||||
.freq(100)
|
||||
.sometimes(s=>s.crush(2.5))
|
||||
@ -92,7 +92,7 @@ ${makeExample(
|
||||
.almostNever(n=>n.freq(400))
|
||||
.out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
`;
|
||||
};
|
||||
@ -1,5 +1,5 @@
|
||||
import { type Editor } from "../../main";
|
||||
import { makeExampleFactory } from "../Documentation";
|
||||
import { makeExampleFactory } from "../../Documentation";
|
||||
|
||||
export const variables = (application: Editor): string => {
|
||||
const makeExample = makeExampleFactory(application);
|
||||
@ -12,22 +12,22 @@ By default, each script is independant from each other. The variables defined in
|
||||
There is a <ic>global</ic> object that you can use to store and retrieve information. It is a simple key/value store. You can store any type of data in it:
|
||||
|
||||
${makeExample(
|
||||
"Setting a global variable",
|
||||
`
|
||||
"Setting a global variable",
|
||||
`
|
||||
// This is script n°3
|
||||
global.my_variable = 2
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Getting that variable back and printing!",
|
||||
`
|
||||
"Getting that variable back and printing!",
|
||||
`
|
||||
// This is script n°4
|
||||
log(global.my_variable)
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
Now your scripts can share information with each other!
|
||||
|
||||
@ -47,30 +47,30 @@ You will often need to use iterators and/or counters to index over data structur
|
||||
**Note:** Counters also come with a secret syntax. They can be called with the **$** symbol!
|
||||
|
||||
${makeExample(
|
||||
"Iterating over a list of samples using a counter",
|
||||
`
|
||||
"Iterating over a list of samples using a counter",
|
||||
`
|
||||
rhythm(.25, 6, 8) :: sound('dr').n($(1)).end(.25).out()
|
||||
`,
|
||||
true,
|
||||
)}
|
||||
true,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Using a more complex counter",
|
||||
`
|
||||
"Using a more complex counter",
|
||||
`
|
||||
// Limit is 20, step is 5
|
||||
rhythm(.25, 6, 8) :: sound('dr').n($(1, 20, 5)).end(.25).out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
${makeExample(
|
||||
"Calling the drunk mechanism",
|
||||
`
|
||||
"Calling the drunk mechanism",
|
||||
`
|
||||
// Limit is 20, step is 5
|
||||
rhythm(.25, 6, 8) :: sound('dr').n(drunk()).end(.25).out()
|
||||
`,
|
||||
false,
|
||||
)}
|
||||
false,
|
||||
)}
|
||||
|
||||
|
||||
|
||||