|
| 1 | +import { IColorGetter, IColorMapper, IArrColor } from 'src/typings' |
| 2 | +import { callIndexedGetter } from './mappers' |
| 3 | +import { pixelsCount, hueToColor } from '../shared' |
| 4 | +import { settings } from 'src/settings' |
| 5 | +import { audioState } from '../wsAudio' |
| 6 | + |
| 7 | +interface Ripple { |
| 8 | + pos: number |
| 9 | + radius: number |
| 10 | + brightness: number |
| 11 | + hue: number |
| 12 | +} |
| 13 | + |
| 14 | +let ripples: Ripple[] = [] |
| 15 | +let lastTime = Date.now() |
| 16 | +let averages: number[] = [] |
| 17 | +const attenuation = 0.9 |
| 18 | +const speed = 60 |
| 19 | + |
| 20 | +function spawnRipple(bin: number, mag: number) { |
| 21 | + const hue = (bin / audioState.bins.length) * 270 |
| 22 | + ripples.push({ |
| 23 | + pos: (bin / audioState.bins.length) * pixelsCount, |
| 24 | + radius: 1, |
| 25 | + brightness: Math.min(1, mag), |
| 26 | + hue, |
| 27 | + }) |
| 28 | +} |
| 29 | + |
| 30 | +function update(time: number) { |
| 31 | + const dt = (time - lastTime) * settings.effectSpeed |
| 32 | + lastTime = time |
| 33 | + const bins = audioState.bins |
| 34 | + if (bins && bins.length) { |
| 35 | + if (averages.length !== bins.length) averages = bins.slice() |
| 36 | + for (let i = 0; i < bins.length; i++) { |
| 37 | + const m = bins[i] |
| 38 | + averages[i] = averages[i] * 0.9 + m * 0.1 |
| 39 | + if (m > averages[i] * 1.5) spawnRipple(i, m) |
| 40 | + } |
| 41 | + } |
| 42 | + ripples.forEach(r => { |
| 43 | + r.radius += (speed * dt) / 1000 |
| 44 | + r.brightness *= Math.pow(attenuation, dt / 16) |
| 45 | + }) |
| 46 | + ripples = ripples.filter(r => r.brightness > 0.05) |
| 47 | +} |
| 48 | + |
| 49 | +export const getFftRippleColor: IColorGetter = (index, time) => { |
| 50 | + if (index === 0) update(time) |
| 51 | + let r = 0 |
| 52 | + let g = 0 |
| 53 | + let b = 0 |
| 54 | + for (const ripple of ripples) { |
| 55 | + const dist = Math.abs(index - ripple.pos) |
| 56 | + if (dist <= ripple.radius) { |
| 57 | + const intensity = ripple.brightness * (1 - dist / ripple.radius) |
| 58 | + const { r: rr, g: gg, b: bb } = hueToColor(ripple.hue).rgb() |
| 59 | + r += rr * intensity |
| 60 | + g += gg * intensity |
| 61 | + b += bb * intensity |
| 62 | + } |
| 63 | + } |
| 64 | + return [Math.min(255, Math.round(r)), Math.min(255, Math.round(g)), Math.min(255, Math.round(b))] |
| 65 | +} |
| 66 | + |
| 67 | +export function resetFftRipples() { |
| 68 | + ripples = [] |
| 69 | + lastTime = Date.now() |
| 70 | + averages = [] |
| 71 | +} |
| 72 | + |
| 73 | +export const fftRippleMapper: IColorMapper = () => callIndexedGetter(getFftRippleColor) |
0 commit comments