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

75 lines
2.2 KiB
TypeScript

import type { BeatPoint } from './sequencer';
import {
PLAYBACK_SUBSTEPS_PER_STEP,
TOTAL_STEPS,
} from './sequencer';
export const SVG_SIZE = 600;
export const SVG_CENTER = SVG_SIZE / 2;
export const ORBIT_RADIUS = 216;
const MARKER_STEP_OFFSET = 0.3;
export interface CirclePoint {
x: number;
y: number;
}
export function getStepFromPosition(
x: number,
y: number,
center = SVG_CENTER,
totalSteps = TOTAL_STEPS,
): number {
const angle = Math.atan2(y - center, x - center) + Math.PI / 2;
const normalizedAngle = (angle + Math.PI * 2) % (Math.PI * 2);
return (normalizedAngle / (Math.PI * 2)) * totalSteps;
}
export function getPointForStep(
step: number,
radius: number,
center = SVG_CENTER,
totalSteps = TOTAL_STEPS,
): CirclePoint {
const angle = (step / totalSteps) * Math.PI * 2 - Math.PI / 2;
return {
x: center + Math.cos(angle) * radius,
y: center + Math.sin(angle) * radius,
};
}
export function getLoopPositionPercent(step: number, totalSteps: number): number {
return Math.round((step / totalSteps) * 100);
}
export function wrapStepPosition(step: number, totalSteps: number): number {
return ((step % totalSteps) + totalSteps) % totalSteps;
}
export function getSoundOrbitRadius(soundIndex: number, soundCount: number): number {
return ORBIT_RADIUS * (soundCount + 1 - soundIndex) / (soundCount + 1);
}
export function getPlaybackTick(step: number, totalSteps: number): number {
const totalPlaybackTicks = totalSteps * PLAYBACK_SUBSTEPS_PER_STEP;
return Math.round(step * PLAYBACK_SUBSTEPS_PER_STEP) % totalPlaybackTicks;
}
export function getStackedPosition(
beat: BeatPoint,
beats: readonly BeatPoint[],
totalSteps: number,
orbitRadius: number,
): CirclePoint {
const siblings = beats
.filter((candidate) => (
candidate.soundId === beat.soundId
&& getPlaybackTick(candidate.step, totalSteps) === getPlaybackTick(beat.step, totalSteps)
))
.sort((first, second) => first.id.localeCompare(second.id));
const index = siblings.findIndex((candidate) => candidate.id === beat.id);
const offset = (index - (siblings.length - 1) / 2) * MARKER_STEP_OFFSET;
return getPointForStep(beat.step + offset, orbitRadius, SVG_CENTER, totalSteps);
}