(...array: T[]): T => {
/**
* Returns a random element from an array.
@@ -940,19 +862,6 @@ export class UserAPI {
return final_pulses.some((p) => p == true);
};
- stop = (): void => {
- /**
- * Stops the clock.
- *
- * @see silence
- * @see hush
- */
- this.app.clock.pause();
- this.app.setButtonHighlighting("pause", true);
- };
- silence = this.stop;
- hush = this.stop;
-
prob = (p: number): boolean => {
/**
* Returns true p% of the time.
@@ -977,7 +886,7 @@ export class UserAPI {
return this.randomGen() > 0.5;
};
- min = (...values: number[]): number => {
+ public min = (...values: number[]): number => {
/**
* Returns the minimum value of a list of numbers.
*
@@ -987,7 +896,7 @@ export class UserAPI {
return Math.min(...values);
};
- max = (...values: number[]): number => {
+ public max = (...values: number[]): number => {
/**
* Returns the maximum value of a list of numbers.
*
@@ -997,6 +906,20 @@ export class UserAPI {
return Math.max(...values);
};
+ public mean = (...values: number[]): number => {
+ /**
+ * Returns the mean of a list of numbers.
+ *
+ * @param values - The list of numbers
+ * @returns The mean value of the list of numbers
+ */
+ const sum = values.reduce(
+ (accumulator, currentValue) => accumulator + currentValue,
+ 0
+ );
+ return sum / values.length;
+ };
+
limit = (value: number, min: number, max: number): number => {
/**
* Limits a value between a minimum and a maximum.
@@ -1036,30 +959,24 @@ export class UserAPI {
};
public mod = (...n: number[]): boolean => {
- const results: boolean[] = n.map((value) => this.epulse() % value === 0);
+ const results: boolean[] = n.map(
+ (value) => this.epulse() % Math.floor(value * this.ppqn()) === 0
+ );
return results.some((value) => value === true);
};
public modbar = (...n: number[]): boolean => {
- const results: boolean[] = n.map((value) => this.bar() % value === 0);
+ const results: boolean[] = n.map(
+ (value) => this.bar() % Math.floor(value * this.ppqn()) === 0
+ );
return results.some((value) => value === true);
};
- // mod = (...pulse: number[]): boolean => {
- // /**
- // * Returns true if the current pulse is a modulo of any of the given pulses.
- // *
- // * @param pulse - The pulse to check for
- // * @returns True if the current pulse is a modulo of any of the given pulses
- // */
- // return pulse.some((p) => this.app.clock.time_position.pulse % p === 0);
- // };
-
// =============================================================
// Rythmic generators
// =============================================================
- euclid = (
+ public euclid = (
iterator: number,
pulses: number,
length: number,
@@ -1076,6 +993,7 @@ export class UserAPI {
*/
return this._euclidean_cycle(pulses, length, rotate)[iterator % length];
};
+ ec = this.euclid;
_euclidean_cycle(
pulses: number,
@@ -1216,20 +1134,30 @@ export class UserAPI {
return (this.triangle(freq, offset) + 1) / 2;
};
- square = (freq: number = 1, offset: number = 0): number => {
+ square = (
+ freq: number = 1,
+ offset: number = 0,
+ duty: number = 0.5
+ ): number => {
/**
- * Returns a square wave between -1 and 1.
+ * Returns a square wave with a specified duty cycle between -1 and 1.
*
- * @returns A square wave between -1 and 1
+ * @returns A square wave with a specified duty cycle between -1 and 1
* @see saw
* @see triangle
* @see sine
* @see noise
*/
- return this.saw(freq, offset) > 0 ? 1 : -1;
+ const period = 1 / freq;
+ const t = (Date.now() / 1000 + offset) % period;
+ return t / period < duty ? 1 : -1;
};
- usquare = (freq: number = 1, offset: number = 0): number => {
+ usquare = (
+ freq: number = 1,
+ offset: number = 0,
+ duty: number = 0.5
+ ): number => {
/**
* Returns a square wave between 0 and 1.
*
@@ -1238,7 +1166,7 @@ export class UserAPI {
* @returns A square wave between 0 and 1
* @see square
*/
- return (this.square(freq, offset) + 1) / 2;
+ return (this.square(freq, offset, duty) + 1) / 2;
};
noise = (): number => {
@@ -1268,8 +1196,9 @@ export class UserAPI {
sound = (sound: string) => {
return new Sound(sound, this.app);
};
-
+ snd = this.sound;
samples = samples;
+ soundMap = soundMap;
log = console.log;
diff --git a/src/Documentation.ts b/src/Documentation.ts
index 40ac497..e0b10f9 100644
--- a/src/Documentation.ts
+++ b/src/Documentation.ts
@@ -1,11 +1,15 @@
const key_shortcut = (shortcut: string): string => {
- return `${shortcut}`;
+ return `${shortcut}`;
+};
+
+const injectAvailableSamples = (): string => {
+ return "";
};
const introduction: string = `
# Welcome
-Welcome to the Topos documentation. This documentation companion is made to help you understand the software and the ideas behind Topos. You can summon it anytime by pressing ${key_shortcut(
+Welcome to the Topos documentation. These pages are made to help you understand the software and the ideas behind Topos. You can jump here anytime by pressing ${key_shortcut(
"Ctrl + D"
)}. Press again to make the documentation disappear.
@@ -14,7 +18,11 @@ Welcome to the Topos documentation. This documentation companion is made to help
Topos is an _algorithmic_ sequencer. Topos uses small algorithms to represent musical sequences and processes. These can be written in just a few lines of code. Topos is made to be _live-coded_. The _live coder_ strives for the constant interaction with algorithms and sound during a musical performance. Topos is aiming to be a digital playground for live algorithmic music.
-Topos is deeply inspired by the [Monome Teletype](https://monome.org/). The Teletype is an open source hardware module for Eurorack synthesizers. While the Teletype was initially born as an hardware module, Topos is a web-browser based software sequencer from the same family! It is a sequencer, a scriptable interface, a companion for algorithmic music-making. Topos wishes to fullfill the same goal than the Teletype, keeping the same spirit alive on the web. It is free, open-source, and made to be shared and used by everyone.
+Topos is deeply inspired by the [Monome Teletype](https://monome.org/). The Teletype is/was an open source hardware module for Eurorack synthesizers. While the Teletype was initially born as an hardware module, Topos aims to be a web-browser based software sequencer from the same family! It is a sequencer, a scriptable interface, a companion for algorithmic music-making. Topos wishes to fullfill the same goal than the Teletype, keeping the same spirit alive on the web. It is free, open-source, and made to be shared and used by everyone.
+
+## How to read this documentation
+
+These pages have been conceived to introduce the core concepts first before diving to the more arcane bits. You can read them in order if you just found out about this software! Later on, this documentation will only help you to refresh your memory about some function, etc...
## Example
@@ -22,51 +30,53 @@ Press ${key_shortcut(
"Ctrl + G"
)} to switch to the global file. This is where everything starts! Evaluate the following script there by pasting and pressing ${key_shortcut(
"Ctrl + Enter"
-)}:
+)}. You are now making music:
-if (bar() % 4 > 2 ) {
- often() && mod(48) && sound('808bd').out()
- mod(24) && euclid($('a'), 3, 8) && sound('808sd').out()
- mod(seqbeat(24,12)) && euclid($('a'), 7, 8) && sound('hh')
- .delay(0.75).delaytime(0.75)
- .speed(seqbeat(1,2,3,4)).out()
- mod(48) && sound('bd').n(6).out()
-} else {
- mod(24) && sound('hh').n(seqbeat(1,2,3,4)).end(.01).out()
- mod(48) && sound('kick').out()
- mod(24) && euclid($('ba'), 5, 8) && sound('cp').out()
-}
+bpm(80)
+mod(0.25) :: sound('sawtooth')
+ .note(seqbar(
+ pick(60, 67, 63) - 12, pick(60, 67, 63) - 12,
+ pick(60, 67, 63) - 12 + 5, pick(60, 67, 63) - 12 + 5,
+ pick(60, 67, 63) - 12 + 7, pick(60, 67, 63) - 12 + 7) + (sometimes() ? 24 : 12))
+ .dur(0.1).fmi(8).fmh(4).room(0.9)
+ .gain(0.75).cutoff(500 + usine(8) * 10000)
+ .delay(0.5).delaytime(bpm() / 60 / 4 / 3)
+ .delayfeedback(0.25)
+ .out()
+mod(1) && snd('kick').out()
+mod(2) && snd('snare').out()
+mod(.5) && snd('hat').out()
`;
const software_interface: string = `
# Interface
-The Topos interface is molded around the core concepts at play: _scripts_ and _universes_. By mastering them, you will be able to compose complex algorithmic musical compositions.
+The Topos interface is molded around the core concepts of the software: _scripts_ and _universes_. By mastering the interface, you will already understand quite a lot about Topos and how to play music with it.
## Scripts
-Topos works by linking together several scripts into what is called a _universe_:
+Every Topos session is composed of several scripts. A set of scripts is called a _universe_. Every script is written using the JavaScript programming language and describes a musical or algorithmic process that takes place over time.
- the global script (${key_shortcut(
"Ctrl + G"
-)}): Evaluated for every clock pulse.
+)}): **Evaluated for every clock pulse**. The central piece, acting as the conductor for all the other scripts. You can also jam directly from the global script to test your ideas before pushing them to a separate script.
- the local scripts (${key_shortcut(
"Ctrl + L"
-)}): Evaluated _on demand_. Local scripts are storing musical parts, logic or whatever you need!
+)}): **Evaluated on demand**. Local scripts are used to store anything too complex to sit in the global script. It can be a musical process, a whole section of your composition, a complex controller that you've built for your hardware, etc...
- the init script (${key_shortcut(
"Ctrl + I"
-)}): Evaluated on program load. Used to set up the software (_bpm_, etc...).
+)}): **Evaluated on program load**. Used to set up the software the session to the desired state before playing (_bpm_, etc...).
- the note file (${key_shortcut(
"Ctrl + N"
-)}): Not evaluated. Used to store thoughts and ideas about the music you are making.
+)}): **Not evaluated**. Used to store your thoughts or commentaries about the session you are currently playing. It is nothing more than a scratchpad really!
## Universes
A set of files is called a _universe_. Topos can store several universes and switch immediately from one to another. You can switch between universes by pressing ${key_shortcut(
"Ctrl + B"
-)}. You can also create a new universe by entering a name that has never been used before. _Universes_ are only known by their names.
+)}. You can also create a new universe by entering a name that has never been used before. _Universes_ are only referenced by their names. Once a universe is loaded, it is not possible to call any data/code from any other universe.
Switching between universes will not stop the transport nor reset the clock. You are switching the context but time keeps flowing. This can be useful to prepare immediate transitions between songs and parts. Think of universes as an algorithmic set of music. All scripts in a given universe are aware about how many times they have been runned already. You can reset that value programatically.
@@ -76,33 +86,45 @@ You can clear the current universe by pressing the flame button on the top right
const time: string = `
# Time
-Time in Topos is handled by a _transport_ system. It allows you to **play**, **pause** and **reset** time. Time is quite simple to understand:
+Time in Topos can be **paused** and/or **resetted**. Musical time is flowing at a given **BPM** (_beats per minute_) like a regular drum machine. There are three core values that you will often interact with in one form or another:
- **bars**: how many bars have elapsed since the origin of time.
- **beats**: how many beats have elapsed since the beginning of the bar.
- **pulse**: how many pulses have elapsed since the last beat.
-The **pulse** is also known as the [PPQN](https://en.wikipedia.org/wiki/Pulses_per_quarter_note). By default, Topos is using a pulses per quarter note of 48. It means that the lowest possible rhythmic value is 1/48 of a quarter note. That's plenty of time already. Music is sequenced by playing around with these core time values.
+To change the tempo, use the bpm(number) function. You can interact with time using interface buttons, keyboard shortcuts but also by using the play(), pause() and stop() functions. You will soon learn how to manipulate time to your liking for backtracking, jumping forward, etc... The traditional timeline model has little value when you can script everything.
-**Note:** you will also learn how to manipulate time to backtrack, jump forward, etc... Your traditional timeline based playback will progressively get more spicy.
+**Note:** the bpm(number) function can serve both for getting and setting the **BPM** value.
-## Programming with time
+## Pulses
+
+To make a beat, you need a certain number of time grains or **pulses**. The **pulse** is also known as the [PPQN](https://en.wikipedia.org/wiki/Pulses_per_quarter_note). By default, Topos is using a _pulses per quarter note_ of 48. You can change it by using the ppqn(number) function. It means that the lowest possible rhythmic value is 1/48 of a quarter note. That's plenty of time already.
+
+**Note:** the ppqn(number) function can serve both for getting and setting the **PPQN** value.
+
+## Time Primitives
Every script can access the current time by using the following functions:
- bar(n: number): returns the current bar since the origin of time.
-- beat(n: number): returns the current beat since the origin of the bar.
+- beat(n: number): returns the current beat since the beginning of the bar.
-- ebeat(): returns the current beat since the origin of time.
+- ebeat(): returns the current beat since the origin of time (counting from 1).
- pulse(): returns the current bar since the origin of the beat.
-- epulse(): returns the current bar since the origin of time.
+- ppqn(): returns the current **PPQN** (see above).
-## Useful basic functions
+- bpm(): returns the current **BPM** (see above).
-Some functions are used very often as time primitives. They are used to create more complex rhythms and patterns:
+- time(): returns the current wall clock time, the real time of the system.
+
+These values are **extremely useful** to craft more complex syntax or to write musical scores. However, Topos is also offering more high-level sequencing functions to make it easier to play music.
+
+## Useful Basic Functions
+
+Some functions can be leveraged to play rhythms without thinking too much about the clock. Learn them well:
- beat(...values: number[]): returns true on the given beat. You can add any number of beat values, (_e.g._ onbeat(1.2,1.5,2.3,2.5)). The function will return true only for a given pulse, which makes this function very useful for drumming.
@@ -112,32 +134,52 @@ Some functions are used very often as time primitives. They are used to create m
onbeat(3) && sound('sd').out()
\`\`\`
-- mod(...values: number[]): returns true if the current pulse is a multiple of the given value. You can add any number of values, (_e.g._ mod(12,36)).
+- mod(...values: number[]): returns true if the current pulse is a multiple of the given value. You can add any number of values, (_e.g._ mod(.25,.75)). Note that 1 will equal to ppqn() pulses by default. Thus, mod(.5) for a **PPQN** of 48 will be 24 pulses.
\`\`\`javascript
- mod(48) && sound('bd').out()
- mod(pick(12,24)) && sound('hh').out()
- mod(24) && sound('jvbass').out()
+ mod(1) && sound('bd').out()
+ mod(pick(.25,.5)) && sound('hh').out()
+ mod(.5) && sound('jvbass').out()
\`\`\`
- onbar(...values: number[]): returns true if the bar is currently equal to any of the specified values.
- modbar(...values: number[]): returns true if the bar is currently a multiple of any of the specified values.
+## Rhythm generators
+
+We included a bunch of popular rhythm generators in Topos such as the euclidian rhythms algorithms or the one to generate rhythms based on a binary sequence. They all work using _iterators_ that you will gradually learn to use for iterating over lists.
+
+- euclid(iterator: number, pulses: number, length: number, rotate: number): boolean: generates true or false values from an euclidian rhythm sequence. This algorithm is very popular in the electronic music making world.
+
+\`\`\`javascript
+ mod(.5) && euclid($(1), 5, 8) && snd('kick').out()
+ mod(.5) && euclid($(2), 2, 8) && snd('sd').out()
+\`\`\`
+
+- bin(iterator: number, n: number): boolean: a binary rhythm generator. It transforms the given number into its binary representation (_e.g_ 34 becomes 100010). It then returns a boolean value based on the iterator in order to generate a rhythm.
+
+
+\`\`\`javascript
+ mod(.5) && euclid($(1), 34) && snd('kick').out()
+ mod(.5) && euclid($(2), 48) && snd('sd').out()
+\`\`\`
+
## Using time as a conditional
You can use the time functions as conditionals. The following example will play a pattern A for 2 bars and a pattern B for 2 bars:
\`\`\`javascript
if((bar() % 4) > 1) {
- mod(48) && sound('kick').out()
- rarely() && mod(24) && sound('sd').out()
- mod(24) && sound('jvbass').freq(500).out()
+ mod(1) && sound('kick').out()
+ rarely() && mod(.5) && sound('sd').out()
+ mod(.5) && sound('jvbass').freq(500).out()
} else {
- mod(24) && sound('hh').out()
- mod(36) && sound('cp').out()
- mod(24) && sound('jvbass').freq(250).out()
+ mod(.5) && sound('hh').out()
+ mod(.75) && sound('cp').out()
+ mod(.5) && sound('jvbass').freq(250).out()
}
\`\`\`
+
`;
const midi: string = `
@@ -152,10 +194,23 @@ You can use Topos to play MIDI thanks to the [WebMIDI API](https://developer.moz
\`\`\`javascript
bpm(80) // Setting a default BPM
- mod(24) && note(36 + seqbeat(0,12), {duration: 0.02})
- mod(12) && note(pick(64, 76), {duration: 0.05})
- mod(36) && note(seqbeat(64, 67, 69), {duration: 0.05})
- sometimes() && mod(12) && note(seqbeat(64, 67, 69) + 24, {duration: 0.5})
+ mod(.5) && note(36 + seqbeat(0,12)).duration(0.02).out()
+ mod(.25) && note(pick(64, 76)).duration(0.05).out()
+ mod(.75) && note(seqbeat(64, 67, 69)).duration(0.05).out()
+ sometimes() && mod(.25) && note(seqbeat(64, 67, 69) + 24).duration(0.05).out()
+\`\`\`
+
+### Note chaining
+
+The note(number) function can be chained to _specify_ a midi note more. For instance, you can add a duration, a velocity, a channel, etc...:
+
+\`\`\`javascript
+mod(0.25) && note(60)
+ .sometimes(n=>n.note(irand(40,60)))
+ .duration(0.05)
+ .channel(2)
+ .port("bespoke")
+ .out()
\`\`\`
## Control and Program Changes
@@ -184,7 +239,7 @@ You can use Topos to play MIDI thanks to the [WebMIDI API](https://developer.moz
- midi_clock(): send a MIDI Clock message. This function is used to synchronize Topos with other MIDI devices or DAWs.
\`\`\`javascript
- mod(12) && midi_clock() // Sending clock to MIDI device from the global buffer
+ mod(.25) && midi_clock() // Sending clock to MIDI device from the global buffer
\`\`\`
## MIDI Output Selection
@@ -210,8 +265,8 @@ I recommended you to run the following scripts in the global script (${key_short
The basic function to play a sound is sound('sample/synth').out(). If the given sound exists in the database, it will be automatically queried and will start playing once loaded. To play a very basic beat, evaluate the following script:
\`\`\`javascript
-mod(48) && sound('bd').out()
-mod(24) && sound('hh').out()
+mod(1) && sound('bd').out()
+mod(0.5) && sound('hh').out()
\`\`\`
In plain english, this translates to:
@@ -226,7 +281,7 @@ If you remove the **mod** instruction, you will end up with a deluge of kick dru
The .n(number) 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:
\`\`\`javascript
-mod(48) && sound('kick').n(pick(1,2,3,4,5,6,7,8)).out()
+mod(1) && sound('kick').n(pick(1,2,3,4,5,6,7,8)).out()
\`\`\`
Don't worry about the number. If it gets too big, it will be automatically wrapped to the number of samples in the folder.
@@ -235,8 +290,8 @@ Don't worry about the number. If it gets too big, it will be automatically wrapp
The sound('sample_name') function can be chained to _specify_ a sound more. For instance, you can add a filter and some effects to your high-hat:
\`\`\`javascript
-mod(24) && sound('hh')
- .speed(pick(1,2,3))
+mod(0.5) && sound('hh')
+ .sometimes(s=>s.speed(pick(1,5,10)))
.room(0.5)
.cutoff(usine(2) * 5000)
.out()
@@ -279,6 +334,15 @@ No sound will play until you add .out() at the end of the chain.
| out() | Returns an object processed by the superdough function, using the current values in the values object and the pulse_duration from the app.clock. |
`;
+const samples: string = `
+# Audio Samples
+
+## Available audio samples
+
+${injectAvailableSamples()}
+
+`;
+
const about: string = `
# About Topos
@@ -318,10 +382,113 @@ The code you enter in any of the scripts is evaluated in strict mode. This tells
- **about errors and printing:** your code will crash! Don't worry, it will hopefully try to crash in the most gracious way possible. To check if your code is erroring, you will have to open the dev console with ${key_shortcut(
"Ctrl + Shift + I"
)}. You cannot directly use console.log('hello, world') in the interface. You will have to open the console as well to see your messages being printed there!
+- **about new syntax:** sometimes, we have taken liberties with the JavaScript syntax in order to make it easier/faster to write on stage. && can also be written :: or -> because it is faster to type or better for the eyes!
+
+## About crashes and bugs
+
+Things will crash, that's also 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 are no safeties in place to save you. This is to ensure that you have all the available possible room to write bespoke code and experiment with your ideas through code.
`;
const functions: string = `
# Functions
+
+## Global Shared Variables
+
+By default, each script is independant from each other. Scripts live in their own bubble and you cannot get or set variables affecting a script from any other script. **However**, everybody knows that global variables are cool and should be used everywhere. This is an incredibely powerful tool to use for radically altering a composition in a few lines of code.
+
+- variable(a: number | string, b?: any): if only one argument is provided, the value of the variable will be returned through its name, denoted by the first argument. If a second argument is used, it will be saved as a global variable under the name of the first argument.
+ - delete_variable(name: string): deletes a global variable from storage.
+ - clear_variables(): clear **ALL** variables. **This is a destructive operation**!
+
+## Counter and iterators
+
+You will often need to use iterators and/or counters to index over data structures (getting a note from a list of notes, etc...). There are functions ready to be used for this. Each script also comes with its own iterator that you can access using the i variable. **Note:** the script iteration count is **not** resetted between sessions. It will continue to increase the more you play, even if you just picked up an old project.
+
+- counter(name: number | string, limit?: number, step?: number): reads the value of the counter name. You can also call this function using the dollar symbol: $.
+ - limit?: counter upper limit before wrapping up.
+ - step?: incrementor. If step is 2, the iterator will go: 0, 2, 4, 6, etc...
+
+- drunk(n?: number): returns the value of the internal drunk walk counter. This iterator will sometimes go up, sometimes go down. It comes with companion functions that you can use to finetune its behavior.
+ - drunk_max(max: number): sets the maximum value.
+ - drunk_min(min: number): sets the minimum value.
+ - drunk_wrap(wrap: boolean): whether to wrap the drunk walk to 0 once the upper limit is reached or not.
+
+
+
+## Scripts
+
+You can control scripts programatically. This is the core concept of Topos after all!
+
+- script(...number: number[]): call one or more scripts (_e.g. script(1,2,3,4)). Once called, scripts will be evaluated once. There are nine local scripts by default. You cannot call the global script nor the initialisation script.
+
+- clear_script(number): deletes the given script.
+- copy_script(from: number, to: number): copies a local script denoted by its number to another local script. **This is a destructive operation!**
+
+## Mouse
+
+You can get the current position of the mouse on the screen by using the following functions:
+
+- mouseX(): the horizontal position of the mouse on the screen (as a floating point number).
+- mouseY(): the vertical position of the mouse on the screen (as a floating point number).
+
+## Low Frequency Oscillators
+
+Low Frequency Oscillators (_LFOs_) are an important piece in any digital audio workstation or synthesizer. Topos implements some basic waveforms you can play with to automatically modulate your paremeters.
+
+- sine(freq: number = 1, offset: number= 0): number: returns a sinusoïdal oscillation between -1 and 1.
+- usine(freq: number = 1, offset: number= 0): number: returns a sinusoïdal oscillation between 0 and 1. The u stands for _unipolar_.
+
+\`\`\`javascript
+ mod(.25) && snd('cp').speed(1 + usine(0.25) * 2).out()
+\`\`\`
+
+- triangle(freq: number = 1, offset: number= 0): number: returns a triangle oscillation between -1 and 1.
+- utriangle(freq: number = 1, offset: number= 0): number: returns a triangle oscillation between 0 and 1. The u stands for _unipolar_.
+
+\`\`\`javascript
+ mod(.25) && snd('cp').speed(1 + utriangle(0.25) * 2).out()
+\`\`\`
+
+- saw(freq: number = 1, offset: number= 0): number: returns a sawtooth-like oscillation between -1 and 1.
+- usaw(freq: number = 1, offset: number= 0): number: returns a sawtooth-like oscillation between 0 and 1. The u stands for _unipolar_.
+
+\`\`\`javascript
+ mod(.25) && snd('cp').speed(1 + usaw(0.25) * 2).out()
+\`\`\`
+
+- square(freq: number = 1, offset: number= 0, duty: number = .5): number: returns a square wave oscillation between -1 and 1. You can also control the duty cycle using the duty parameter.
+- usquare(freq: number = 1, offset: number= 0, duty: number = .5): number: returns a square wave oscillation between 0 and 1. The u stands for _unipolar_. You can also control the duty cycle using the duty parameter.
+
+\`\`\`javascript
+ mod(.25) && snd('cp').speed(1 + usquare(0.25, 0, 0.25) * 2).out()
+\`\`\`
+
+- noise(): returns a random value between -1 and 1.
+
+\`\`\`javascript
+ mod(.25) && snd('cp').speed(1 + noise() * 2).out()
+\`\`\`
+
+## Probabilities
+
+There are some simple functions to play with probabilities.
+
+- prob(p: number): return true _p_% of time, false in other cases.
+- toss(): throwing a coin. Head (true) or tails (false).
+
+## Math functions
+
+- max(...values: number[]): number: returns the maximum value of a list of numbers.
+- min(...values: number[]): number: returns the minimum value of a list of numbers.
+- mean(...values: number[]): number: returns the arithmetic mean of a list of numbers.
+- limit(value: number, min: number, max: number): number: Limits a value between a minimum and a maximum.
+
+## Delay functions
+
+- delay(ms: number, func: Function): void: Delays the execution of a function by a given number of milliseconds.
+- delayr(ms: number, nb: number, func: Function): void: Delays the execution of a function by a given number of milliseconds, repeated a given number of times.
+
+
`;
const reference: string = `
@@ -371,6 +538,7 @@ export const documentation = {
code: code,
time: time,
sound: sound,
+ samples: samples,
midi: midi,
functions: functions,
reference: reference,
diff --git a/src/Evaluator.ts b/src/Evaluator.ts
index ff21cf1..c9130c7 100644
--- a/src/Evaluator.ts
+++ b/src/Evaluator.ts
@@ -6,6 +6,10 @@ const delay = (ms: number) =>
setTimeout(() => reject(new Error("Operation took too long")), ms)
);
+const codeReplace = (code: string): string => {
+ let new_code = code.replace(/->/g, "&&").replace(/::/g, "&&");
+ return new_code;
+};
const tryCatchWrapper = (
application: Editor,
@@ -13,9 +17,12 @@ const tryCatchWrapper = (
): Promise => {
return new Promise((resolve, _) => {
try {
- Function(`"use strict";try{${code}} catch (e) {console.log(e)};`).call(application.api);
+ Function(
+ `"use strict";try{${codeReplace(code)}} catch (e) {console.log(e); _reportError(e);};`
+ ).call(application.api);
resolve(true);
} catch (error) {
+ application.error_line.innerHTML = error as string;
console.log(error);
resolve(false);
}
@@ -31,7 +38,7 @@ const addFunctionToCache = (code: string, fn: Function) => {
cache.delete(cache.keys().next().value);
}
cache.set(code, fn);
-}
+};
export const tryEvaluate = async (
application: Editor,
@@ -41,7 +48,7 @@ export const tryEvaluate = async (
try {
code.evaluations!++;
const candidateCode = code.candidate;
-
+
if (cache.has(candidateCode)) {
// If the code is already in cache, use it
cache.get(candidateCode)!.call(application.api);
@@ -54,13 +61,18 @@ export const tryEvaluate = async (
]);
if (isCodeValid) {
code.committed = code.candidate;
- const newFunction = new Function(`"use strict";try{${wrappedCode}} catch (e) {console.log(e)};`);
+ const newFunction = new Function(
+ `"use strict";try{${codeReplace(
+ wrappedCode
+ )}} catch (e) {console.log(e)};`
+ );
addFunctionToCache(candidateCode, newFunction);
} else {
await evaluate(application, code, timeout);
}
}
} catch (error) {
+ application.error_line.innerHTML = error as string;
console.log(error);
}
};
@@ -77,6 +89,7 @@ export const evaluate = async (
]);
if (code.evaluations) code.evaluations++;
} catch (error) {
+ application.error_line.innerHTML = error as string;
console.log(error);
}
};
diff --git a/src/Note.ts b/src/Note.ts
index 3fbd170..65e8bc0 100644
--- a/src/Note.ts
+++ b/src/Note.ts
@@ -17,6 +17,11 @@ export class Note extends Event {
return this;
}
+ duration = (value: number): this => {
+ this.values['duration'] = value;
+ return this;
+ }
+
channel = (value: number): this => {
this.values['channel'] = value;
return this;
@@ -33,13 +38,19 @@ export class Note extends Event {
}
modify = (func: Function): this => {
+ if(typeof func === 'function') {
const funcResult = func(this);
- if(funcResult instanceof Object) return funcResult;
+ if(funcResult instanceof Object) {
+ console.log("IS OBJECT?");
+ return funcResult;
+
+ }
else {
func(this.values);
return this;
}
}
+ }
// TODO: Add bend
freq = (value: number): this => {
@@ -63,7 +74,11 @@ export class Note extends Event {
const note = this.values.note ? this.values.note : 60;
const channel = this.values.channel ? this.values.channel : 0;
const velocity = this.values.velocity ? this.values.velocity : 100;
- const duration = this.values.duration ? this.values.duration : 0.5;
+
+ const duration = this.values.duration ?
+ this.values.duration * Math.floor(this.app.clock.pulse_duration * this.app.api.ppqn()) :
+ this.app.clock.pulse_duration * this.app.api.ppqn();
+
const bend = this.values.bend ? this.values.bend : undefined;
const port = this.values.port ?
diff --git a/src/Sound.ts b/src/Sound.ts
index 8e7dd85..9fbd64f 100644
--- a/src/Sound.ts
+++ b/src/Sound.ts
@@ -7,171 +7,213 @@ import {
} from "superdough";
export class Sound extends Event {
-
- values: { [key: string]: any }
+ values: { [key: string]: any };
constructor(sound: string|object, public app: Editor) {
super(app);
- if (typeof sound === 'string') this.values = { 's': sound };
+ if (typeof sound === 'string') this.values = { 's': sound, 'dur': 0.5 };
else this.values = sound;
}
+ attack = (value: number): this => {
+ this.values["attack"] = value;
+ return this;
+ };
+ atk = this.attack;
+
+ decay = (value: number): this => {
+ this.values["decay"] = value;
+ return this;
+ };
+ dec = this.decay;
+
+ sustain = (value: number): this => {
+ this.values["sustain"] = value;
+ return this;
+ };
+ sus = this.sustain;
+
+ release = (value: number): this => {
+ this.values["release"] = value;
+ return this;
+ };
+ rel = this.release;
+
+ unit = (value: number): this => {
+ this.values["unit"] = value;
+ return this;
+ };
+
+ freq = (value: number): this => {
+ this.values["freq"] = value;
+ return this;
+ };
+
+ fm = (value: number | string): this => {
+ if (typeof value === "number") {
+ this.values["fmi"] = value;
+ } else {
+ let values = value.split(":");
+ this.values["fmi"] = parseFloat(values[0]);
+ if (values.length > 1) this.values["fmh"] = parseFloat(values[1]);
+ }
+ return this;
+ };
+
sound = (value: string): this => {
this.values['s'] = value
return this;
- }
+ };
- snd = this.sound;
-
- unit = (value: number): this => {
- this.values['unit'] = value
+ fmi = (value: number): this => {
+ this.values["fmi"] = value;
return this;
- }
+ };
- freq = (value: number): this => {
- this.values['freq'] = value
+ fmh = (value: number): this => {
+ this.values["fmh"] = value;
return this;
- }
+ };
nudge = (value: number): this => {
- this.values['nudge'] = value
+ this.values["nudge"] = value;
return this;
- }
+ };
cut = (value: number): this => {
- this.values['cut'] = value
+ this.values["cut"] = value;
return this;
- }
+ };
loop = (value: number): this => {
- this.values['loop'] = value
+ this.values["loop"] = value;
return this;
- }
+ };
clip = (value: number): this => {
- this.values['clip'] = value
+ this.values["clip"] = value;
return this;
- }
+ };
n = (value: number): this => {
- this.values['n'] = value
+ this.values["n"] = value;
return this;
- }
+ };
note = (value: number): this => {
- this.values['note'] = value
+ this.values["note"] = value;
return this;
- }
+ };
speed = (value: number): this => {
- this.values['speed'] = value
+ this.values["speed"] = value;
return this;
- }
+ };
begin = (value: number): this => {
- this.values['begin'] = value
+ this.values["begin"] = value;
return this;
- }
+ };
end = (value: number): this => {
- this.values['end'] = value
+ this.values["end"] = value;
return this;
- }
+ };
gain = (value: number): this => {
- this.values['gain'] = value
+ this.values["gain"] = value;
return this;
- }
+ };
cutoff = (value: number): this => {
- this.values['cutoff'] = value
+ this.values["cutoff"] = value;
return this;
- }
+ };
resonance = (value: number): this => {
- this.values['resonance'] = value
+ this.values["resonance"] = value;
return this;
- }
+ };
hcutoff = (value: number): this => {
- this.values['hcutoff'] = value
+ this.values["hcutoff"] = value;
return this;
- }
+ };
hresonance = (value: number): this => {
- this.values['hresonance'] = value
+ this.values["hresonance"] = value;
return this;
- }
+ };
bandf = (value: number): this => {
- this.values['bandf'] = value
+ this.values["bandf"] = value;
return this;
- }
+ };
bandq = (value: number): this => {
- this.values['bandq'] = value
+ this.values["bandq"] = value;
return this;
- }
+ };
coarse = (value: number): this => {
- this.values['coarse'] = value
+ this.values["coarse"] = value;
return this;
- }
+ };
crush = (value: number): this => {
- this.values['crush'] = value
+ this.values["crush"] = value;
return this;
- }
+ };
shape = (value: number): this => {
- this.values['shape'] = value
+ this.values["shape"] = value;
return this;
- }
+ };
pan = (value: number): this => {
- this.values['pan'] = value
+ this.values["pan"] = value;
return this;
- }
+ };
vowel = (value: number): this => {
- this.values['vowel'] = value
+ this.values["vowel"] = value;
return this;
- }
+ };
delay = (value: number): this => {
- this.values['delay'] = value
+ this.values["delay"] = value;
return this;
- }
+ };
delayfeedback = (value: number): this => {
- this.values['delayfeedback'] = value
+ this.values["delayfeedback"] = value;
return this;
- }
+ };
delaytime = (value: number): this => {
- this.values['delaytime'] = value
+ this.values["delaytime"] = value;
return this;
- }
+ };
orbit = (value: number): this => {
- this.values['orbit'] = value
+ this.values["orbit"] = value;
return this;
- }
+ };
room = (value: number): this => {
- this.values['room'] = value
+ this.values["room"] = value;
return this;
- }
+ };
size = (value: number): this => {
- this.values['size'] = value
+ this.values["size"] = value;
return this;
- }
+ };
velocity = (value: number): this => {
- this.values['velocity'] = value
+ this.values["velocity"] = value;
return this;
- }
+ };
modify = (func: Function): this => {
const funcResult = func(this);
@@ -180,9 +222,20 @@ export class Sound extends Event {
func(this.values);
return this;
}
- }
+ };
+
+ dur = (value: number): this => {
+ this.values["dur"] = value;
+ return this;
+ };
+
+ out = (): object => {
+ return superdough(
+ this.values,
+ this.app.clock.pulse_duration,
+ this.values.dur
+ );
+ };
+
- out = (): void => {
- superdough(this.values, this.app.clock.pulse_duration);
- }
}
\ No newline at end of file
diff --git a/src/main.ts b/src/main.ts
index 515c4b8..f9cd479 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -28,20 +28,21 @@ import showdown from "showdown";
showdown.setFlavor("github");
import showdownHighlight from "showdown-highlight";
const classMap = {
- h1: "text-4xl text-white ml-4 mx-4 my-4 mb-8",
- h2: "text-3xl text-white mx-4 my-4 mt-12 mb-6",
+ h1: "text-white lg:text-4xl text-xl lg:ml-4 lg:mx-4 mx-2 lg:my-4 my-2 lg:mb-8 mb-4 bg-neutral-900 rounded-lg py-2 px-2",
+ h2: "text-white lg:text-3xl text-xl lg:ml-4 lg:mx-4 mx-2 lg:my-4 my-2 lg:mb-8 mb-4 bg-neutral-900 rounded-lg py-2 px-2",
ul: "text-underline",
- li: "ml-12 list-disc text-2xl text-white mx-4 my-4 leading-normal",
- p: "text-2xl text-white mx-4 my-4 leading-normal",
- a: "text-2xl text-orange-300",
- code: "my-4 block whitespace-pre overflow-x-scroll",
- icode: "my-4 text-white font-mono bg-neutral-600",
+ li: "ml-12 list-disc lg:text-2xl text-base text-white lg:mx-4 mx-2 my-4 lg:pl-4 my-2 leading-normal",
+ p: "lg:text-2xl text-base text-white lg:mx-4 mx-2 my-4 leading-normal",
+ a: "lg:text-2xl text-base text-orange-300",
+ code: "lg:my-4 sm:my-1 text-base lg:text-xl block whitespace-pre overflow-x-scroll",
+ icode:
+ "lg:my-4 my-1 lg:text-xl sm:text-xs text-white font-mono bg-neutral-600",
blockquote: "text-neutral-200 border-l-4 border-neutral-500 pl-4 my-4 mx-4",
table:
- "justify-center my-8 mx-8 text-2xl w-full text-left text-white border-collapse",
+ "justify-center lg:my-8 my-2 lg:mx-8 mx-2 lg:text-2xl text-base w-full text-left text-white border-collapse",
thead:
"text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400",
- th: "px-6 py-6",
+ th: "lg:px-6 lg:py-6 px-2 py-2",
td: "py-2",
tr: "py-0",
};
@@ -101,6 +102,9 @@ export class Editor {
documentation_button: HTMLButtonElement = document.getElementById(
"doc-button-1"
) as HTMLButtonElement;
+ eval_button: HTMLButtonElement = document.getElementById(
+ "eval-button-1"
+ ) as HTMLButtonElement;
// Script selection elements
local_button: HTMLButtonElement = document.getElementById(
@@ -159,6 +163,10 @@ export class Editor {
"vim-mode"
) as HTMLButtonElement;
+ // Error line
+ error_line: HTMLElement = document.getElementById("error_line") as HTMLElement
+ show_error: boolean = false
+
constructor() {
// ================================================================================
// Loading the universe from local storage
@@ -400,6 +408,11 @@ export class Editor {
this.showDocumentation();
});
+ this.eval_button.addEventListener("click", () => {
+ this.currentFile().candidate = this.view.state.doc.toString();
+ this.flashBackground("#2d313d", 200);
+ });
+
this.pause_buttons.forEach((button) => {
button.addEventListener("click", () => {
this.setButtonHighlighting("pause", true);
@@ -500,55 +513,31 @@ export class Editor {
});
tryEvaluate(this, this.universes[this.selected_universe.toString()].init);
- // Setting up the documentation page
- document
- .getElementById("docs_introduction")!
- .addEventListener("click", () => {
- this.currentDocumentationPane = "introduction";
- this.updateDocumentationContent();
- });
- document.getElementById("docs_interface")!.addEventListener("click", () => {
- this.currentDocumentationPane = "interface";
- this.updateDocumentationContent();
- });
- document.getElementById("docs_code")!.addEventListener("click", () => {
- this.currentDocumentationPane = "code";
- this.updateDocumentationContent();
- });
- document.getElementById("docs_time")!.addEventListener("click", () => {
- this.currentDocumentationPane = "time";
- this.updateDocumentationContent();
- });
- document.getElementById("docs_sound")!.addEventListener("click", () => {
- this.currentDocumentationPane = "sound";
- this.updateDocumentationContent();
- });
- document.getElementById("docs_midi")!.addEventListener("click", () => {
- this.currentDocumentationPane = "midi";
- this.updateDocumentationContent();
- });
+ [
+ "introduction",
+ "interface",
+ "code",
+ "time",
+ "sound",
+ "samples",
+ "midi",
+ "functions",
+ "reference",
+ "shortcuts",
+ "about",
+ ].forEach((e) => {
+ let name = `docs_` + e;
+ document.getElementById(name)!
+ .addEventListener("click", () => {
+ this.currentDocumentationPane = e;
+ this.updateDocumentationContent();
+ });
+ });
- document.getElementById("docs_functions")!.addEventListener("click", () => {
- this.currentDocumentationPane = "functions";
- this.updateDocumentationContent();
- });
- document.getElementById("docs_reference")!.addEventListener("click", () => {
- this.currentDocumentationPane = "reference";
- this.updateDocumentationContent();
- });
- document.getElementById("docs_shortcuts")!.addEventListener("click", () => {
- this.currentDocumentationPane = "shortcuts";
- this.updateDocumentationContent();
- });
- document.getElementById("docs_about")!.addEventListener("click", () => {
- this.currentDocumentationPane = "about";
- this.updateDocumentationContent();
- });
-
- // Passing the API to the User
- Object.entries(this.api).forEach(([name, value]) => {
- (globalThis as Record)[name] = value;
- });
+ // Passing the API to the User
+ Object.entries(this.api).forEach(([name, value]) => {
+ (globalThis as Record)[name] = value;
+ });
}
get note_buffer() {
@@ -715,6 +704,7 @@ export class Editor {
.querySelectorAll(possible_selectors[selector])
.forEach((button) => {
if (highlight) button.children[0].classList.add("fill-orange-300");
+ if (highlight) button.children[0].classList.add("animate-pulse");
});
// All other buttons must lose the highlighting
document
@@ -725,12 +715,14 @@ export class Editor {
button.children[0].classList.remove("fill-orange-300");
button.children[0].classList.remove("text-orange-300");
button.children[0].classList.remove("bg-orange-300");
+ button.children[0].classList.remove("animate-pulse");
});
}
unfocusPlayButtons() {
document.querySelectorAll('[id^="play-button-"]').forEach((button) => {
button.children[0].classList.remove("fill-orange-300");
+ button.children[0].classList.remove("animate-pulse");
});
}
diff --git a/yarn.lock b/yarn.lock
index 2c5060a..f5c0699 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1267,10 +1267,10 @@ sucrase@^3.32.0:
pirates "^4.0.1"
ts-interface-checker "^0.1.9"
-superdough@^0.9.3:
- version "0.9.4"
- resolved "https://registry.yarnpkg.com/superdough/-/superdough-0.9.4.tgz#cfae0bc6dfe5976ea0abb423a9cf2b3670944b86"
- integrity sha512-1wOJbnm5e/9tn9TzYuhzlxhrXPJ3m6sY21tf+nNnU9JXA0ZUAGbGyHDWTT8R/cEtKziFAmgVxdwGBFOAxgTWdw==
+superdough@^0.9.5:
+ version "0.9.5"
+ resolved "https://registry.yarnpkg.com/superdough/-/superdough-0.9.5.tgz#316b9fa9699cf1b86285e65c4084c4e2ea4489dd"
+ integrity sha512-PcEzWaD9oQ6apDCLmQq9OtyiAVB+Ell4U3RsYTR48L6jTssZILfYEG8pzHVf06QHeCl0rhl3/QlgO5Vf9HKMkg==
dependencies:
nanostores "^0.8.1"