Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
amiika committed Dec 18, 2023
2 parents 3c602dc + 5456410 commit 7086682
Show file tree
Hide file tree
Showing 12 changed files with 472 additions and 135 deletions.
8 changes: 8 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,14 @@ <h1 class="lg:mt-12 mt-6 font-semibold rounded-lg justify-center lg:text-center
</svg>
<span class="text-selection_foreground">Destroy universes</span>
</button>
<!-- Upload audio samples -->
<p class="font-bold lg:text-xl text-sm ml-4 pb-2 pt-2 underline underline-offset-4 text-selection_background">Audio samples</p>

<label class="bg-brightwhite font-bold lg:py-4 lg:px-2 px-1 py-2 rounded-lg inline-flex items-center mx-4 text-selection_background">
<svg class="rotate-180 fill-current w-4 h-6 mr-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M13 8V2H7v6H2l8 8 8-8h-5zM0 18h20v2H0v-2z"/></svg>
<input id="upload-samples" type="file" class="hidden" accept="file" webkitdirectory directory multiple>
<span id="sample-indicator" class="text-selection_foreground">Import samples</span>
</label>
</div>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/API.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2920,7 +2920,7 @@ export class UserAPI {
address: address,
port: port,
args: args,
timetag: Math.round(Date.now() + this.app.clock.deadline),
timetag: Math.round(Date.now() + (this.app.clock.nudge - this.app.clock.deviation)),
} as OSCMessage);
};

Expand Down
201 changes: 91 additions & 110 deletions src/Clock.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import { Editor } from "./main";
import { tryEvaluate } from "./Evaluator";
// @ts-ignore
import { getAudioContext } from "superdough";
// @ts-ignore
import "zyklus";
const zeroPad = (num: number, places: number) =>
String(num).padStart(places, "0");
import { TransportNode } from "./TransportNode";
import TransportProcessor from "./TransportProcessor?worker&url";
import { Editor } from "./main";

export interface TimePosition {
/**
Expand All @@ -22,29 +18,35 @@ export interface TimePosition {

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 - main application instance
* @param clock - zyklus clock
* @param ctx - current AudioContext used by app
* @param bpm - current beats per minute value
* @param time_signature - time signature
* @param time_position - current time position
* @param ppqn - pulses per quarter note
* @param tick - current tick since origin
* @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
*/

private _bpm: number;
private _ppqn: number;
clock: any;
ctx: AudioContext;
logicalTime: number;
transportNode: TransportNode | null;
private _bpm: number;
time_signature: number[];
time_position: TimePosition;
private _ppqn: number;
tick: number;
running: boolean;
timeviewer: HTMLElement;
deadline: number;
lastPauseTime: number;
lastPlayPressTime: number;
totalPauseTime: number;

constructor(
public app: Editor,
Expand All @@ -56,59 +58,31 @@ export class Clock {
this.tick = 0;
this._bpm = 120;
this._ppqn = 48;
this.transportNode = null;
this.ctx = ctx;
this.running = true;
this.deadline = 0;
this.timeviewer = document.getElementById("timeviewer")!;
this.clock = getAudioContext().createClock(
this.clockCallback,
this.pulse_duration,
);
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);
});
}

// @ts-ignore
clockCallback = (time: number, duration: number, tick: number) => {
/**
* Callback function for the zyklus clock. Updates the clock info and sends a
* MIDI clock message if the setting is enabled. Also evaluates the global buffer.
*
* @param time - precise AudioContext time when the tick should happen
* @param duration - seconds between each tick
* @param tick - count of the current tick
*/
let deadline = time - getAudioContext().currentTime;
this.deadline = deadline;
this.tick = tick;
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;
if (futureTimeStamp.pulse % this.app.clock.ppqn == 0) {
this.timeviewer.innerHTML = `${zeroPad(futureTimeStamp.bar, 2)}:${
futureTimeStamp.beat + 1
} / ${this.app.clock.bpm}`;
}
if (this.app.exampleIsPlaying) {
tryEvaluate(this.app, this.app.example_buffer);
} else {
tryEvaluate(this.app, this.app.global_buffer);
}
}

// Implement TransportNode clock callback and update clock info with it
};

convertTicksToTimeposition(ticks: number): TimePosition {
/**
* Converts ticks to a time position.
*
* @param ticks - ticks to convert
* @returns 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);
Expand All @@ -119,9 +93,10 @@ export class Clock {

get ticks_before_new_bar(): number {
/**
* Calculates the number of ticks before the next bar.
* This function returns the number of ticks separating the current moment
* from the beginning of the next bar.
*
* @returns number - ticks before 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;
Expand All @@ -130,18 +105,17 @@ export class Clock {

get next_beat_in_ticks(): number {
/**
* Calculates the number of ticks before the next beat.
* This function returns the number of ticks separating the current moment
* from the beginning of the next beat.
*
* @returns number - ticks before 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.
*
* @returns number - beats per bar
*/
return this.time_signature[0];
}
Expand All @@ -150,7 +124,7 @@ export class Clock {
/**
* Returns the number of beats since the origin.
*
* @returns number - beats since the origin
* @returns number of beats since origin
*/
return Math.floor(this.tick / this.ppqn);
}
Expand All @@ -159,120 +133,127 @@ export class Clock {
/**
* Returns the number of pulses since the origin.
*
* @returns number - 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.
* @returns number - 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 given bpm.
*
* @param bpm - bpm to calculate the pulse duration for
* @returns number - duration of a pulse in seconds
* Returns the duration of a pulse in seconds at a specific bpm.
*/
return 60 / bpm / this.ppqn;
}

get bpm(): number {
/**
* Returns the current bpm.
* @returns number - current bpm
*/
return this._bpm;
}

get tickDuration(): number {
/**
* Returns the duration of a tick in seconds.
* @returns number - duration of a tick in seconds
*/
return 1 / this.ppqn;
set nudge(nudge: number) {
this.transportNode?.setNudge(nudge);
}

set bpm(bpm: number) {
/**
* Sets the bpm.
* @param bpm - bpm to set
*/
if (bpm > 0 && this._bpm !== bpm) {
this.transportNode?.setBPM(bpm);
this._bpm = bpm;
this.clock.setDuration(() => (this.tickDuration * 60) / this.bpm);
this.logicalTime = this.realTime;
}
}

get ppqn(): number {
/**
* Returns the current ppqn.
* @returns number - current ppqn
*/
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) {
/**
* Sets the ppqn.
* @param ppqn - ppqn to set
* @returns number - current ppqn
*/
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 {
/**
* Start the clock
* 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.clock.start();
this.lastPlayPressTime = this.app.audioContext.currentTime;
this.totalPauseTime += this.lastPlayPressTime - this.lastPauseTime;
this.transportNode?.start();
}

public pause(): void {
/**
* Pause the clock.
* 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.clock.pause();
this.lastPauseTime = this.app.audioContext.currentTime;
this.logicalTime = this.realTime;
}

public stop(): void {
/**
* Stops the clock.
* 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.clock.stop();
this.transportNode?.stop();
}
}
}
4 changes: 3 additions & 1 deletion src/DomElements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ export const singleElements = {
load_universe_button: "load-universe-button",
download_universe_button: "download-universes",
upload_universe_button: "upload-universes",
upload_samples_button: "upload-samples",
sample_indicator: "sample-indicator",
destroy_universes_button: "destroy-universes",
documentation_button: "doc-button-1",
eval_button: "eval-button-1",
Expand Down Expand Up @@ -81,7 +83,7 @@ export const createDocumentationStyle = (app: Editor) => {
p: "lg:text-2xl text-base text-white lg:mx-6 mx-2 my-4 leading-normal",
warning:
"animate-pulse lg:text-2xl font-bold text-brightred lg:mx-6 mx-2 my-4 leading-normal",
a: "lg:text-2xl text-base text-white",
a: "lg:text-2xl text-base text-brightred",
code: `lg:my-4 sm:my-1 text-base lg:text-xl block whitespace-pre overflow-x-hidden`,
icode:
"lg:my-1 my-1 lg:text-xl sm:text-xs text-brightwhite font-mono bg-brightblack",
Expand Down
Loading

0 comments on commit 7086682

Please sign in to comment.