Files
beat-hound/src/domain/sequencer.ts
T

78 lines
2.4 KiB
TypeScript

import { INSTRUMENT_BY_ID } from './instruments';
import type { InstrumentCategoryId, InstrumentId } from './instruments';
export const STEPS_PER_BEAT = 4;
export const PLAYBACK_SUBSTEPS_PER_STEP = 4;
export const DEFAULT_BEATS_PER_BAR = 4;
export const BEATS_PER_BAR_OPTIONS = [2, 3, 4, 5, 6, 7, 8] as const;
export type BeatsPerBar = (typeof BEATS_PER_BAR_OPTIONS)[number];
export const TOTAL_STEPS = DEFAULT_BEATS_PER_BAR * STEPS_PER_BEAT;
export const TEMPO_BPM = 112;
export const MIN_TEMPO_BPM = 30;
export const MAX_TEMPO_BPM = 260;
export function getTotalSteps(beatsPerBar: BeatsPerBar): number {
return beatsPerBar * STEPS_PER_BEAT;
}
export function clampTempoBpm(tempoBpm: number): number {
return Math.min(MAX_TEMPO_BPM, Math.max(MIN_TEMPO_BPM, Math.round(tempoBpm)));
}
export function getPlaybackTickDurationMs(tempoBpm: number): number {
return 60_000 / tempoBpm / STEPS_PER_BEAT / PLAYBACK_SUBSTEPS_PER_STEP;
}
export interface BeatPoint {
id: string;
soundId: InstrumentId;
/** Short unique label within its instrument category, such as a, b, or c. */
letter: string;
/** Position in sixteenth-note steps; fractional values represent microtiming. */
step: number;
/** Pitch offset from the instrument's base note in semitones. */
pitchSemitones?: number;
}
export function getAlphabeticLabel(index: number): string {
let value = Math.floor(index) + 1;
if (!Number.isSafeInteger(value) || value < 1) return '';
let label = '';
while (value > 0) {
value -= 1;
label = String.fromCharCode(65 + (value % 26)) + label;
value = Math.floor(value / 26);
}
return label;
}
export function getNextBeatLetter(
beats: readonly BeatPoint[],
categoryId: InstrumentCategoryId,
): string {
const usedLetters = new Set(
beats
.filter((beat) => INSTRUMENT_BY_ID[beat.soundId].categoryId === categoryId)
.map((beat) => beat.letter),
);
let index = 0;
let letter = getAlphabeticLabel(index).toLowerCase();
while (usedLetters.has(letter)) {
index += 1;
letter = getAlphabeticLabel(index).toLowerCase();
}
return letter;
}
export function getNextAvailableStep(
beats: readonly BeatPoint[],
totalSteps = TOTAL_STEPS,
): number {
const occupiedSteps = new Set(beats.map((beat) => beat.step));
const nextStep = Array.from({ length: totalSteps }, (_, step) => step)
.find((step) => !occupiedSteps.has(step));
return nextStep ?? 0;
}