feature: lyric smooth scrolling using new arch

todo: var `nextUpdate`'s assignment when backtracking
This commit is contained in:
alikia2x (寒寒) 2024-10-24 00:44:17 +08:00
parent 0c315972c1
commit 10c5ea3916
Signed by: alikia2x
GPG Key ID: 56209E0CCD8420C6
4 changed files with 197 additions and 181 deletions

View File

@ -7,7 +7,6 @@
export let line: ScriptItem; export let line: ScriptItem;
export let index: number; export let index: number;
export let debugMode: Boolean; export let debugMode: Boolean;
export let initPos: LyricPos;
let ref: HTMLDivElement; let ref: HTMLDivElement;
let time = 0; let time = 0;
@ -21,25 +20,18 @@
let springX: Spring | undefined = undefined; let springX: Spring | undefined = undefined;
let isCurrentLyric = false; let isCurrentLyric = false;
$: {
if (initPos) {
positionX = initPos.x;
positionY = initPos.y;
}
}
function updateY(timestamp: number) { function updateY(timestamp: number) {
if (lastUpdateY === undefined) { if (lastUpdateY === undefined) {
lastUpdateY = timestamp; lastUpdateY = new Date().getTime();
} }
if (springY === undefined) return; if (springY === undefined) return;
time = (timestamp - lastUpdateY) / 1000; time = (new Date().getTime() - lastUpdateY) / 1000;
springY.update(time); springY.update(time);
positionY = springY.getCurrentPosition(); positionY = springY.getCurrentPosition();
if (!springY.arrived()) { if (!springY.arrived()) {
requestAnimationFrame(updateY); requestAnimationFrame(updateY);
} }
lastUpdateY = timestamp; lastUpdateY = new Date().getTime();
} }
function updateX(timestamp: number) { function updateX(timestamp: number) {
@ -47,7 +39,7 @@
lastUpdateX = timestamp; lastUpdateX = timestamp;
} }
if (springX === undefined) return; if (springX === undefined) return;
time = (timestamp - lastUpdateX) / 1000; time = (new Date().getTime() - lastUpdateX) / 1000;
springX.update(time); springX.update(time);
positionX = springX.getCurrentPosition(); positionX = springX.getCurrentPosition();
if (!springX.arrived()) { if (!springX.arrived()) {
@ -77,16 +69,18 @@
}; };
export const update = (pos: LyricPos, delay: number = 0) => { export const update = (pos: LyricPos, delay: number = 0) => {
if (lastPosX === undefined) { if (lastPosX === undefined || lastPosY === undefined) {
lastPosX = pos.x; lastPosX = pos.x;
}
if (lastPosY === undefined) {
lastPosY = pos.y; lastPosY = pos.y;
} }
springY = createSpring(lastPosY, pos.y, 0.12, 0.7, delay); springY = createSpring(lastPosY, pos.y, .126, .85, delay);
springX = createSpring(lastPosX, pos.x, 0.12, 0.7, delay); springX = createSpring(lastPosX, pos.x, .126, .85, delay);
lastUpdateY = new Date().getTime();
lastUpdateX = new Date().getTime();
requestAnimationFrame(updateY); requestAnimationFrame(updateY);
requestAnimationFrame(updateX); requestAnimationFrame(updateX);
lastPosX = pos.x;
lastPosY = pos.y;
}; };
export const getInfo = () => { export const getInfo = () => {
@ -109,7 +103,7 @@
<div style="transform: translateY({positionY}px) translateX({positionX}px);" class="absolute z-50" bind:this={ref}> <div style="transform: translateY({positionY}px) translateX({positionX}px);" class="absolute z-50" bind:this={ref}>
{#if debugMode} {#if debugMode}
<span class="text-lg absolute -translate-y-7">Line idx: {index}</span> <span class="text-lg absolute -translate-y-7">Line idx: {index}, duration: {(line.end - line.start).toFixed(3)}</span>
{/if} {/if}
<span class={`text-white text-5xl font-semibold text-shadow-lg ${!isCurrentLyric && 'opacity-50'} `}> <span class={`text-white text-5xl font-semibold text-shadow-lg ${!isCurrentLyric && 'opacity-50'} `}>
{line.text} {line.text}

View File

@ -3,7 +3,8 @@
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import type { ScriptItem } from '$lib/lyrics/type'; import type { ScriptItem } from '$lib/lyrics/type';
import LyricLine from './lyricLine.svelte'; import LyricLine from './lyricLine.svelte';
import type { LyricPos } from './type'; import type { LyricLayout, LyricPos } from './type';
import createLyricsSearcher from '$lib/lyrics/lyricSearcher';
// Props // Props
export let originalLyrics: LrcJsonData; export let originalLyrics: LrcJsonData;
@ -14,23 +15,28 @@
let lyricLines: ScriptItem[] = []; let lyricLines: ScriptItem[] = [];
let lyricExists = false; let lyricExists = false;
let lyricsContainer: HTMLDivElement | null; let lyricsContainer: HTMLDivElement | null;
let lyricLayouts: LyricLayout[] = [];
let debugMode = false; let debugMode = false;
let showTranslation = false; let showTranslation = false;
// Exlpaination:
// The hot module reloading makes the each lyric component position to be re-initialized,
// which causes the lyrics are all at {x: 0, y: 0},
// instead of the value calculated in the initLyricComponents.
// So, we need to store the initial position of each lyric component and restore it.
let lyricComponentInitPos = Array<LyricPos>(lyricLines.length).fill({ x: 0, y: 0 });
// References to lyric elements // References to lyric elements
let lyricElements: HTMLDivElement[] = []; let lyricElements: HTMLDivElement[] = [];
let lyricComponents: LyricLine[] = []; let lyricComponents: LyricLine[] = [];
let lyricTopList: number[] = [];
let nextUpdate = 0;
const marginY = 48;
$: getLyricIndex = createLyricsSearcher(originalLyrics);
function initLyricComponents() { function initLyricComponents() {
initLyricTopList();
for (let i = 0; i < lyricComponents.length; i++) {
lyricComponents[i].init({ x: 0, y: lyricTopList[i] });
}
}
function initLyricTopList() {
let cumulativeHeight = 0; let cumulativeHeight = 0;
const marginY = 48;
for (let i = 0; i < lyricLines.length; i++) { for (let i = 0; i < lyricLines.length; i++) {
const c = lyricComponents[i]; const c = lyricComponents[i];
lyricElements.push(c.getRef()); lyricElements.push(c.getRef());
@ -38,10 +44,37 @@
const elementHeight = e.getBoundingClientRect().height; const elementHeight = e.getBoundingClientRect().height;
const elementTargetTop = cumulativeHeight; const elementTargetTop = cumulativeHeight;
cumulativeHeight += elementHeight + marginY; cumulativeHeight += elementHeight + marginY;
lyricComponentInitPos[i] = { x: 0, y: elementTargetTop }; lyricTopList.push(elementTargetTop);
} }
} }
function computeLayout(progress: number) {
if (!originalLyrics.scripts) return;
const currentLyricIndex = getLyricIndex(progress);
const currentLyricDuration =
originalLyrics.scripts[currentLyricIndex].end - originalLyrics.scripts[currentLyricIndex].start;
const relativeOrigin = lyricTopList[currentLyricIndex];
for (let i = 0; i < lyricElements.length; i++) {
const currentLyricComponent = lyricComponents[i];
lyricLayouts[i] = {
blur: 0,
scale: 1,
pos: {
y: lyricTopList[i] - relativeOrigin,
x: 0
}
};
let delay = 0;
if (i <= currentLyricIndex) {
delay = 0;
} else {
delay = 0.013 + Math.min(Math.min(currentLyricDuration, 0.3), 0.075 * (i - currentLyricIndex));
}
currentLyricComponent.update({ x: 0, y: lyricTopList[i] - relativeOrigin }, delay);
}
nextUpdate = originalLyrics.scripts[currentLyricIndex + 1].start;
}
$: { $: {
if (originalLyrics && originalLyrics.scripts) { if (originalLyrics && originalLyrics.scripts) {
lyricExists = true; lyricExists = true;
@ -55,6 +88,12 @@
} }
} }
$: {
if (lyricsContainer && lyricComponents.length > 0) {
if (progress >= nextUpdate) computeLayout(progress);
}
}
onMount(() => { onMount(() => {
// Initialize // Initialize
if (localStorage.getItem('debugMode') == null) { if (localStorage.getItem('debugMode') == null) {
@ -72,13 +111,7 @@
bind:this={lyricsContainer} bind:this={lyricsContainer}
> >
{#each lyricLines as lyric, i} {#each lyricLines as lyric, i}
<LyricLine <LyricLine line={lyric} index={i} bind:this={lyricComponents[i]} {debugMode} />
line={lyric}
index={i}
bind:this={lyricComponents[i]}
{debugMode}
initPos={lyricComponentInitPos[i]}
/>
{/each} {/each}
<div class="relative w-full h-[50rem]"></div> <div class="relative w-full h-[50rem]"></div>
</div> </div>

View File

@ -1,4 +1,4 @@
import { getVelocity } from "./derivative"; import { getVelocity } from './derivative';
/** MIT License github.com/pushkine/ */ /** MIT License github.com/pushkine/ */
export interface SpringParams { export interface SpringParams {
@ -39,13 +39,7 @@ export class Spring {
private resetSolver() { private resetSolver() {
const curV = this.getV(this.currentTime); const curV = this.getV(this.currentTime);
this.currentTime = 0; this.currentTime = 0;
this.currentSolver = solveSpring( this.currentSolver = solveSpring(this.currentPosition, curV, this.targetPosition, 0, this.params);
this.currentPosition,
curV,
this.targetPosition,
0,
this.params,
);
this.getV = getVelocity(this.currentSolver); this.getV = getVelocity(this.currentSolver);
this.getV2 = getVelocity(this.getV); this.getV2 = getVelocity(this.getV);
} }
@ -72,7 +66,7 @@ export class Spring {
this.queueParams.time -= delta; this.queueParams.time -= delta;
if (this.queueParams.time <= 0) { if (this.queueParams.time <= 0) {
this.updateParams({ this.updateParams({
...this.queueParams, ...this.queueParams
}); });
} }
} }
@ -91,13 +85,13 @@ export class Spring {
this.queueParams = { this.queueParams = {
...(this.queuePosition ?? {}), ...(this.queuePosition ?? {}),
...params, ...params,
time: delay, time: delay
}; };
} else { } else {
this.queuePosition = undefined; this.queuePosition = undefined;
this.params = { this.params = {
...this.params, ...this.params,
...params, ...params
}; };
this.resetSolver(); this.resetSolver();
} }
@ -107,7 +101,7 @@ export class Spring {
this.queuePosition = { this.queuePosition = {
...(this.queuePosition ?? {}), ...(this.queuePosition ?? {}),
position: targetPosition, position: targetPosition,
time: delay, time: delay
}; };
} else { } else {
this.queuePosition = undefined; this.queuePosition = undefined;
@ -125,7 +119,7 @@ function solveSpring(
velocity: number, velocity: number,
to: number, to: number,
delay: seconds = 0, delay: seconds = 0,
params?: Partial<SpringParams>, params?: Partial<SpringParams>
): (t: seconds) => number { ): (t: seconds) => number {
const soft = params?.soft ?? false; const soft = params?.soft ?? false;
const stiffness = params?.stiffness ?? 100; const stiffness = params?.stiffness ?? 100;
@ -142,17 +136,12 @@ function solveSpring(
}; };
} }
const damping_frequency = Math.sqrt(4.0 * mass * stiffness - damping ** 2.0); const damping_frequency = Math.sqrt(4.0 * mass * stiffness - damping ** 2.0);
const leftover = const leftover = (damping * delta - 2.0 * mass * velocity) / damping_frequency;
(damping * delta - 2.0 * mass * velocity) / damping_frequency;
const dfm = (0.5 * damping_frequency) / mass; const dfm = (0.5 * damping_frequency) / mass;
const dm = -(0.5 * damping) / mass; const dm = -(0.5 * damping) / mass;
return (t: seconds) => { return (t: seconds) => {
t -= delay; t -= delay;
if (t < 0) return from; if (t < 0) return from;
return ( return to - (Math.cos(t * dfm) * delta + Math.sin(t * dfm) * leftover) * Math.E ** (t * dm);
to -
(Math.cos(t * dfm) * delta + Math.sin(t * dfm) * leftover) *
Math.E ** (t * dm)
);
}; };
} }

View File

@ -214,7 +214,7 @@
<NewLyrics {originalLyrics} progress={currentProgress} player={audioPlayer}/> <NewLyrics {originalLyrics} progress={currentProgress} player={audioPlayer}/>
<Lyrics lyrics={lyricsText} {originalLyrics} progress={currentProgress} player={audioPlayer} class="hidden" /> <!-- <Lyrics lyrics={lyricsText} {originalLyrics} progress={currentProgress} player={audioPlayer} class="hidden" /> -->
<audio <audio
bind:this={audioPlayer} bind:this={audioPlayer}