🎥 Make videos programmatically with React
replace with threshold parameter
Jonny Burger5702a06c2d8b
diff --git a/packages/core/src/spring.ts b/packages/core/src/spring.tsdeleted file mode 100644index 2b4df0cc64..0000000000--- a/packages/core/src/spring.ts+++ /dev/null@@ -1,227 +0,0 @@-type AnimationNode = {- lastTimestamp: number;- toValue: number;- current: number;- velocity: number;- isFinished?: boolean;- prevPosition?: number;-};--export type SpringConfig = {- damping: number;- mass: number;- stiffness: number;- overshootClamping: boolean;-};--const defaultSpringConfig: SpringConfig = {- damping: 10,- mass: 1,- stiffness: 100,- overshootClamping: false,-};--const DEFAULT_REST_SPEED_THRESHOLD = 0.001;-const DEFAULT_REST_DISPLACEMENT_THRESHOLD = 0.001;--function advance({- animation,- now,- config,- restDisplacementThreshold,- restSpeedThreshold,-}: {- animation: AnimationNode;- now: number;- config: SpringConfig;- restDisplacementThreshold: number;- restSpeedThreshold: number;-}): AnimationNode {- const copiedAnimated = {...animation};- const {toValue, lastTimestamp, current, velocity} = copiedAnimated;-- const deltaTime = Math.min(now - lastTimestamp, 64);- copiedAnimated.lastTimestamp = now;-- const c = config.damping;- const m = config.mass;- const k = config.stiffness;-- const v0 = -velocity;- const x0 = toValue - current;-- const zeta = c / (2 * Math.sqrt(k * m)); // damping ratio- const omega0 = Math.sqrt(k / m); // undamped angular frequency of the oscillator (rad/ms)- const omega1 = omega0 * Math.sqrt(1 - zeta ** 2); // exponential decay-- const t = deltaTime / 1000;-- const sin1 = Math.sin(omega1 * t);- const cos1 = Math.cos(omega1 * t);-- // under damped- const underDampedEnvelope = Math.exp(-zeta * omega0 * t);- const underDampedFrag1 =- underDampedEnvelope *- (sin1 * ((v0 + zeta * omega0 * x0) / omega1) + x0 * cos1);-- const underDampedPosition = toValue - underDampedFrag1;- // This looks crazy -- it's actually just the derivative of the oscillation function- const underDampedVelocity =- zeta * omega0 * underDampedFrag1 -- underDampedEnvelope *- (cos1 * (v0 + zeta * omega0 * x0) - omega1 * x0 * sin1);-- // critically damped- const criticallyDampedEnvelope = Math.exp(-omega0 * t);- const criticallyDampedPosition =- toValue - criticallyDampedEnvelope * (x0 + (v0 + omega0 * x0) * t);-- const criticallyDampedVelocity =- criticallyDampedEnvelope *- (v0 * (t * omega0 - 1) + t * x0 * omega0 * omega0);-- let isOvershooting;- if (config.overshootClamping && config.stiffness != 0) {- if (animation.prevPosition != null && animation.prevPosition < toValue) {- isOvershooting = current > toValue;- } else {- isOvershooting = current < toValue;- }- } else {- isOvershooting = false;- }-- const isVelocity = Math.abs(animation.velocity) < restSpeedThreshold;-- const isDisplacement =- config.stiffness == 0 ||- Math.abs(toValue - current) < restDisplacementThreshold;-- if (isOvershooting == true || (isVelocity && isDisplacement)) {- copiedAnimated.isFinished = true;- }-- copiedAnimated.prevPosition = current;- if (zeta < 1) {- copiedAnimated.current = underDampedPosition;- copiedAnimated.velocity = underDampedVelocity;- } else {- copiedAnimated.current = criticallyDampedPosition;- copiedAnimated.velocity = criticallyDampedVelocity;- }-- if (copiedAnimated.isFinished) {- copiedAnimated.current = toValue;- }-- return copiedAnimated;-}--function springCalculation({- from = 0,- to = 1,- frame,- fps,- config = {},- prevPosition = 0,- restDisplacementThreshold,- restSpeedThreshold,-}: {- from?: number;- to?: number;- frame: number;- fps: number;- config?: Partial<SpringConfig>;- prevPosition?: number;- restDisplacementThreshold: number;- restSpeedThreshold: number;-}): AnimationNode {- let animation: AnimationNode = {- lastTimestamp: 0,- current: from,- toValue: to,- velocity: 0,- isFinished: false,- prevPosition,- };- const frameClamped = Math.max(0, frame);- const unevenRest = frameClamped % 1;- for (let f = 0; f <= Math.floor(frameClamped); f++) {- if (f === Math.floor(frameClamped)) {- f += unevenRest;- }- const time = (f / fps) * 1000;- animation = advance({- animation,- now: time,- config: {- ...defaultSpringConfig,- ...config,- },- restDisplacementThreshold,- restSpeedThreshold,- });- }- return animation;-}--export function spring({- from = 0,- to = 1,- frame,- fps,- config = {},-}: {- frame: number;- fps: number;- config?: Partial<SpringConfig>;- from?: number;- to?: number;-}): number {- return springCalculation({- fps,- frame,- config,- from,- to,- restDisplacementThreshold: DEFAULT_REST_DISPLACEMENT_THRESHOLD,- restSpeedThreshold: DEFAULT_REST_SPEED_THRESHOLD,- }).current;-}--export function measureSpring({- from = 0,- to = 1,- fps,- config = {},- restDisplacementThreshold = DEFAULT_REST_DISPLACEMENT_THRESHOLD,- restSpeedThreshold = DEFAULT_REST_SPEED_THRESHOLD,-}: {- fps: number;- config?: Partial<SpringConfig>;- restDisplacementThreshold?: number;- restSpeedThreshold?: number;- from?: number;- to?: number;-}): number {- let frame = 0;- const calc = () => {- return springCalculation({- prevPosition: 0,- fps,- frame,- config,- from,- to,- restDisplacementThreshold,- restSpeedThreshold,- });- };- let animation = calc();- while (!animation.isFinished) {- frame++;- animation = calc();- }- return frame;-}diff --git a/packages/core/src/spring/index.ts b/packages/core/src/spring/index.tsnew file mode 100644index 0000000000..cbe3cd1459--- /dev/null+++ b/packages/core/src/spring/index.ts@@ -0,0 +1,33 @@+import {springCalculation, SpringConfig} from './spring-utils';++export function spring({+ from = 0,+ to = 1,+ frame,+ fps,+ config = {},+}: {+ frame: number;+ fps: number;+ config?: Partial<SpringConfig>;+ from?: number;+ to?: number;+}): number {+ const spr = springCalculation({+ fps,+ frame,+ config,+ from,+ to,+ });+ if (!config.overshootClamping) {+ return spr.current;+ }+ if (to >= from) {+ return Math.min(spr.current, to);+ }+ return Math.max(spr.current, to);+}++export {measureSpring} from './measure-spring';+export {SpringConfig} from './spring-utils';diff --git a/packages/core/src/spring/measure-spring.ts b/packages/core/src/spring/measure-spring.tsnew file mode 100644index 0000000000..de2368c991--- /dev/null+++ b/packages/core/src/spring/measure-spring.ts@@ -0,0 +1,73 @@+import {springCalculation, SpringConfig} from './spring-utils';++export function measureSpring({+ from = 0,+ to = 1,+ fps,+ config = {},+ threshold = 0.005,+}: {+ fps: number;+ config?: Partial<SpringConfig>;+ threshold?: number;+ from?: number;+ to?: number;+}): number {+ if (typeof threshold !== 'number') {+ throw new TypeError(+ `threshold must be a number, got ${threshold} of type ${typeof threshold}`+ );+ }+ if (isNaN(threshold)) {+ throw new TypeError('Threshold is NaN');+ }+ if (!Number.isFinite(threshold)) {+ throw new TypeError('Threshold is not finite');+ }+ if (threshold < 0) {+ throw new TypeError('Threshold is below 0');+ }+ if (threshold > 1) {+ throw new TypeError('Threshold is above 1');+ }++ const range = Math.abs(from - to);+ let frame = 0;+ let finishedFrame = 0;+ const calc = () => {+ return springCalculation({+ fps,+ frame,+ config,+ from,+ to,+ });+ };+ let animation = calc();+ const calcDifference = () => {+ return (+ Math.abs(animation.current - animation.toValue) /+ (range === 0 ? 1 : range)+ );+ };+ let difference = calcDifference();+ while (difference > threshold) {+ frame++;+ animation = calc();+ difference = calcDifference();+ }+ // Since spring is bouncy, just because it's under the threshold we+ // cannot be sure it's done. We need to animate further until it stays in the+ // threshold for, say, 20 frames.+ finishedFrame = frame;+ for (let i = 0; i < 20; i++) {+ frame++;+ animation = calc();+ difference = calcDifference();+ if (difference > threshold) {+ i = 0;+ finishedFrame = frame + 1;+ }+ }+ return finishedFrame;+}diff --git a/packages/core/src/spring/spring-utils.ts b/packages/core/src/spring/spring-utils.tsnew file mode 100644index 0000000000..097a1c249c--- /dev/null+++ b/packages/core/src/spring/spring-utils.ts@@ -0,0 +1,154 @@+type AnimationNode = {+ lastTimestamp: number;+ toValue: number;+ current: number;+ velocity: number;+ prevPosition?: number;+};++export type SpringConfig = {+ damping: number;+ mass: number;+ stiffness: number;+ overshootClamping: boolean;+};++const defaultSpringConfig: SpringConfig = {+ damping: 10,+ mass: 1,+ stiffness: 100,+ overshootClamping: false,+};++const advanceCache: {[key: string]: AnimationNode} = {};++function advance({+ animation,+ now,+ config,+}: {+ animation: AnimationNode;+ now: number;+ config: SpringConfig;+}): AnimationNode {+ const {toValue, lastTimestamp, current, velocity} = animation;++ const deltaTime = Math.min(now - lastTimestamp, 64);++ const c = config.damping;+ const m = config.mass;+ const k = config.stiffness;++ const cacheKey = [+ toValue,+ lastTimestamp,+ current,+ velocity,+ c,+ m,+ k,+ now,+ ].join('-');+ if (advanceCache[cacheKey]) {+ return advanceCache[cacheKey];+ }++ const v0 = -velocity;+ const x0 = toValue - current;++ const zeta = c / (2 * Math.sqrt(k * m)); // damping ratio+ const omega0 = Math.sqrt(k / m); // undamped angular frequency of the oscillator (rad/ms)+ const omega1 = omega0 * Math.sqrt(1 - zeta ** 2); // exponential decay++ const t = deltaTime / 1000;++ const sin1 = Math.sin(omega1 * t);+ const cos1 = Math.cos(omega1 * t);++ // under damped+ const underDampedEnvelope = Math.exp(-zeta * omega0 * t);+ const underDampedFrag1 =+ underDampedEnvelope *+ (sin1 * ((v0 + zeta * omega0 * x0) / omega1) + x0 * cos1);++ const underDampedPosition = toValue - underDampedFrag1;+ // This looks crazy -- it's actually just the derivative of the oscillation function+ const underDampedVelocity =+ zeta * omega0 * underDampedFrag1 -+ underDampedEnvelope *+ (cos1 * (v0 + zeta * omega0 * x0) - omega1 * x0 * sin1);++ // critically damped+ const criticallyDampedEnvelope = Math.exp(-omega0 * t);+ const criticallyDampedPosition =+ toValue - criticallyDampedEnvelope * (x0 + (v0 + omega0 * x0) * t);++ const criticallyDampedVelocity =+ criticallyDampedEnvelope *+ (v0 * (t * omega0 - 1) + t * x0 * omega0 * omega0);++ const animationNode: AnimationNode = {+ toValue,+ prevPosition: current,+ lastTimestamp: now,+ current: zeta < 1 ? underDampedPosition : criticallyDampedPosition,+ velocity: zeta < 1 ? underDampedVelocity : criticallyDampedVelocity,+ };+ advanceCache[cacheKey] = animationNode;+ return animationNode;+}++const calculationCache: {[key: string]: AnimationNode} = {};++export function springCalculation({+ from = 0,+ to = 1,+ frame,+ fps,+ config = {},+}: {+ from?: number;+ to?: number;+ frame: number;+ fps: number;+ config?: Partial<SpringConfig>;+}): AnimationNode {+ const cacheKey = [+ from,+ to,+ frame,+ fps,+ config.damping,+ config.mass,+ config.overshootClamping,+ config.stiffness,+ ].join('-');+ if (calculationCache[cacheKey]) {+ return calculationCache[cacheKey];+ }+ let animation: AnimationNode = {+ lastTimestamp: 0,+ current: from,+ toValue: to,+ velocity: 0,+ prevPosition: 0,+ };+ const frameClamped = Math.max(0, frame);+ const unevenRest = frameClamped % 1;+ for (let f = 0; f <= Math.floor(frameClamped); f++) {+ if (f === Math.floor(frameClamped)) {+ f += unevenRest;+ }+ const time = (f / fps) * 1000;+ animation = advance({+ animation,+ now: time,+ config: {+ ...defaultSpringConfig,+ ...config,+ },+ });+ }+ calculationCache[cacheKey] = animation;+ return animation;+}diff --git a/packages/core/src/test/measure-spring.test.ts b/packages/core/src/test/measure-spring.test.tsindex f372167425..569c5afc48 100644--- a/packages/core/src/test/measure-spring.test.ts+++ b/packages/core/src/test/measure-spring.test.ts@@ -4,13 +4,13 @@ test('Measure spring should work', () => {const duration = measureSpring({fps: 30,});- expect(duration).toBe(54);+ expect(duration).toBe(28);expect(spring({fps: 30,frame: duration,})- ).toBe(1);+ ).toBeCloseTo(1);expect(spring({fps: 30,diff --git a/packages/core/src/test/spring.test.ts b/packages/core/src/test/spring.test.tsindex 49a1c91ae7..d657664e5a 100644--- a/packages/core/src/test/spring.test.ts+++ b/packages/core/src/test/spring.test.ts@@ -34,5 +34,5 @@ test('Spring should go to 1', () => {fps: 30,frame: 100,})- ).toBe(1);+ ).toBeCloseTo(1);});