Files
react-native/ReactAndroid/src/main/java/com/facebook/react/animated/SpringAnimation.java
Adam Miskiewicz 26133beda9 Add closed-form damped harmonic oscillator algorithm to Animated.spring
Summary:
As I was working on mimicking iOS animations for my ongoing work with `react-navigation`, one task I had was to match the "push from right" animation that is common in UINavigationController.

I was able to grab the exact animation values for this animation with some LLDB magic, and found that the screen is animated using a `CASpringAnimation` with the parameters:

- stiffness: 1000
- damping: 500
- mass: 3

After spending a considerable amount of time attempting to replicate the spring created with these values by CASpringAnimation by specifying values for tension and friction in the current `Animated.spring` implementation, I was unable to come up with mathematically equivalent values that could replicate the spring _exactly_.

After doing some research, I ended up disassembling the QuartzCore framework, reading the assembly, and determined that Apple's implementation of `CASpringAnimation` does not use an integrated, numerical animation model as we do in Animated.spring, but instead solved for the closed form of the equations that govern damped harmonic oscillation (the differential equations themselves are [here](https://en.wikipedia.org/wiki/Harmonic_oscillator#Damped_harmonic_oscillator), and a paper describing the math to arrive at the closed-form solution to the second-order ODE that describes the DHO is [here](http://planetmath.org/sites/default/files/texpdf/39745.pdf)).

Though we can get the currently implemented RK4 integration close by tweaking some values, it is, the current model is at it's core, an approximation. It seemed that if I wanted to implement the `CASpringAnimation` behavior _exactly_, I needed to implement the analytical model (as is implemented in `CASpringAnimation`) in `Animated`.

We add three new optional parameters to `Animated.spring` (to both the JS and native implementations):

- `stiffness`, a value describing the spring's stiffness coefficient
- `damping`, a value defining how the spring's motion should be damped due to the forces of friction (technically called the _viscous damping coefficient_).
- `mass`, a value describing the mass of the object attached to the end of the simulated spring

Just like if a developer were to specify `bounciness`/`speed` and `tension`/`friction` in the same config, specifying any of these new parameters while also specifying the aforementioned config values will cause an error to be thrown.

~Defaults for `Animated.spring` across all three implementations (JS/iOS/Android) stay the same, so this is intended to be *a non-breaking change*.~

~If `stiffness`, `damping`, or `mass` are provided in the config, we switch to animating the spring with the new damped harmonic oscillator model (`DHO` as described in the code).~

We replace the old RK4 integration implementation with our new analytic implementation. Tension/friction nicely correspond directly to stiffness/damping with the mass of the spring locked at 1. This is intended to be *a non-breaking change*, but there may be very slight differences in people's springs (maybe not even noticeable to the naked eye), given the fact that this implementation is more accurate.

The DHO animation algorithm will calculate the _position_ of the spring at time _t_ explicitly and in an analytical fashion, and use this calculation to update the animation's value. It will also analytically calculate the velocity at time _t_, so as to allow animated value tracking to continue to work as expected.

Also, docs have been updated to cover the new configuration options (and also I added docs for Animated configuration options that were missing, such as `restDisplacementThreshold`, etc).

Run tests. Run "Animated Gratuitous App" and "NativeAnimation" example in RNTester.
Closes https://github.com/facebook/react-native/pull/15322

Differential Revision: D5794791

Pulled By: hramos

fbshipit-source-id: 58ed9e134a097e321c85c417a142576f6a8952f8
2017-09-20 23:38:16 -07:00

189 lines
6.5 KiB
Java

package com.facebook.react.animated;
import com.facebook.react.bridge.ReadableMap;
/**
* Implementation of {@link AnimationDriver} providing support for spring animations. The
* implementation has been copied from android implementation of Rebound library (see
* <a href="http://facebook.github.io/rebound/">http://facebook.github.io/rebound/</a>)
*/
/*package*/ class SpringAnimation extends AnimationDriver {
// maximum amount of time to simulate per physics iteration in seconds (4 frames at 60 FPS)
private static final double MAX_DELTA_TIME_SEC = 0.064;
// fixed timestep to use in the physics solver in seconds
private static final double SOLVER_TIMESTEP_SEC = 0.001;
// storage for the current and prior physics state while integration is occurring
private static class PhysicsState {
double position;
double velocity;
}
private long mLastTime;
private boolean mSpringStarted;
// configuration
private double mSpringStiffness;
private double mSpringDamping;
private double mSpringMass;
private double mInitialVelocity;
private boolean mOvershootClampingEnabled;
// all physics simulation objects are final and reused in each processing pass
private final PhysicsState mCurrentState = new PhysicsState();
private double mStartValue;
private double mEndValue;
// thresholds for determining when the spring is at rest
private double mRestSpeedThreshold;
private double mDisplacementFromRestThreshold;
private double mTimeAccumulator = 0;
// for controlling loop
private int mIterations;
private int mCurrentLoop = 0;
private double mOriginalValue;
SpringAnimation(ReadableMap config) {
mSpringStiffness = config.getDouble("stiffness");
mSpringDamping = config.getDouble("damping");
mSpringMass = config.getDouble("mass");
mInitialVelocity = config.getDouble("initialVelocity");
mCurrentState.velocity = mInitialVelocity;
mEndValue = config.getDouble("toValue");
mRestSpeedThreshold = config.getDouble("restSpeedThreshold");
mDisplacementFromRestThreshold = config.getDouble("restDisplacementThreshold");
mOvershootClampingEnabled = config.getBoolean("overshootClamping");
mIterations = config.hasKey("iterations") ? config.getInt("iterations") : 1;
mHasFinished = mIterations == 0;
}
@Override
public void runAnimationStep(long frameTimeNanos) {
long frameTimeMillis = frameTimeNanos / 1000000;
if (!mSpringStarted) {
if (mCurrentLoop == 0) {
mOriginalValue = mAnimatedValue.mValue;
mCurrentLoop = 1;
}
mStartValue = mCurrentState.position = mAnimatedValue.mValue;
mLastTime = frameTimeMillis;
mTimeAccumulator = 0.0;
mSpringStarted = true;
}
advance((frameTimeMillis - mLastTime) / 1000.0);
mLastTime = frameTimeMillis;
mAnimatedValue.mValue = mCurrentState.position;
if (isAtRest()) {
if (mIterations == -1 || mCurrentLoop < mIterations) { // looping animation, return to start
mSpringStarted = false;
mAnimatedValue.mValue = mOriginalValue;
mCurrentLoop++;
} else { // animation has completed
mHasFinished = true;
}
}
}
/**
* get the displacement from rest for a given physics state
* @param state the state to measure from
* @return the distance displaced by
*/
private double getDisplacementDistanceForState(PhysicsState state) {
return Math.abs(mEndValue - state.position);
}
/**
* check if the current state is at rest
* @return is the spring at rest
*/
private boolean isAtRest() {
return Math.abs(mCurrentState.velocity) <= mRestSpeedThreshold &&
(getDisplacementDistanceForState(mCurrentState) <= mDisplacementFromRestThreshold ||
mSpringStiffness == 0);
}
/**
* Check if the spring is overshooting beyond its target.
* @return true if the spring is overshooting its target
*/
private boolean isOvershooting() {
return mSpringStiffness > 0 &&
((mStartValue < mEndValue && mCurrentState.position > mEndValue) ||
(mStartValue > mEndValue && mCurrentState.position < mEndValue));
}
private void advance(double realDeltaTime) {
if (isAtRest()) {
return;
}
// clamp the amount of realTime to simulate to avoid stuttering in the UI. We should be able
// to catch up in a subsequent advance if necessary.
double adjustedDeltaTime = realDeltaTime;
if (realDeltaTime > MAX_DELTA_TIME_SEC) {
adjustedDeltaTime = MAX_DELTA_TIME_SEC;
}
mTimeAccumulator += adjustedDeltaTime;
double c = mSpringDamping;
double m = mSpringMass;
double k = mSpringStiffness;
double v0 = -mInitialVelocity;
double zeta = c / (2 * Math.sqrt(k * m ));
double omega0 = Math.sqrt(k / m);
double omega1 = omega0 * Math.sqrt(1.0 - (zeta * zeta));
double x0 = mEndValue - mStartValue;
double velocity;
double position;
double t = mTimeAccumulator;
if (zeta < 1) {
// Under damped
double envelope = Math.exp(-zeta * omega0 * t);
position =
mEndValue -
envelope *
((v0 + zeta * omega0 * x0) / omega1 * Math.sin(omega1 * t) +
x0 * Math.cos(omega1 * t));
// This looks crazy -- it's actually just the derivative of the
// oscillation function
velocity =
zeta *
omega0 *
envelope *
(Math.sin(omega1 * t) * (v0 + zeta * omega0 * x0) / omega1 +
x0 * Math.cos(omega1 * t)) -
envelope *
(Math.cos(omega1 * t) * (v0 + zeta * omega0 * x0) -
omega1 * x0 * Math.sin(omega1 * t));
} else {
// Critically damped spring
double envelope = Math.exp(-omega0 * t);
position = mEndValue - envelope * (x0 + (v0 + omega0 * x0) * t);
velocity =
envelope * (v0 * (t * omega0 - 1) + t * x0 * (omega0 * omega0));
}
mCurrentState.position = position;
mCurrentState.velocity = velocity;
// End the spring immediately if it is overshooting and overshoot clamping is enabled.
// Also make sure that if the spring was considered within a resting threshold that it's now
// snapped to its end value.
if (isAtRest() || (mOvershootClampingEnabled && isOvershooting())) {
// Don't call setCurrentValue because that forces a call to onSpringUpdate
if (mSpringStiffness > 0) {
mStartValue = mEndValue;
mCurrentState.position = mEndValue;
} else {
mEndValue = mCurrentState.position;
mStartValue = mEndValue;
}
mCurrentState.velocity = 0;
}
}
}