Skip to content

Commit

Permalink
Add closed-form damped harmonic oscillator algorithm to Animated.spring
Browse files Browse the repository at this point in the history
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 facebook/react-native#15322

Differential Revision: D5794791

Pulled By: hramos

fbshipit-source-id: 58ed9e134a097e321c85c417a142576f6a8952f8
  • Loading branch information
Adam Miskiewicz authored and facebook-github-bot committed Sep 21, 2017
1 parent e947fb3 commit 80a0b1c
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 29 deletions.
70 changes: 48 additions & 22 deletions RNTesterUnitTests/RCTNativeAnimatedNodesManagerTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -266,19 +266,12 @@ - (void)testNodeValueListenerIfListening
XCTAssertEqual(observer.calls.count, 7UL);
}

- (void)testSpringAnimation
- (void)performSpringAnimationTestWithConfig:(NSDictionary*)config isCriticallyDamped:(BOOL)testForCriticallyDamped
{
[self createSimpleAnimatedView:@1000 withOpacity:0];
[_nodesManager startAnimatingNode:@1
nodeTag:@1
config:@{@"type": @"spring",
@"friction": @7,
@"tension": @40,
@"initialVelocity": @0,
@"toValue": @1,
@"restSpeedThreshold": @0.001,
@"restDisplacementThreshold": @0.001,
@"overshootClamping": @NO}
config:config
endCallback:nil];

BOOL wasGreaterThanOne = NO;
Expand All @@ -299,7 +292,7 @@ - (void)testSpringAnimation
}

// Verify that animation step is relatively small.
XCTAssertLessThan(fabs(currentValue - previousValue), 0.1);
XCTAssertLessThan(fabs(currentValue - previousValue), 0.12);

previousValue = currentValue;
}
Expand All @@ -308,13 +301,45 @@ - (void)testSpringAnimation
XCTAssertEqual(previousValue, 1.0);

// Verify that value has reached some maximum value that is greater than the final value (bounce).
XCTAssertTrue(wasGreaterThanOne);
if (testForCriticallyDamped) {
XCTAssertFalse(wasGreaterThanOne);
} else {
XCTAssertTrue(wasGreaterThanOne);
}

[[_uiManager reject] synchronouslyUpdateViewOnUIThread:OCMOCK_ANY viewName:OCMOCK_ANY props:OCMOCK_ANY];
[_nodesManager stepAnimations:_displayLink];
[_uiManager verify];
}

- (void)testUnderdampedSpringAnimation
{
[self performSpringAnimationTestWithConfig:@{@"type": @"spring",
@"stiffness": @230.3,
@"damping": @22,
@"mass": @1,
@"initialVelocity": @0,
@"toValue": @1,
@"restSpeedThreshold": @0.001,
@"restDisplacementThreshold": @0.001,
@"overshootClamping": @NO}
isCriticallyDamped:NO];
}

- (void)testCritcallyDampedSpringAnimation
{
[self performSpringAnimationTestWithConfig:@{@"type": @"spring",
@"stiffness": @1000,
@"damping": @500,
@"mass": @3,
@"initialVelocity": @0,
@"toValue": @1,
@"restSpeedThreshold": @0.001,
@"restDisplacementThreshold": @0.001,
@"overshootClamping": @NO}
isCriticallyDamped:YES];
}

- (void)testDecayAnimation
{
[self createSimpleAnimatedView:@1000 withOpacity:0];
Expand Down Expand Up @@ -415,15 +440,16 @@ - (void)testSpringAnimationLoop
nodeTag:@1
config:@{@"type": @"spring",
@"iterations": @5,
@"friction": @7,
@"tension": @40,
@"stiffness": @230.2,
@"damping": @22,
@"mass": @1,
@"initialVelocity": @0,
@"toValue": @1,
@"restSpeedThreshold": @0.001,
@"restDisplacementThreshold": @0.001,
@"overshootClamping": @NO}
endCallback:nil];

BOOL didComeToRest = NO;
CGFloat previousValue = 0;
NSUInteger numberOfResets = 0;
Expand All @@ -433,32 +459,32 @@ - (void)testSpringAnimationLoop
[invocation getArgument:&props atIndex:4];
currentValue = props[@"opacity"].doubleValue;
}] synchronouslyUpdateViewOnUIThread:OCMOCK_ANY viewName:OCMOCK_ANY props:OCMOCK_ANY];

// Run for 3 seconds five times.
for (NSUInteger i = 0; i < 3 * 60 * 5; i++) {
[_nodesManager stepAnimations:_displayLink];

if (!didComeToRest) {
// Verify that animation step is relatively small.
XCTAssertLessThan(fabs(currentValue - previousValue), 0.1);
XCTAssertLessThan(fabs(currentValue - previousValue), 0.12);
}

// Test to see if it reset after coming to rest
if (didComeToRest && currentValue == 0) {
didComeToRest = NO;
numberOfResets++;
}

// Record that the animation did come to rest when it rests on toValue.
didComeToRest = fabs(currentValue - 1) < 0.001 && fabs(currentValue - previousValue) < 0.001;

previousValue = currentValue;
}

// Verify that value reset 4 times after finishing a full animation and is currently resting.
XCTAssertEqual(numberOfResets, 4u);
XCTAssertTrue(didComeToRest);

[[_uiManager reject] synchronouslyUpdateViewOnUIThread:OCMOCK_ANY viewName:OCMOCK_ANY props:OCMOCK_ANY];
[_nodesManager stepAnimations:_displayLink];
[_uiManager verify];
Expand Down
12 changes: 6 additions & 6 deletions js/AnimatedGratuitousApp/AnExChained.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ class AnExChained extends React.Component<Object, any> {
<Animated.Image
{...handlers}
key={i}
source={{uri: CHAIN_IMGS[j]}}
source={CHAIN_IMGS[j]}
style={[styles.sticker, {
transform: this.state.stickers[j].getTranslateTransform(), // simple conversion
}]}
Expand All @@ -100,11 +100,11 @@ var styles = StyleSheet.create({
});

var CHAIN_IMGS = [
'https://scontent-sea1-1.xx.fbcdn.net/hphotos-xpf1/t39.1997-6/p160x160/10574705_1529175770666007_724328156_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-xfa1/t39.1997-6/p160x160/851575_392309884199657_1917957497_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-xfa1/t39.1997-6/p160x160/851567_555288911225630_1628791128_n.png',
'https://scontent-sea1-1.xx.fbcdn.net/hphotos-xfa1/t39.1997-6/p160x160/851583_531111513625557_903469595_n.png',
'https://scontent-sea1-1.xx.fbcdn.net/hphotos-xpa1/t39.1997-6/p160x160/851577_510515972354399_2147096990_n.png',
require('../hawk.png'),
require('../bunny.png'),
require('../relay.png'),
require('../hawk.png'),
require('../bunny.png')
];

module.exports = AnExChained;
28 changes: 27 additions & 1 deletion js/NativeAnimationsExample.js
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ exports.examples = [
},
},
{
title: 'translateX => Animated.spring',
title: 'translateX => Animated.spring (bounciness/speed)',
render: function() {
return (
<Tester type="spring" config={{bounciness: 0}}>
Expand All @@ -454,6 +454,32 @@ exports.examples = [
);
},
},
{
title: 'translateX => Animated.spring (stiffness/damping/mass)',
render: function() {
return (
<Tester type="spring" config={{stiffness: 1000, damping: 500, mass: 3 }}>
{anim => (
<Animated.View
style={[
styles.block,
{
transform: [
{
translateX: anim.interpolate({
inputRange: [0, 1],
outputRange: [0, 100],
}),
},
],
},
]}
/>
)}
</Tester>
);
},
},
{
title: 'translateX => Animated.decay',
render: function() {
Expand Down

0 comments on commit 80a0b1c

Please sign in to comment.