Release 0.1.0
This commit is contained in:
1 parent
fae05a1709
commit
c8bd9b7435
230 files changed
+17003
-15
No files matched your search
Generated
+30
@@ -0,0 +1,30 @@
|
||||
BSD License
|
||||
|
||||
For Pop software
|
||||
|
||||
Copyright (c) 2014, Facebook, Inc. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name Facebook nor the names of its contributors may be used to
|
||||
endorse or promote products derived from this software without specific
|
||||
prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Generated
+170
@@ -0,0 +1,170 @@
|
||||

|
||||
|
||||
Pop is an extensible animation engine for iOS and OS X. In addition to basic static animations, it supports spring and decay dynamic animations, making it useful for building realistic, physics-based interactions. The API allows quick integration with existing Objective-C codebases and enables the animation of any property on any object. It's a mature and well-tested framework that drives all the animations and transitions in [Paper](http://www.facebook.com/paper).
|
||||
|
||||
[](https://travis-ci.org/facebook/pop)
|
||||
|
||||
## Installation
|
||||
|
||||
Pop is available on [CocoaPods](http://cocoapods.org). Just add the following to your project Podfile:
|
||||
|
||||
```ruby
|
||||
pod 'pop', '~> 1.0'
|
||||
```
|
||||
Alternatively, you can add the project to your workspace and adopt the provided configuration files or manually copy the files under the pop subdirectory into your project. If installing manually, ensure the C++ standard library is also linked by including `-lc++` to your project linker flags.
|
||||
|
||||
## Usage
|
||||
|
||||
Pop adopts the Core Animation explicit animation programming model. Use by including the following import:
|
||||
|
||||
```objective-c
|
||||
#import <pop/POP.h>
|
||||
```
|
||||
|
||||
### Start, Stop & Update
|
||||
|
||||
To start an animation, add it to the object you wish to animate:
|
||||
|
||||
```objective-c
|
||||
POPSpringAnimation *anim = [POPSpringAnimation animation];
|
||||
...
|
||||
[layer pop_addAnimation:anim forKey:@"myKey"];
|
||||
```
|
||||
|
||||
To stop an animation, remove it from the object referencing the key specified on start:
|
||||
|
||||
```objective-c
|
||||
[layer pop_removeAnimationForKey:@"myKey"];
|
||||
```
|
||||
|
||||
The key can also be used to query for the existence of an animation. Updating the toValue of a running animation can provide the most seamless way to change course:
|
||||
|
||||
```objective-c
|
||||
anim = [layer pop_animationForKey:@"myKey"];
|
||||
if (anim) {
|
||||
/* update to value to new destination */
|
||||
anim.toValue = @(42.0);
|
||||
} else {
|
||||
/* create and start a new animation */
|
||||
....
|
||||
}
|
||||
```
|
||||
|
||||
While a layer was used in the above examples, the Pop interface is implemented as a category addition on NSObject. Any NSObject or subclass can be animated.
|
||||
|
||||
### Types
|
||||
|
||||
There are four concrete animation types: spring, decay, basic and custom.
|
||||
|
||||
Spring animations can be used to give objects a delightful bounce. In this example, we use a spring animation to animate a layer's bounds from its current value to (0, 0, 400, 400):
|
||||
|
||||
```objective-c
|
||||
POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerBounds];
|
||||
anim.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 400, 400)];
|
||||
[layer pop_addAnimation:anim forKey:@"size"];
|
||||
```
|
||||
Decay animations can be used to gradually slow an object to a halt. In this example, we decay a layer's positionX from it's current value and velocity 1000pts per second:
|
||||
|
||||
```objective-c
|
||||
POPDecayAnimation *anim = [POPDecayAnimation animationWithPropertyNamed:kPOPLayerPositionX];
|
||||
anim.velocity = @(1000.);
|
||||
[layer pop_addAnimation:anim forKey:@"slide"];
|
||||
```
|
||||
|
||||
Basic animations can be used to interpolate values over a specified time period. To use an ease-in ease-out animation to animate a view's alpha from 0.0 to 1.0 over the default duration:
|
||||
```objective-c
|
||||
POPBasicAnimation *anim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewAlpha];
|
||||
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
|
||||
anim.fromValue = @(0.0);
|
||||
anim.toValue = @(1.0);
|
||||
[view pop_addAnimation:anim forKey:@"fade"];
|
||||
```
|
||||
`POPCustomAnimation` makes creating custom animations and transitions easier by handling CADisplayLink and associated time-step management. See header for more details.
|
||||
|
||||
|
||||
### Properties
|
||||
|
||||
The property animated is specified by the `POPAnimatableProperty` class. In this example we create a spring animation and explicitly set the animatable property corresponding to `-[CALayer bounds]`:
|
||||
|
||||
```objective-c
|
||||
POPSpringAnimation *anim = [POPSpringAnimation animation];
|
||||
anim.property = [POPAnimatableProperty propertyWithName:kPOPLayerBounds];
|
||||
```
|
||||
|
||||
The framework provides many common layer and view animatable properties out of box. You can animate a custom property by creating a new instance of the class. In this example, we declare a custom volume property:
|
||||
|
||||
```objective-c
|
||||
prop = [POPAnimatableProperty propertyWithName:@"com.foo.radio.volume" initializer:^(POPMutableAnimatableProperty *prop) {
|
||||
// read value
|
||||
prop.readBlock = ^(id obj, CGFloat values[]) {
|
||||
values[0] = [obj volume];
|
||||
};
|
||||
// write value
|
||||
prop.writeBlock = ^(id obj, const CGFloat values[]) {
|
||||
[obj setVolume:values[0]];
|
||||
};
|
||||
// dynamics threshold
|
||||
prop.threshold = 0.01;
|
||||
}];
|
||||
|
||||
anim.property = prop;
|
||||
```
|
||||
|
||||
For a complete listing of provided animatable properties, as well more information on declaring custom properties see `POPAnimatableProperty.h`.
|
||||
|
||||
|
||||
### Debugging
|
||||
|
||||
Here are a few tips when debugging. Pop obeys the Simulator's Toggle Slow Animations setting. Try enabling it to slow down animations and more easily observe interactions.
|
||||
|
||||
Consider naming your animations. This will allow you to more easily identify them when referencing them, either via logging or in the debugger:
|
||||
|
||||
```objective-c
|
||||
anim.name = @"springOpen";
|
||||
```
|
||||
|
||||
Each animation comes with an associated tracer. The tracer allows you to record all animation-related events, in a fast and efficient manner, allowing you to query and analyze them after animation completion. The below example starts the tracer and configures it to log all events on animation completion:
|
||||
|
||||
```objective-c
|
||||
POPAnimationTracer *tracer = anim.tracer;
|
||||
tracer.shouldLogAndResetOnCompletion = YES;
|
||||
[tracer start];
|
||||
```
|
||||
|
||||
See `POPAnimationTracer.h` for more details.
|
||||
|
||||
## Testing
|
||||
|
||||
Pop has extensive unit test coverage. To install test dependencies, navigate to the root pop directory and type:
|
||||
|
||||
```sh
|
||||
pod install
|
||||
```
|
||||
|
||||
Assuming CocoaPods is installed, this will include the necessary OCMock dependency to the unit test targets.
|
||||
|
||||
## Resources
|
||||
|
||||
A collection of links to external resources that may prove valuable:
|
||||
|
||||
* [AGGeometryKit+POP - Animating Quadrilaterals with Pop](https://github.com/hfossli/aggeometrykit-pop)
|
||||
* [Apple – Core Animation Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreAnimation_guide/Introduction/Introduction.html)
|
||||
* [Codeplease – Bridging the gesture to animation gap](http://codeplease.io/playing-with-pop-ii/)
|
||||
* [Codeplease – Playing with Pop (iii)](http://codeplease.io/playing-with-pop-iii/)
|
||||
* [Codeplease – Adding a custom animatable property](http://codeplease.io/playing-with-pop-v/)
|
||||
* [iOS Development Tips – UIScrollView-like deceleration with Pop](http://iosdevtips.co/post/84571595353/replicating-uiscrollviews-deceleration-with-facebook)
|
||||
* [Pop Playground – Repository of Pop animation examples](https://github.com/callmeed/pop-playground)
|
||||
* [Pop Playground 2 – Playing with Facebook's framework](http://victorbaro.com/2014/05/pop-playground-playing-with-facebooks-framework/)
|
||||
* [POP-MCAnimate – Concise syntax for the Pop animation framework](https://github.com/matthewcheok/POP-MCAnimate)
|
||||
* [Popping - Great examples in one project](https://github.com/schneiderandre/popping)
|
||||
* [Rebound – Spring Animations for Android](http://facebook.github.io/rebound/)
|
||||
* [Tapity Tutorial – Getting Started with Pop](http://tapity.com/tutorial-getting-started-with-pop/)
|
||||
* [Tweaks – Easily adjust parameters for iOS apps in development](https://github.com/facebook/tweaks)
|
||||
* [POP Tutorial in 5 steps](https://github.com/maxmyers/FacebookPop)
|
||||
|
||||
## Contributing
|
||||
See the CONTRIBUTING file for how to help out.
|
||||
|
||||
## License
|
||||
|
||||
Pop is released under a BSD License. See LICENSE file for details.
|
||||
Generated
+28
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#ifndef POP_POP_H
|
||||
#define POP_POP_H
|
||||
|
||||
#import <pop/POPAnimatableProperty.h>
|
||||
#import <pop/POPAnimation.h>
|
||||
#import <pop/POPAnimationEvent.h>
|
||||
#import <pop/POPAnimationExtras.h>
|
||||
#import <pop/POPAnimationTracer.h>
|
||||
#import <pop/POPAnimator.h>
|
||||
#import <pop/POPBasicAnimation.h>
|
||||
#import <pop/POPCustomAnimation.h>
|
||||
#import <pop/POPDecayAnimation.h>
|
||||
#import <pop/POPDefines.h>
|
||||
#import <pop/POPGeometry.h>
|
||||
#import <pop/POPPropertyAnimation.h>
|
||||
#import <pop/POPSpringAnimation.h>
|
||||
|
||||
|
||||
#endif /* POP_POP_H */
|
||||
Generated
+66
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#ifndef POPACTION_H
|
||||
#define POPACTION_H
|
||||
|
||||
#import <QuartzCore/CATransaction.h>
|
||||
#import <pop/POPDefines.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
namespace POP {
|
||||
|
||||
/**
|
||||
@abstract Disables Core Animation actions using RAII.
|
||||
@discussion The disablement of actions is scoped to the current transaction.
|
||||
*/
|
||||
class ActionDisabler
|
||||
{
|
||||
BOOL state;
|
||||
|
||||
public:
|
||||
ActionDisabler() POP_NOTHROW
|
||||
{
|
||||
state = [CATransaction disableActions];
|
||||
[CATransaction setDisableActions:YES];
|
||||
}
|
||||
|
||||
~ActionDisabler()
|
||||
{
|
||||
[CATransaction setDisableActions:state];
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@abstract Enables Core Animation actions using RAII.
|
||||
@discussion The enablement of actions is scoped to the current transaction.
|
||||
*/
|
||||
class ActionEnabler
|
||||
{
|
||||
BOOL state;
|
||||
|
||||
public:
|
||||
ActionEnabler() POP_NOTHROW
|
||||
{
|
||||
state = [CATransaction disableActions];
|
||||
[CATransaction setDisableActions:NO];
|
||||
}
|
||||
|
||||
~ActionEnabler()
|
||||
{
|
||||
[CATransaction setDisableActions:state];
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#endif /* POPACTION_H */
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
#import <Foundation/NSObject.h>
|
||||
|
||||
@class POPMutableAnimatableProperty;
|
||||
|
||||
/**
|
||||
@abstract Describes an animatable property.
|
||||
*/
|
||||
@interface POPAnimatableProperty : NSObject <NSCopying, NSMutableCopying>
|
||||
|
||||
/**
|
||||
@abstract Property accessor.
|
||||
@param name The name of the property.
|
||||
@return The animatable property with that name or nil if it does not exist.
|
||||
@discussion Common animatable properties are included by default. Use the provided constants to reference.
|
||||
*/
|
||||
+ (id)propertyWithName:(NSString *)name;
|
||||
|
||||
/**
|
||||
@abstract The designated initializer.
|
||||
@param name The name of the property.
|
||||
@param block The block used to configure the property on creation.
|
||||
@return The animatable property with name if it exists, otherwise a newly created instance configured by block.
|
||||
@discussion Custom properties should use reverse-DNS naming. A newly created instance is only mutable in the scope of block. Once constructed, a property becomes immutable.
|
||||
*/
|
||||
+ (id)propertyWithName:(NSString *)name initializer:(void (^)(POPMutableAnimatableProperty *prop))block;
|
||||
|
||||
/**
|
||||
@abstract The name of the property.
|
||||
@discussion Used to uniquely identify an animatable property.
|
||||
*/
|
||||
@property (readonly, nonatomic, copy) NSString *name;
|
||||
|
||||
/**
|
||||
@abstract Block used to read values from a property into an array of floats.
|
||||
*/
|
||||
@property (readonly, nonatomic, copy) void (^readBlock)(id obj, CGFloat values[]);
|
||||
|
||||
/**
|
||||
@abstract Block used to write values from an array of floats into a property.
|
||||
*/
|
||||
@property (readonly, nonatomic, copy) void (^writeBlock)(id obj, const CGFloat values[]);
|
||||
|
||||
/**
|
||||
@abstract The threshold value used when determining completion of dynamics simulations.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign) CGFloat threshold;
|
||||
|
||||
@end
|
||||
|
||||
/**
|
||||
@abstract A mutable animatable property intended for configuration.
|
||||
*/
|
||||
@interface POPMutableAnimatableProperty : POPAnimatableProperty
|
||||
|
||||
/**
|
||||
@abstract A read-write version of POPAnimatableProperty name property.
|
||||
*/
|
||||
@property (readwrite, nonatomic, copy) NSString *name;
|
||||
|
||||
/**
|
||||
@abstract A read-write version of POPAnimatableProperty readBlock property.
|
||||
*/
|
||||
@property (readwrite, nonatomic, copy) void (^readBlock)(id obj, CGFloat values[]);
|
||||
|
||||
/**
|
||||
@abstract A read-write version of POPAnimatableProperty writeBlock property.
|
||||
*/
|
||||
@property (readwrite, nonatomic, copy) void (^writeBlock)(id obj, const CGFloat values[]);
|
||||
|
||||
/**
|
||||
@abstract A read-write version of POPAnimatableProperty threshold property.
|
||||
*/
|
||||
@property (readwrite, nonatomic, assign) CGFloat threshold;
|
||||
|
||||
@end
|
||||
|
||||
/**
|
||||
Common CALayer property names.
|
||||
*/
|
||||
extern NSString * const kPOPLayerBackgroundColor;
|
||||
extern NSString * const kPOPLayerBounds;
|
||||
extern NSString * const kPOPLayerCornerRadius;
|
||||
extern NSString * const kPOPLayerBorderWidth;
|
||||
extern NSString * const kPOPLayerBorderColor;
|
||||
extern NSString * const kPOPLayerOpacity;
|
||||
extern NSString * const kPOPLayerPosition;
|
||||
extern NSString * const kPOPLayerPositionX;
|
||||
extern NSString * const kPOPLayerPositionY;
|
||||
extern NSString * const kPOPLayerRotation;
|
||||
extern NSString * const kPOPLayerRotationX;
|
||||
extern NSString * const kPOPLayerRotationY;
|
||||
extern NSString * const kPOPLayerScaleX;
|
||||
extern NSString * const kPOPLayerScaleXY;
|
||||
extern NSString * const kPOPLayerScaleY;
|
||||
extern NSString * const kPOPLayerSize;
|
||||
extern NSString * const kPOPLayerSubscaleXY;
|
||||
extern NSString * const kPOPLayerSubtranslationX;
|
||||
extern NSString * const kPOPLayerSubtranslationXY;
|
||||
extern NSString * const kPOPLayerSubtranslationY;
|
||||
extern NSString * const kPOPLayerSubtranslationZ;
|
||||
extern NSString * const kPOPLayerTranslationX;
|
||||
extern NSString * const kPOPLayerTranslationXY;
|
||||
extern NSString * const kPOPLayerTranslationY;
|
||||
extern NSString * const kPOPLayerTranslationZ;
|
||||
extern NSString * const kPOPLayerZPosition;
|
||||
extern NSString * const kPOPLayerShadowColor;
|
||||
extern NSString * const kPOPLayerShadowOffset;
|
||||
extern NSString * const kPOPLayerShadowOpacity;
|
||||
extern NSString * const kPOPLayerShadowRadius;
|
||||
|
||||
/**
|
||||
Common CAShapeLayer property names.
|
||||
*/
|
||||
extern NSString * const kPOPShapeLayerStrokeStart;
|
||||
extern NSString * const kPOPShapeLayerStrokeEnd;
|
||||
extern NSString * const kPOPShapeLayerStrokeColor;
|
||||
extern NSString * const kPOPShapeLayerFillColor;
|
||||
|
||||
/**
|
||||
Common NSLayoutConstraint property names.
|
||||
*/
|
||||
extern NSString * const kPOPLayoutConstraintConstant;
|
||||
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
|
||||
/**
|
||||
Common UIView property names.
|
||||
*/
|
||||
extern NSString * const kPOPViewAlpha;
|
||||
extern NSString * const kPOPViewBackgroundColor;
|
||||
extern NSString * const kPOPViewBounds;
|
||||
extern NSString * const kPOPViewCenter;
|
||||
extern NSString * const kPOPViewFrame;
|
||||
extern NSString * const kPOPViewScaleX;
|
||||
extern NSString * const kPOPViewScaleXY;
|
||||
extern NSString * const kPOPViewScaleY;
|
||||
extern NSString * const kPOPViewSize;
|
||||
extern NSString * const kPOPViewTintColor;
|
||||
|
||||
/**
|
||||
Common UIScrollView property names.
|
||||
*/
|
||||
extern NSString * const kPOPScrollViewContentOffset;
|
||||
extern NSString * const kPOPScrollViewContentSize;
|
||||
extern NSString * const kPOPScrollViewZoomScale;
|
||||
extern NSString * const kPOPScrollViewContentInset;
|
||||
|
||||
/**
|
||||
Common UITableView property names.
|
||||
*/
|
||||
extern NSString * const kPOPTableViewContentOffset;
|
||||
extern NSString * const kPOPTableViewContentSize;
|
||||
|
||||
/**
|
||||
Common UICollectionView property names.
|
||||
*/
|
||||
extern NSString * const kPOPCollectionViewContentOffset;
|
||||
extern NSString * const kPOPCollectionViewContentSize;
|
||||
|
||||
/**
|
||||
Common UINavigationBar property names.
|
||||
*/
|
||||
extern NSString * const kPOPNavigationBarBarTintColor;
|
||||
|
||||
/**
|
||||
Common UIToolbar property names.
|
||||
*/
|
||||
extern NSString * const kPOPToolbarBarTintColor;
|
||||
|
||||
/**
|
||||
Common UITabBar property names.
|
||||
*/
|
||||
extern NSString * const kPOPTabBarBarTintColor;
|
||||
|
||||
/**
|
||||
Common UILabel property names.
|
||||
*/
|
||||
extern NSString * const kPOPLabelTextColor;
|
||||
|
||||
#endif
|
||||
+849
@@ -0,0 +1,849 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPAnimatableProperty.h"
|
||||
#import "POPCGUtils.h"
|
||||
#import "POPAnimationRuntime.h"
|
||||
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
|
||||
#import <pop/POPLayerExtras.h>
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
#import <UIKit/UIKit.h>
|
||||
#else
|
||||
#import <AppKit/NSLayoutConstraint.h>
|
||||
#endif
|
||||
|
||||
// common threshold definitions
|
||||
static CGFloat const kPOPThresholdColor = 0.01;
|
||||
static CGFloat const kPOPThresholdPoint = 1.0;
|
||||
static CGFloat const kPOPThresholdOpacity = 0.01;
|
||||
static CGFloat const kPOPThresholdScale = 0.005;
|
||||
static CGFloat const kPOPThresholdRotation = 0.01;
|
||||
static CGFloat const kPOPThresholdRadius = 0.01;
|
||||
|
||||
#pragma mark - Static
|
||||
|
||||
// CALayer
|
||||
NSString * const kPOPLayerBackgroundColor = @"backgroundColor";
|
||||
NSString * const kPOPLayerBounds = @"bounds";
|
||||
NSString * const kPOPLayerCornerRadius = @"cornerRadius";
|
||||
NSString * const kPOPLayerBorderWidth = @"borderWidth";
|
||||
NSString * const kPOPLayerBorderColor = @"borderColor";
|
||||
NSString * const kPOPLayerOpacity = @"opacity";
|
||||
NSString * const kPOPLayerPosition = @"position";
|
||||
NSString * const kPOPLayerPositionX = @"positionX";
|
||||
NSString * const kPOPLayerPositionY = @"positionY";
|
||||
NSString * const kPOPLayerRotation = @"rotation";
|
||||
NSString * const kPOPLayerRotationX = @"rotationX";
|
||||
NSString * const kPOPLayerRotationY = @"rotationY";
|
||||
NSString * const kPOPLayerScaleX = @"scaleX";
|
||||
NSString * const kPOPLayerScaleXY = @"scaleXY";
|
||||
NSString * const kPOPLayerScaleY = @"scaleY";
|
||||
NSString * const kPOPLayerSize = @"size";
|
||||
NSString * const kPOPLayerSubscaleXY = @"subscaleXY";
|
||||
NSString * const kPOPLayerSubtranslationX = @"subtranslationX";
|
||||
NSString * const kPOPLayerSubtranslationXY = @"subtranslationXY";
|
||||
NSString * const kPOPLayerSubtranslationY = @"subtranslationY";
|
||||
NSString * const kPOPLayerSubtranslationZ = @"subtranslationZ";
|
||||
NSString * const kPOPLayerTranslationX = @"translationX";
|
||||
NSString * const kPOPLayerTranslationXY = @"translationXY";
|
||||
NSString * const kPOPLayerTranslationY = @"translationY";
|
||||
NSString * const kPOPLayerTranslationZ = @"translationZ";
|
||||
NSString * const kPOPLayerZPosition = @"zPosition";
|
||||
NSString * const kPOPLayerShadowColor = @"shadowColor";
|
||||
NSString * const kPOPLayerShadowOffset = @"shadowOffset";
|
||||
NSString * const kPOPLayerShadowOpacity = @"shadowOpacity";
|
||||
NSString * const kPOPLayerShadowRadius = @"shadowRadius";
|
||||
|
||||
// CAShapeLayer
|
||||
NSString * const kPOPShapeLayerStrokeStart = @"shapeLayer.strokeStart";
|
||||
NSString * const kPOPShapeLayerStrokeEnd = @"shapeLayer.strokeEnd";
|
||||
NSString * const kPOPShapeLayerStrokeColor = @"shapeLayer.strokeColor";
|
||||
NSString * const kPOPShapeLayerFillColor = @"shapeLayer.fillColor";
|
||||
|
||||
// NSLayoutConstraint
|
||||
NSString * const kPOPLayoutConstraintConstant = @"layoutConstraint.constant";
|
||||
|
||||
// UIView
|
||||
NSString * const kPOPViewAlpha = @"view.alpha";
|
||||
NSString * const kPOPViewBackgroundColor = @"view.backgroundColor";
|
||||
NSString * const kPOPViewBounds = kPOPLayerBounds;
|
||||
NSString * const kPOPViewCenter = @"view.center";
|
||||
NSString * const kPOPViewFrame = @"view.frame";
|
||||
NSString * const kPOPViewScaleX = @"view.scaleX";
|
||||
NSString * const kPOPViewScaleXY = @"view.scaleXY";
|
||||
NSString * const kPOPViewScaleY = @"view.scaleY";
|
||||
NSString * const kPOPViewSize = kPOPLayerSize;
|
||||
NSString * const kPOPViewTintColor = @"view.tintColor";
|
||||
|
||||
// UIScrollView
|
||||
NSString * const kPOPScrollViewContentOffset = @"scrollView.contentOffset";
|
||||
NSString * const kPOPScrollViewContentSize = @"scrollView.contentSize";
|
||||
NSString * const kPOPScrollViewZoomScale = @"scrollView.zoomScale";
|
||||
NSString * const kPOPScrollViewContentInset = @"scrollView.contentInset";
|
||||
|
||||
// UITableView
|
||||
NSString * const kPOPTableViewContentOffset = kPOPScrollViewContentOffset;
|
||||
NSString * const kPOPTableViewContentSize = kPOPScrollViewContentSize;
|
||||
|
||||
// UICollectionView
|
||||
NSString * const kPOPCollectionViewContentOffset = kPOPScrollViewContentOffset;
|
||||
NSString * const kPOPCollectionViewContentSize = kPOPScrollViewContentSize;
|
||||
|
||||
// UINavigationBar
|
||||
NSString * const kPOPNavigationBarBarTintColor = @"navigationBar.barTintColor";
|
||||
|
||||
// UIToolbar
|
||||
NSString * const kPOPToolbarBarTintColor = kPOPNavigationBarBarTintColor;
|
||||
|
||||
// UITabBar
|
||||
NSString * const kPOPTabBarBarTintColor = kPOPNavigationBarBarTintColor;
|
||||
|
||||
//UILabel
|
||||
NSString * const kPOPLabelTextColor = @"label.textColor";
|
||||
|
||||
/**
|
||||
State structure internal to static animatable property.
|
||||
*/
|
||||
typedef struct
|
||||
{
|
||||
NSString *name;
|
||||
pop_animatable_read_block readBlock;
|
||||
pop_animatable_write_block writeBlock;
|
||||
CGFloat threshold;
|
||||
} _POPStaticAnimatablePropertyState;
|
||||
typedef _POPStaticAnimatablePropertyState POPStaticAnimatablePropertyState;
|
||||
|
||||
static POPStaticAnimatablePropertyState _staticStates[] =
|
||||
{
|
||||
/* CALayer */
|
||||
|
||||
{kPOPLayerBackgroundColor,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
POPCGColorGetRGBAComponents(obj.backgroundColor, values);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
CGColorRef color = POPCGColorRGBACreate(values);
|
||||
[obj setBackgroundColor:color];
|
||||
CGColorRelease(color);
|
||||
},
|
||||
kPOPThresholdColor
|
||||
},
|
||||
|
||||
{kPOPLayerBounds,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values_from_rect(values, [obj bounds]);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
[obj setBounds:values_to_rect(values)];
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerCornerRadius,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = [obj cornerRadius];
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
[obj setCornerRadius:values[0]];
|
||||
},
|
||||
kPOPThresholdRadius
|
||||
},
|
||||
|
||||
{kPOPLayerBorderWidth,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = [obj borderWidth];
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
[obj setBorderWidth:values[0]];
|
||||
},
|
||||
0.01
|
||||
},
|
||||
|
||||
{kPOPLayerBorderColor,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
POPCGColorGetRGBAComponents(obj.borderColor, values);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
CGColorRef color = POPCGColorRGBACreate(values);
|
||||
[obj setBorderColor:color];
|
||||
CGColorRelease(color);
|
||||
},
|
||||
kPOPThresholdColor
|
||||
},
|
||||
|
||||
{kPOPLayerPosition,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values_from_point(values, [(CALayer *)obj position]);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
[obj setPosition:values_to_point(values)];
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerPositionX,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = [(CALayer *)obj position].x;
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
CGPoint p = [(CALayer *)obj position];
|
||||
p.x = values[0];
|
||||
[obj setPosition:p];
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerPositionY,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = [(CALayer *)obj position].y;
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
CGPoint p = [(CALayer *)obj position];
|
||||
p.y = values[0];
|
||||
[obj setPosition:p];
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerOpacity,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = [obj opacity];
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
[obj setOpacity:((float)values[0])];
|
||||
},
|
||||
kPOPThresholdOpacity
|
||||
},
|
||||
|
||||
{kPOPLayerScaleX,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetScaleX(obj);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetScaleX(obj, values[0]);
|
||||
},
|
||||
kPOPThresholdScale
|
||||
},
|
||||
|
||||
{kPOPLayerScaleY,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetScaleY(obj);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetScaleY(obj, values[0]);
|
||||
},
|
||||
kPOPThresholdScale
|
||||
},
|
||||
|
||||
{kPOPLayerScaleXY,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values_from_point(values, POPLayerGetScaleXY(obj));
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetScaleXY(obj, values_to_point(values));
|
||||
},
|
||||
kPOPThresholdScale
|
||||
},
|
||||
|
||||
{kPOPLayerSubscaleXY,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values_from_point(values, POPLayerGetSubScaleXY(obj));
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetSubScaleXY(obj, values_to_point(values));
|
||||
},
|
||||
kPOPThresholdScale
|
||||
},
|
||||
|
||||
{kPOPLayerTranslationX,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetTranslationX(obj);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetTranslationX(obj, values[0]);
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerTranslationY,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetTranslationY(obj);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetTranslationY(obj, values[0]);
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerTranslationZ,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetTranslationZ(obj);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetTranslationZ(obj, values[0]);
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerTranslationXY,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values_from_point(values, POPLayerGetTranslationXY(obj));
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetTranslationXY(obj, values_to_point(values));
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerSubtranslationX,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetSubTranslationX(obj);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetSubTranslationX(obj, values[0]);
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerSubtranslationY,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetSubTranslationY(obj);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetSubTranslationY(obj, values[0]);
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerSubtranslationZ,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetSubTranslationZ(obj);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetSubTranslationZ(obj, values[0]);
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerSubtranslationXY,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values_from_point(values, POPLayerGetSubTranslationXY(obj));
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetSubTranslationXY(obj, values_to_point(values));
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerZPosition,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = [obj zPosition];
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
[obj setZPosition:values[0]];
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerSize,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values_from_size(values, [obj bounds].size);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
CGSize size = values_to_size(values);
|
||||
if (size.width < 0. || size.height < 0.)
|
||||
return;
|
||||
|
||||
CGRect b = [obj bounds];
|
||||
b.size = size;
|
||||
[obj setBounds:b];
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPLayerRotation,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetRotation(obj);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetRotation(obj, values[0]);
|
||||
},
|
||||
kPOPThresholdRotation
|
||||
},
|
||||
|
||||
{kPOPLayerRotationY,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetRotationY(obj);
|
||||
},
|
||||
^(id obj, const CGFloat values[]) {
|
||||
POPLayerSetRotationY(obj, values[0]);
|
||||
},
|
||||
kPOPThresholdRotation
|
||||
},
|
||||
|
||||
{kPOPLayerRotationX,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetRotationX(obj);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
POPLayerSetRotationX(obj, values[0]);
|
||||
},
|
||||
kPOPThresholdRotation
|
||||
},
|
||||
|
||||
{kPOPLayerShadowColor,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
POPCGColorGetRGBAComponents(obj.shadowColor, values);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
CGColorRef color = POPCGColorRGBACreate(values);
|
||||
[obj setShadowColor:color];
|
||||
CGColorRelease(color);
|
||||
},
|
||||
0.01
|
||||
},
|
||||
|
||||
{kPOPLayerShadowOffset,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values_from_size(values, [obj shadowOffset]);
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
CGSize size = values_to_size(values);
|
||||
[obj setShadowOffset:size];
|
||||
},
|
||||
0.01
|
||||
},
|
||||
|
||||
{kPOPLayerShadowOpacity,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = [obj shadowOpacity];
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
[obj setShadowOpacity:values[0]];
|
||||
},
|
||||
kPOPThresholdOpacity
|
||||
},
|
||||
|
||||
{kPOPLayerShadowRadius,
|
||||
^(CALayer *obj, CGFloat values[]) {
|
||||
values[0] = [obj shadowRadius];
|
||||
},
|
||||
^(CALayer *obj, const CGFloat values[]) {
|
||||
[obj setShadowRadius:values[0]];
|
||||
},
|
||||
kPOPThresholdRadius
|
||||
},
|
||||
|
||||
/* CAShapeLayer */
|
||||
|
||||
{kPOPShapeLayerStrokeStart,
|
||||
^(CAShapeLayer *obj, CGFloat values[]) {
|
||||
values[0] = obj.strokeStart;
|
||||
},
|
||||
^(CAShapeLayer *obj, const CGFloat values[]) {
|
||||
obj.strokeStart = values[0];
|
||||
},
|
||||
0.01
|
||||
},
|
||||
|
||||
{kPOPShapeLayerStrokeEnd,
|
||||
^(CAShapeLayer *obj, CGFloat values[]) {
|
||||
values[0] = obj.strokeEnd;
|
||||
},
|
||||
^(CAShapeLayer *obj, const CGFloat values[]) {
|
||||
obj.strokeEnd = values[0];
|
||||
},
|
||||
0.01
|
||||
},
|
||||
|
||||
{kPOPShapeLayerStrokeColor,
|
||||
^(CAShapeLayer *obj, CGFloat values[]) {
|
||||
POPCGColorGetRGBAComponents(obj.strokeColor, values);
|
||||
},
|
||||
^(CAShapeLayer *obj, const CGFloat values[]) {
|
||||
CGColorRef color = POPCGColorRGBACreate(values);
|
||||
[obj setStrokeColor:color];
|
||||
CGColorRelease(color);
|
||||
},
|
||||
kPOPThresholdColor
|
||||
},
|
||||
|
||||
{kPOPShapeLayerFillColor,
|
||||
^(CAShapeLayer *obj, CGFloat values[]) {
|
||||
POPCGColorGetRGBAComponents(obj.fillColor, values);
|
||||
},
|
||||
^(CAShapeLayer *obj, const CGFloat values[]) {
|
||||
CGColorRef color = POPCGColorRGBACreate(values);
|
||||
[obj setFillColor:color];
|
||||
CGColorRelease(color);
|
||||
},
|
||||
kPOPThresholdColor
|
||||
},
|
||||
|
||||
{kPOPLayoutConstraintConstant,
|
||||
^(NSLayoutConstraint *obj, CGFloat values[]) {
|
||||
values[0] = obj.constant;
|
||||
},
|
||||
^(NSLayoutConstraint *obj, const CGFloat values[]) {
|
||||
obj.constant = values[0];
|
||||
},
|
||||
0.01
|
||||
},
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
|
||||
/* UIView */
|
||||
|
||||
{kPOPViewAlpha,
|
||||
^(UIView *obj, CGFloat values[]) {
|
||||
values[0] = obj.alpha;
|
||||
},
|
||||
^(UIView *obj, const CGFloat values[]) {
|
||||
obj.alpha = values[0];
|
||||
},
|
||||
kPOPThresholdOpacity
|
||||
},
|
||||
|
||||
{kPOPViewBackgroundColor,
|
||||
^(UIView *obj, CGFloat values[]) {
|
||||
POPUIColorGetRGBAComponents(obj.backgroundColor, values);
|
||||
},
|
||||
^(UIView *obj, const CGFloat values[]) {
|
||||
obj.backgroundColor = POPUIColorRGBACreate(values);
|
||||
},
|
||||
kPOPThresholdColor
|
||||
},
|
||||
|
||||
{kPOPViewCenter,
|
||||
^(UIView *obj, CGFloat values[]) {
|
||||
values_from_point(values, obj.center);
|
||||
},
|
||||
^(UIView *obj, const CGFloat values[]) {
|
||||
obj.center = values_to_point(values);
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPViewFrame,
|
||||
^(UIView *obj, CGFloat values[]) {
|
||||
values_from_rect(values, obj.frame);
|
||||
},
|
||||
^(UIView *obj, const CGFloat values[]) {
|
||||
obj.frame = values_to_rect(values);
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPViewScaleX,
|
||||
^(UIView *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetScaleX(obj.layer);
|
||||
},
|
||||
^(UIView *obj, const CGFloat values[]) {
|
||||
POPLayerSetScaleX(obj.layer, values[0]);
|
||||
},
|
||||
kPOPThresholdScale
|
||||
},
|
||||
|
||||
{kPOPViewScaleY,
|
||||
^(UIView *obj, CGFloat values[]) {
|
||||
values[0] = POPLayerGetScaleY(obj.layer);
|
||||
},
|
||||
^(UIView *obj, const CGFloat values[]) {
|
||||
POPLayerSetScaleY(obj.layer, values[0]);
|
||||
},
|
||||
kPOPThresholdScale
|
||||
},
|
||||
|
||||
{kPOPViewScaleXY,
|
||||
^(UIView *obj, CGFloat values[]) {
|
||||
values_from_point(values, POPLayerGetScaleXY(obj.layer));
|
||||
},
|
||||
^(UIView *obj, const CGFloat values[]) {
|
||||
POPLayerSetScaleXY(obj.layer, values_to_point(values));
|
||||
},
|
||||
kPOPThresholdScale
|
||||
},
|
||||
|
||||
{kPOPViewTintColor,
|
||||
^(UIView *obj, CGFloat values[]) {
|
||||
POPUIColorGetRGBAComponents(obj.tintColor, values);
|
||||
},
|
||||
^(UIView *obj, const CGFloat values[]) {
|
||||
obj.tintColor = POPUIColorRGBACreate(values);
|
||||
},
|
||||
kPOPThresholdColor
|
||||
},
|
||||
|
||||
/* UIScrollView */
|
||||
|
||||
{kPOPScrollViewContentOffset,
|
||||
^(UIScrollView *obj, CGFloat values[]) {
|
||||
values_from_point(values, obj.contentOffset);
|
||||
},
|
||||
^(UIScrollView *obj, const CGFloat values[]) {
|
||||
[obj setContentOffset:values_to_point(values) animated:NO];
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPScrollViewContentSize,
|
||||
^(UIScrollView *obj, CGFloat values[]) {
|
||||
values_from_size(values, obj.contentSize);
|
||||
},
|
||||
^(UIScrollView *obj, const CGFloat values[]) {
|
||||
obj.contentSize = values_to_size(values);
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
{kPOPScrollViewZoomScale,
|
||||
^(UIScrollView *obj, CGFloat values[]) {
|
||||
values[0]=obj.zoomScale;
|
||||
},
|
||||
^(UIScrollView *obj, const CGFloat values[]) {
|
||||
obj.zoomScale=values[0];
|
||||
},
|
||||
kPOPThresholdScale
|
||||
},
|
||||
|
||||
{kPOPScrollViewContentInset,
|
||||
^(UIScrollView *obj, CGFloat values[]) {
|
||||
values[0] = obj.contentInset.top;
|
||||
values[1] = obj.contentInset.left;
|
||||
values[2] = obj.contentInset.bottom;
|
||||
values[3] = obj.contentInset.right;
|
||||
},
|
||||
^(UIScrollView *obj, const CGFloat values[]) {
|
||||
obj.contentInset = values_to_edge_insets(values);
|
||||
},
|
||||
kPOPThresholdPoint
|
||||
},
|
||||
|
||||
/* UINavigationBar */
|
||||
|
||||
{kPOPNavigationBarBarTintColor,
|
||||
^(UINavigationBar *obj, CGFloat values[]) {
|
||||
POPUIColorGetRGBAComponents(obj.barTintColor, values);
|
||||
},
|
||||
^(UINavigationBar *obj, const CGFloat values[]) {
|
||||
obj.barTintColor = POPUIColorRGBACreate(values);
|
||||
},
|
||||
kPOPThresholdColor
|
||||
},
|
||||
|
||||
/* UILabel */
|
||||
|
||||
{kPOPLabelTextColor,
|
||||
^(UILabel *obj, CGFloat values[]) {
|
||||
POPUIColorGetRGBAComponents(obj.textColor, values);
|
||||
},
|
||||
^(UILabel *obj, const CGFloat values[]) {
|
||||
obj.textColor = POPUIColorRGBACreate(values);
|
||||
},
|
||||
kPOPThresholdColor
|
||||
},
|
||||
|
||||
#endif
|
||||
|
||||
};
|
||||
|
||||
static NSUInteger staticIndexWithName(NSString *aName)
|
||||
{
|
||||
NSUInteger idx = 0;
|
||||
|
||||
while (idx < POP_ARRAY_COUNT(_staticStates)) {
|
||||
if ([_staticStates[idx].name isEqualToString:aName])
|
||||
return idx;
|
||||
idx++;
|
||||
}
|
||||
|
||||
return NSNotFound;
|
||||
}
|
||||
|
||||
/**
|
||||
Concrete static property class.
|
||||
*/
|
||||
@interface POPStaticAnimatableProperty : POPAnimatableProperty
|
||||
{
|
||||
@public
|
||||
POPStaticAnimatablePropertyState *_state;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation POPStaticAnimatableProperty
|
||||
|
||||
- (NSString *)name
|
||||
{
|
||||
return _state->name;
|
||||
}
|
||||
|
||||
- (pop_animatable_read_block)readBlock
|
||||
{
|
||||
return _state->readBlock;
|
||||
}
|
||||
|
||||
- (pop_animatable_write_block)writeBlock
|
||||
{
|
||||
return _state->writeBlock;
|
||||
}
|
||||
|
||||
- (CGFloat)threshold
|
||||
{
|
||||
return _state->threshold;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark - Concrete
|
||||
|
||||
/**
|
||||
Concrete immutable property class.
|
||||
*/
|
||||
@interface POPConcreteAnimatableProperty : POPAnimatableProperty
|
||||
- (instancetype)initWithName:(NSString *)name readBlock:(pop_animatable_read_block)read writeBlock:(pop_animatable_write_block)write threshold:(CGFloat)threshold;
|
||||
@end
|
||||
|
||||
@implementation POPConcreteAnimatableProperty
|
||||
|
||||
// default synthesis
|
||||
@synthesize name, readBlock, writeBlock, threshold;
|
||||
|
||||
- (instancetype)initWithName:(NSString *)aName readBlock:(pop_animatable_read_block)aReadBlock writeBlock:(pop_animatable_write_block)aWriteBlock threshold:(CGFloat)aThreshold
|
||||
{
|
||||
self = [super init];
|
||||
if (nil != self) {
|
||||
name = [aName copy];
|
||||
readBlock = [aReadBlock copy];
|
||||
writeBlock = [aWriteBlock copy];
|
||||
threshold = aThreshold;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@end
|
||||
|
||||
#pragma mark - Mutable
|
||||
|
||||
@implementation POPMutableAnimatableProperty
|
||||
|
||||
// default synthesis
|
||||
@synthesize name, readBlock, writeBlock, threshold;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark - Cluster
|
||||
|
||||
/**
|
||||
Singleton placeholder property class to support class cluster.
|
||||
*/
|
||||
@interface POPPlaceholderAnimatableProperty : POPAnimatableProperty
|
||||
|
||||
@end
|
||||
|
||||
@implementation POPPlaceholderAnimatableProperty
|
||||
|
||||
// default synthesis
|
||||
@synthesize name, readBlock, writeBlock, threshold;
|
||||
|
||||
@end
|
||||
|
||||
/**
|
||||
Cluster class.
|
||||
*/
|
||||
@implementation POPAnimatableProperty
|
||||
|
||||
// avoid creating backing ivars
|
||||
@dynamic name, readBlock, writeBlock, threshold;
|
||||
|
||||
static POPAnimatableProperty *placeholder = nil;
|
||||
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self == [POPAnimatableProperty class]) {
|
||||
placeholder = [POPPlaceholderAnimatableProperty alloc];
|
||||
}
|
||||
}
|
||||
|
||||
+ (id)allocWithZone:(struct _NSZone *)zone
|
||||
{
|
||||
if (self == [POPAnimatableProperty class]) {
|
||||
if (nil == placeholder) {
|
||||
placeholder = [super allocWithZone:zone];
|
||||
}
|
||||
return placeholder;
|
||||
}
|
||||
return [super allocWithZone:zone];
|
||||
}
|
||||
|
||||
- (id)copyWithZone:(NSZone *)zone
|
||||
{
|
||||
if ([self isKindOfClass:[POPMutableAnimatableProperty class]]) {
|
||||
POPConcreteAnimatableProperty *copyProperty = [[POPConcreteAnimatableProperty alloc] initWithName:self.name readBlock:self.readBlock writeBlock:self.writeBlock threshold:self.threshold];
|
||||
return copyProperty;
|
||||
} else {
|
||||
return self;
|
||||
}
|
||||
}
|
||||
|
||||
- (id)mutableCopyWithZone:(NSZone *)zone
|
||||
{
|
||||
POPMutableAnimatableProperty *copyProperty = [[POPMutableAnimatableProperty alloc] init];
|
||||
copyProperty.name = self.name;
|
||||
copyProperty.readBlock = self.readBlock;
|
||||
copyProperty.writeBlock = self.writeBlock;
|
||||
copyProperty.threshold = self.threshold;
|
||||
return copyProperty;
|
||||
}
|
||||
|
||||
+ (id)propertyWithName:(NSString *)aName
|
||||
{
|
||||
return [self propertyWithName:aName initializer:NULL];
|
||||
}
|
||||
|
||||
+ (id)propertyWithName:(NSString *)aName initializer:(void (^)(POPMutableAnimatableProperty *prop))aBlock
|
||||
{
|
||||
POPAnimatableProperty *prop = nil;
|
||||
|
||||
static NSMutableDictionary *_propertyDict = nil;
|
||||
if (nil == _propertyDict) {
|
||||
_propertyDict = [[NSMutableDictionary alloc] initWithCapacity:10];
|
||||
}
|
||||
|
||||
prop = _propertyDict[aName];
|
||||
if (nil != prop) {
|
||||
return prop;
|
||||
}
|
||||
|
||||
NSUInteger staticIdx = staticIndexWithName(aName);
|
||||
|
||||
if (NSNotFound != staticIdx) {
|
||||
POPStaticAnimatableProperty *staticProp = [[POPStaticAnimatableProperty alloc] init];
|
||||
staticProp->_state = &_staticStates[staticIdx];
|
||||
_propertyDict[aName] = staticProp;
|
||||
prop = staticProp;
|
||||
} else if (NULL != aBlock) {
|
||||
POPMutableAnimatableProperty *mutableProp = [[POPMutableAnimatableProperty alloc] init];
|
||||
mutableProp.name = aName;
|
||||
mutableProp.threshold = 1.0;
|
||||
aBlock(mutableProp);
|
||||
prop = [mutableProp copy];
|
||||
}
|
||||
|
||||
return prop;
|
||||
}
|
||||
|
||||
- (NSString *)description
|
||||
{
|
||||
NSMutableString *s = [NSMutableString stringWithFormat:@"%@ name:%@ threshold:%f", super.description, self.name, self.threshold];
|
||||
return s;
|
||||
}
|
||||
|
||||
@end
|
||||
Generated
+162
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <Foundation/NSObject.h>
|
||||
|
||||
#import <pop/POPAnimationTracer.h>
|
||||
#import <pop/POPGeometry.h>
|
||||
|
||||
@class CAMediaTimingFunction;
|
||||
|
||||
/**
|
||||
@abstract The abstract animation base class.
|
||||
@discussion Instantiate and use one of the concrete animation subclasses.
|
||||
*/
|
||||
@interface POPAnimation : NSObject
|
||||
|
||||
/**
|
||||
@abstract The name of the animation.
|
||||
@discussion Optional property to help identify the animation.
|
||||
*/
|
||||
@property (copy, nonatomic) NSString *name;
|
||||
|
||||
/**
|
||||
@abstract The beginTime of the animation in media time.
|
||||
@discussion Defaults to 0 and starts immediately.
|
||||
*/
|
||||
@property (assign, nonatomic) CFTimeInterval beginTime;
|
||||
|
||||
/**
|
||||
@abstract The animation delegate.
|
||||
@discussion See {@ref POPAnimationDelegate} for details.
|
||||
*/
|
||||
@property (weak, nonatomic) id delegate;
|
||||
|
||||
/**
|
||||
@abstract The animation tracer.
|
||||
@discussion Returns the existing tracer, creating one if needed. Call start/stop on the tracer to toggle event collection.
|
||||
*/
|
||||
@property (readonly, nonatomic) POPAnimationTracer *tracer;
|
||||
|
||||
/**
|
||||
@abstract Optional block called on animation completion.
|
||||
*/
|
||||
@property (copy, nonatomic) void (^completionBlock)(POPAnimation *anim, BOOL finished);
|
||||
|
||||
/**
|
||||
@abstract Flag indicating whether animation should be removed on completion.
|
||||
@discussion Setting to NO can facilitate animation reuse. Defaults to YES.
|
||||
*/
|
||||
@property (assign, nonatomic) BOOL removedOnCompletion;
|
||||
|
||||
/**
|
||||
@abstract Flag indicating whether animation is paused.
|
||||
@discussion A paused animation is excluded from the list of active animations. On initial creation, defaults to YES. On animation addition, the animation is implicity unpaused. On animation completion, the animation is implicity paused including for animations with removedOnCompletion set to NO.
|
||||
*/
|
||||
@property (assign, nonatomic, getter = isPaused) BOOL paused;
|
||||
|
||||
/**
|
||||
@abstract Flag indicating whether animation autoreverses.
|
||||
@discussion An animation that autoreverses will have twice the duration before it is considered finished. It will animate to the toValue, stop, then animate back to the original fromValue. The delegate methods are called as follows:
|
||||
|
||||
1) animationDidStart: is called at the beginning, as usual, and then after each toValue is reached and the autoreverse is going to start.
|
||||
2) animationDidReachToValue: is called every time the toValue is reached. The toValue is swapped with the fromValue at the end of each animation segment. This means that with autoreverses set to YES, the animationDidReachToValue: delegate method will be called a minimum of twice.
|
||||
3) animationDidStop:finished: is called every time the toValue is reached, the finished argument will be NO if the autoreverse is not yet complete.
|
||||
*/
|
||||
@property (assign, nonatomic) BOOL autoreverses;
|
||||
|
||||
/**
|
||||
@abstract The number of times to repeat the animation.
|
||||
@discussion A repeatCount of 0 or 1 means that the animation will not repeat, just like Core Animation. A repeatCount of 2 or greater means that the animation will run that many times before stopping. The delegate methods are called as follows:
|
||||
|
||||
1) animationDidStart: is called at the beginning of each animation repeat.
|
||||
2) animationDidReachToValue: is called every time the toValue is reached.
|
||||
3) animationDidStop:finished: is called every time the toValue is reached, the finished argument will be NO if the autoreverse is not yet complete.
|
||||
|
||||
When combined with the autoreverses property, a singular animation is effectively twice as long.
|
||||
*/
|
||||
@property (assign, nonatomic) NSInteger repeatCount;
|
||||
|
||||
/**
|
||||
@abstract Repeat the animation forever.
|
||||
@discussion This property will make the animation repeat forever. The value of the repeatCount property is undefined when this property is set. The finished parameter of the delegate callback animationDidStop:finished: will always be NO.
|
||||
*/
|
||||
@property (assign, nonatomic) BOOL repeatForever;
|
||||
|
||||
@end
|
||||
|
||||
/**
|
||||
@abstract The animation delegate.
|
||||
*/
|
||||
@protocol POPAnimationDelegate <NSObject>
|
||||
@optional
|
||||
|
||||
/**
|
||||
@abstract Called on animation start.
|
||||
@param anim The relevant animation.
|
||||
*/
|
||||
- (void)pop_animationDidStart:(POPAnimation *)anim;
|
||||
|
||||
/**
|
||||
@abstract Called when value meets or exceeds to value.
|
||||
@param anim The relevant animation.
|
||||
*/
|
||||
- (void)pop_animationDidReachToValue:(POPAnimation *)anim;
|
||||
|
||||
/**
|
||||
@abstract Called on animation stop.
|
||||
@param anim The relevant animation.
|
||||
@param finished Flag indicating finished state. Flag is true if the animation reached completion before being removed.
|
||||
*/
|
||||
- (void)pop_animationDidStop:(POPAnimation *)anim finished:(BOOL)finished;
|
||||
|
||||
/**
|
||||
@abstract Called each frame animation is applied.
|
||||
@param anim The relevant animation.
|
||||
*/
|
||||
- (void)pop_animationDidApply:(POPAnimation *)anim;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@interface NSObject (POP)
|
||||
|
||||
/**
|
||||
@abstract Add an animation to the reciver.
|
||||
@param anim The animation to add.
|
||||
@param key The key used to identify the animation.
|
||||
@discussion The 'key' may be any string such that only one animation per unique key is added per object.
|
||||
*/
|
||||
- (void)pop_addAnimation:(POPAnimation *)anim forKey:(NSString *)key;
|
||||
|
||||
/**
|
||||
@abstract Remove all animations attached to the receiver.
|
||||
*/
|
||||
- (void)pop_removeAllAnimations;
|
||||
|
||||
/**
|
||||
@abstract Remove any animation attached to the receiver for 'key'.
|
||||
@param key The key used to identify the animation.
|
||||
*/
|
||||
- (void)pop_removeAnimationForKey:(NSString *)key;
|
||||
|
||||
/**
|
||||
@abstract Returns an array containing the keys of all animations currently attached to the receiver.
|
||||
@param The order of keys reflects the order in which animations will be applied.
|
||||
*/
|
||||
- (NSArray *)pop_animationKeys;
|
||||
|
||||
/**
|
||||
@abstract Returns any animation attached to the receiver.
|
||||
@param key The key used to identify the animation.
|
||||
@returns The animation currently attached, or nil if no such animation exists.
|
||||
*/
|
||||
- (id)pop_animationForKey:(NSString *)key;
|
||||
|
||||
@end
|
||||
Generated
+269
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPAnimationInternal.h"
|
||||
#import "POPAnimationTracerInternal.h"
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#import "POPAnimationExtras.h"
|
||||
#import "POPAnimationRuntime.h"
|
||||
#import "POPAnimatorPrivate.h"
|
||||
#import "POPAction.h"
|
||||
|
||||
using namespace POP;
|
||||
|
||||
#pragma mark - POPAnimation
|
||||
|
||||
@implementation POPAnimation
|
||||
@synthesize solver = _solver;
|
||||
@synthesize currentValue = _currentValue;
|
||||
@synthesize progressMarkers = _progressMarkers;
|
||||
|
||||
#pragma mark - Lifecycle
|
||||
|
||||
- (id)init
|
||||
{
|
||||
[NSException raise:NSStringFromClass([self class]) format:@"Attempting to instantiate an abstract class. Use a concrete subclass instead."];
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (id)_init
|
||||
{
|
||||
self = [super init];
|
||||
if (nil != self) {
|
||||
[self _initState];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)_initState
|
||||
{
|
||||
_state = new POPAnimationState(self);
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
if (_state) {
|
||||
delete _state;
|
||||
_state = NULL;
|
||||
};
|
||||
}
|
||||
|
||||
#pragma mark - Properties
|
||||
|
||||
- (id)delegate
|
||||
{
|
||||
return _state->delegate;
|
||||
}
|
||||
|
||||
- (void)setDelegate:(id)delegate
|
||||
{
|
||||
_state->setDelegate(delegate);
|
||||
}
|
||||
|
||||
- (BOOL)isPaused
|
||||
{
|
||||
return _state->paused;
|
||||
}
|
||||
|
||||
- (void)setPaused:(BOOL)paused
|
||||
{
|
||||
_state->setPaused(paused ? true : false);
|
||||
}
|
||||
|
||||
- (NSInteger)repeatCount
|
||||
{
|
||||
if (_state->autoreverses) {
|
||||
return _state->repeatCount / 2;
|
||||
} else {
|
||||
return _state->repeatCount;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setRepeatCount:(NSInteger)repeatCount
|
||||
{
|
||||
if (repeatCount > 0) {
|
||||
if (repeatCount > NSIntegerMax / 2) {
|
||||
repeatCount = NSIntegerMax / 2;
|
||||
}
|
||||
|
||||
if (_state->autoreverses) {
|
||||
_state->repeatCount = (repeatCount * 2);
|
||||
} else {
|
||||
_state->repeatCount = repeatCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)autoreverses
|
||||
{
|
||||
return _state->autoreverses;
|
||||
}
|
||||
|
||||
- (void)setAutoreverses:(BOOL)autoreverses
|
||||
{
|
||||
_state->autoreverses = autoreverses;
|
||||
if (autoreverses) {
|
||||
if (_state->repeatCount == 0) {
|
||||
[self setRepeatCount:1];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
FB_PROPERTY_GET(POPAnimationState, type, POPAnimationType);
|
||||
DEFINE_RW_PROPERTY_OBJ_COPY(POPAnimationState, completionBlock, setCompletionBlock:, POPAnimationCompletionBlock);
|
||||
DEFINE_RW_PROPERTY_OBJ_COPY(POPAnimationState, name, setName:, NSString*);
|
||||
DEFINE_RW_PROPERTY(POPAnimationState, beginTime, setBeginTime:, CFTimeInterval);
|
||||
DEFINE_RW_FLAG(POPAnimationState, removedOnCompletion, removedOnCompletion, setRemovedOnCompletion:);
|
||||
DEFINE_RW_FLAG(POPAnimationState, repeatForever, repeatForever, setRepeatForever:);
|
||||
|
||||
- (id)valueForUndefinedKey:(NSString *)key
|
||||
{
|
||||
return _state->dict[key];
|
||||
}
|
||||
|
||||
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
|
||||
{
|
||||
if (!value) {
|
||||
[_state->dict removeObjectForKey:key];
|
||||
} else {
|
||||
if (!_state->dict)
|
||||
_state->dict = [[NSMutableDictionary alloc] init];
|
||||
_state->dict[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
- (POPAnimationTracer *)tracer
|
||||
{
|
||||
if (!_state->tracer) {
|
||||
_state->tracer = [[POPAnimationTracer alloc] initWithAnimation:self];
|
||||
}
|
||||
return _state->tracer;
|
||||
}
|
||||
|
||||
- (NSString *)description
|
||||
{
|
||||
NSMutableString *s = [NSMutableString stringWithFormat:@"<%@:%p", NSStringFromClass([self class]), self];
|
||||
[self _appendDescription:s debug:NO];
|
||||
[s appendString:@">"];
|
||||
return s;
|
||||
}
|
||||
|
||||
- (NSString *)debugDescription
|
||||
{
|
||||
NSMutableString *s = [NSMutableString stringWithFormat:@"<%@:%p", NSStringFromClass([self class]), self];
|
||||
[self _appendDescription:s debug:YES];
|
||||
[s appendString:@">"];
|
||||
return s;
|
||||
}
|
||||
|
||||
#pragma mark - Utility
|
||||
|
||||
POPAnimationState *POPAnimationGetState(POPAnimation *a)
|
||||
{
|
||||
return a->_state;
|
||||
}
|
||||
|
||||
- (BOOL)_advance:(id)object currentTime:(CFTimeInterval)currentTime elapsedTime:(CFTimeInterval)elapsedTime
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug
|
||||
{
|
||||
if (_state->name)
|
||||
[s appendFormat:@"; name = %@", _state->name];
|
||||
|
||||
if (!self.removedOnCompletion)
|
||||
[s appendFormat:@"; removedOnCompletion = %@", POPStringFromBOOL(self.removedOnCompletion)];
|
||||
|
||||
if (debug) {
|
||||
if (_state->active)
|
||||
[s appendFormat:@"; active = %@", POPStringFromBOOL(_state->active)];
|
||||
|
||||
if (_state->paused)
|
||||
[s appendFormat:@"; paused = %@", POPStringFromBOOL(_state->paused)];
|
||||
}
|
||||
|
||||
if (_state->beginTime) {
|
||||
[s appendFormat:@"; beginTime = %f", _state->beginTime];
|
||||
}
|
||||
|
||||
for (NSString *key in _state->dict) {
|
||||
[s appendFormat:@"; %@ = %@", key, _state->dict[key]];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
#pragma mark - POPPropertyAnimation
|
||||
|
||||
#pragma mark - POPBasicAnimation
|
||||
|
||||
#pragma mark - POPDecayAnimation
|
||||
|
||||
@implementation NSObject (POP)
|
||||
|
||||
- (void)pop_addAnimation:(POPAnimation *)anim forKey:(NSString *)key
|
||||
{
|
||||
[[POPAnimator sharedAnimator] addAnimation:anim forObject:self key:key];
|
||||
}
|
||||
|
||||
- (void)pop_removeAllAnimations
|
||||
{
|
||||
[[POPAnimator sharedAnimator] removeAllAnimationsForObject:self];
|
||||
}
|
||||
|
||||
- (void)pop_removeAnimationForKey:(NSString *)key
|
||||
{
|
||||
[[POPAnimator sharedAnimator] removeAnimationForObject:self key:key];
|
||||
}
|
||||
|
||||
- (NSArray *)pop_animationKeys
|
||||
{
|
||||
return [[POPAnimator sharedAnimator] animationKeysForObject:self];
|
||||
}
|
||||
|
||||
- (id)pop_animationForKey:(NSString *)key
|
||||
{
|
||||
return [[POPAnimator sharedAnimator] animationForObject:self key:key];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation NSProxy (POP)
|
||||
|
||||
- (void)pop_addAnimation:(POPAnimation *)anim forKey:(NSString *)key
|
||||
{
|
||||
[[POPAnimator sharedAnimator] addAnimation:anim forObject:self key:key];
|
||||
}
|
||||
|
||||
- (void)pop_removeAllAnimations
|
||||
{
|
||||
[[POPAnimator sharedAnimator] removeAllAnimationsForObject:self];
|
||||
}
|
||||
|
||||
- (void)pop_removeAnimationForKey:(NSString *)key
|
||||
{
|
||||
[[POPAnimator sharedAnimator] removeAnimationForObject:self key:key];
|
||||
}
|
||||
|
||||
- (NSArray *)pop_animationKeys
|
||||
{
|
||||
return [[POPAnimator sharedAnimator] animationKeysForObject:self];
|
||||
}
|
||||
|
||||
- (id)pop_animationForKey:(NSString *)key
|
||||
{
|
||||
return [[POPAnimator sharedAnimator] animationForObject:self key:key];
|
||||
}
|
||||
|
||||
@end
|
||||
Generated
+69
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
/**
|
||||
@abstract Enumeraton of animation event types.
|
||||
*/
|
||||
typedef NS_ENUM(NSUInteger, POPAnimationEventType) {
|
||||
kPOPAnimationEventPropertyRead = 0,
|
||||
kPOPAnimationEventPropertyWrite,
|
||||
kPOPAnimationEventToValueUpdate,
|
||||
kPOPAnimationEventFromValueUpdate,
|
||||
kPOPAnimationEventVelocityUpdate,
|
||||
kPOPAnimationEventBouncinessUpdate,
|
||||
kPOPAnimationEventSpeedUpdate,
|
||||
kPOPAnimationEventFrictionUpdate,
|
||||
kPOPAnimationEventMassUpdate,
|
||||
kPOPAnimationEventTensionUpdate,
|
||||
kPOPAnimationEventDidStart,
|
||||
kPOPAnimationEventDidStop,
|
||||
kPOPAnimationEventDidReachToValue,
|
||||
kPOPAnimationEventAutoreversed
|
||||
};
|
||||
|
||||
/**
|
||||
@abstract The base animation event class.
|
||||
*/
|
||||
@interface POPAnimationEvent : NSObject
|
||||
|
||||
/**
|
||||
@abstract The event type. See {@ref POPAnimationEventType} for possible values.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign) POPAnimationEventType type;
|
||||
|
||||
/**
|
||||
@abstract The time of event.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign) CFTimeInterval time;
|
||||
|
||||
/**
|
||||
@abstract Optional string describing the animation at time of event.
|
||||
*/
|
||||
@property (readonly, nonatomic, copy) NSString *animationDescription;
|
||||
|
||||
@end
|
||||
|
||||
/**
|
||||
@abstract An animation event subclass for recording value and velocity.
|
||||
*/
|
||||
@interface POPAnimationValueEvent : POPAnimationEvent
|
||||
|
||||
/**
|
||||
@abstract The value recorded.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) id value;
|
||||
|
||||
/**
|
||||
@abstract The velocity recorded, if any.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) id velocity;
|
||||
|
||||
@end
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPAnimationEvent.h"
|
||||
#import "POPAnimationEventInternal.h"
|
||||
|
||||
static NSString *stringFromType(POPAnimationEventType aType)
|
||||
{
|
||||
switch (aType) {
|
||||
case kPOPAnimationEventPropertyRead:
|
||||
return @"read";
|
||||
case kPOPAnimationEventPropertyWrite:
|
||||
return @"write";
|
||||
case kPOPAnimationEventToValueUpdate:
|
||||
return @"toValue";
|
||||
case kPOPAnimationEventFromValueUpdate:
|
||||
return @"fromValue";
|
||||
case kPOPAnimationEventVelocityUpdate:
|
||||
return @"velocity";
|
||||
case kPOPAnimationEventSpeedUpdate:
|
||||
return @"speed";
|
||||
case kPOPAnimationEventBouncinessUpdate:
|
||||
return @"bounciness";
|
||||
case kPOPAnimationEventFrictionUpdate:
|
||||
return @"friction";
|
||||
case kPOPAnimationEventMassUpdate:
|
||||
return @"mass";
|
||||
case kPOPAnimationEventTensionUpdate:
|
||||
return @"tension";
|
||||
case kPOPAnimationEventDidStart:
|
||||
return @"didStart";
|
||||
case kPOPAnimationEventDidStop:
|
||||
return @"didStop";
|
||||
case kPOPAnimationEventDidReachToValue:
|
||||
return @"didReachToValue";
|
||||
case kPOPAnimationEventAutoreversed:
|
||||
return @"autoreversed";
|
||||
default:
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
@implementation POPAnimationEvent
|
||||
@synthesize type = _type;
|
||||
@synthesize time = _time;
|
||||
@synthesize animationDescription = _animationDescription;
|
||||
|
||||
- (instancetype)initWithType:(POPAnimationEventType)aType time:(CFTimeInterval)aTime
|
||||
{
|
||||
self = [super init];
|
||||
if (nil != self) {
|
||||
_type = aType;
|
||||
_time = aTime;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (NSString *)description
|
||||
{
|
||||
NSMutableString *s = [NSMutableString stringWithFormat:@"<POPAnimationEvent:%f; type = %@", _time, stringFromType(_type)];
|
||||
[self _appendDescription:s];
|
||||
[s appendString:@">"];
|
||||
return s;
|
||||
}
|
||||
|
||||
// subclass override
|
||||
- (void)_appendDescription:(NSMutableString *)s
|
||||
{
|
||||
if (0 != _animationDescription.length) {
|
||||
[s appendFormat:@"; animation = %@", _animationDescription];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation POPAnimationValueEvent
|
||||
@synthesize value = _value;
|
||||
@synthesize velocity = _velocity;
|
||||
|
||||
- (instancetype)initWithType:(POPAnimationEventType)aType time:(CFTimeInterval)aTime value:(id)aValue
|
||||
{
|
||||
self = [self initWithType:aType time:aTime];
|
||||
if (nil != self) {
|
||||
_value = aValue;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)_appendDescription:(NSMutableString *)s
|
||||
{
|
||||
[super _appendDescription:s];
|
||||
|
||||
if (nil != _value) {
|
||||
[s appendFormat:@"; value = %@", _value];
|
||||
}
|
||||
|
||||
if (nil != _velocity) {
|
||||
[s appendFormat:@"; velocity = %@", _velocity];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "POPAnimationEvent.h"
|
||||
|
||||
@interface POPAnimationEvent ()
|
||||
|
||||
/**
|
||||
@abstract Default initializer.
|
||||
*/
|
||||
- (instancetype)initWithType:(POPAnimationEventType)type time:(CFTimeInterval)time;
|
||||
|
||||
/**
|
||||
@abstract Readwrite redefinition of public property.
|
||||
*/
|
||||
@property (readwrite, nonatomic, copy) NSString *animationDescription;
|
||||
|
||||
@end
|
||||
|
||||
@interface POPAnimationValueEvent ()
|
||||
|
||||
/**
|
||||
@abstract Default initializer.
|
||||
*/
|
||||
- (instancetype)initWithType:(POPAnimationEventType)type time:(CFTimeInterval)time value:(id)value;
|
||||
|
||||
/**
|
||||
@abstract Readwrite redefinition of public property.
|
||||
*/
|
||||
@property (readwrite, nonatomic, strong) id velocity;
|
||||
|
||||
@end
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <QuartzCore/CAAnimation.h>
|
||||
|
||||
#import <pop/POPDefines.h>
|
||||
#import <pop/POPSpringAnimation.h>
|
||||
|
||||
/**
|
||||
@abstract The current drag coefficient.
|
||||
@discussion A value greater than 1.0 indicates Simulator slow-motion animations are enabled. Defaults to 1.0.
|
||||
*/
|
||||
extern CGFloat POPAnimationDragCoefficient();
|
||||
|
||||
@interface CAAnimation (POPAnimationExtras)
|
||||
|
||||
/**
|
||||
@abstract Apply the current drag coefficient to animation speed.
|
||||
@discussion Convenience utility to respect Simulator slow-motion animation settings.
|
||||
*/
|
||||
- (void)pop_applyDragCoefficient;
|
||||
|
||||
@end
|
||||
|
||||
@interface POPSpringAnimation (POPAnimationExtras)
|
||||
|
||||
/**
|
||||
@abstract Converts from spring bounciness and speed to tension, friction and mass dynamics values.
|
||||
*/
|
||||
+ (void)convertBounciness:(CGFloat)bounciness speed:(CGFloat)speed toTension:(CGFloat *)outTension friction:(CGFloat *)outFriction mass:(CGFloat *)outMass;
|
||||
|
||||
/**
|
||||
@abstract Converts from dynamics tension, friction and mass to spring bounciness and speed values.
|
||||
*/
|
||||
+ (void)convertTension:(CGFloat)tension friction:(CGFloat)friction toBounciness:(CGFloat *)outBounciness speed:(CGFloat *)outSpeed;
|
||||
|
||||
@end
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPAnimationExtras.h"
|
||||
|
||||
#import "POPAnimationPrivate.h"
|
||||
#import "POPMath.h"
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
||||
|
||||
#if TARGET_IPHONE_SIMULATOR
|
||||
UIKIT_EXTERN CGFloat UIAnimationDragCoefficient(); // UIKit private drag coeffient, use judiciously
|
||||
#endif
|
||||
|
||||
CGFloat POPAnimationDragCoefficient()
|
||||
{
|
||||
#if TARGET_IPHONE_SIMULATOR
|
||||
return UIAnimationDragCoefficient();
|
||||
#else
|
||||
return 1.0;
|
||||
#endif
|
||||
}
|
||||
|
||||
@implementation CAAnimation (POPAnimationExtras)
|
||||
|
||||
- (void)pop_applyDragCoefficient
|
||||
{
|
||||
CGFloat k = POPAnimationDragCoefficient();
|
||||
if (k != 0 && k != 1)
|
||||
self.speed = 1 / k;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation POPSpringAnimation (POPAnimationExtras)
|
||||
|
||||
static const CGFloat POPBouncy3NormalizationRange = 20.0;
|
||||
static const CGFloat POPBouncy3NormalizationScale = 1.7;
|
||||
static const CGFloat POPBouncy3BouncinessNormalizedMin = 0.0;
|
||||
static const CGFloat POPBouncy3BouncinessNormalizedMax = 0.8;
|
||||
static const CGFloat POPBouncy3SpeedNormalizedMin = 0.5;
|
||||
static const CGFloat POPBouncy3SpeedNormalizedMax = 200;
|
||||
static const CGFloat POPBouncy3FrictionInterpolationMax = 0.01;
|
||||
|
||||
+ (void)convertBounciness:(CGFloat)bounciness speed:(CGFloat)speed toTension:(CGFloat *)outTension friction:(CGFloat *)outFriction mass:(CGFloat *)outMass
|
||||
{
|
||||
double b = POPNormalize(bounciness / POPBouncy3NormalizationScale, 0, POPBouncy3NormalizationRange);
|
||||
b = POPProjectNormal(b, POPBouncy3BouncinessNormalizedMin, POPBouncy3BouncinessNormalizedMax);
|
||||
|
||||
double s = POPNormalize(speed / POPBouncy3NormalizationScale, 0, POPBouncy3NormalizationRange);
|
||||
|
||||
CGFloat tension = POPProjectNormal(s, POPBouncy3SpeedNormalizedMin, POPBouncy3SpeedNormalizedMax);
|
||||
CGFloat friction = POPQuadraticOutInterpolation(b, POPBouncy3NoBounce(tension), POPBouncy3FrictionInterpolationMax);
|
||||
|
||||
tension = POP_ANIMATION_TENSION_FOR_QC_TENSION(tension);
|
||||
friction = POP_ANIMATION_FRICTION_FOR_QC_FRICTION(friction);
|
||||
|
||||
if (outTension) {
|
||||
*outTension = tension;
|
||||
}
|
||||
|
||||
if (outFriction) {
|
||||
*outFriction = friction;
|
||||
}
|
||||
|
||||
if (outMass) {
|
||||
*outMass = 1.0;
|
||||
}
|
||||
}
|
||||
|
||||
+ (void)convertTension:(CGFloat)tension friction:(CGFloat)friction toBounciness:(CGFloat *)outBounciness speed:(CGFloat *)outSpeed
|
||||
{
|
||||
// Convert to QC values, in which our calculations are done.
|
||||
CGFloat qcFriction = QC_FRICTION_FOR_POP_ANIMATION_FRICTION(friction);
|
||||
CGFloat qcTension = QC_TENSION_FOR_POP_ANIMATION_TENSION(tension);
|
||||
|
||||
// Friction is a function of bounciness and tension, according to the following:
|
||||
// friction = POPQuadraticOutInterpolation(b, POPBouncy3NoBounce(tension), POPBouncy3FrictionInterpolationMax);
|
||||
// Solve for bounciness, given a tension and friction.
|
||||
|
||||
CGFloat nobounceTension = POPBouncy3NoBounce(qcTension);
|
||||
CGFloat bounciness1, bounciness2;
|
||||
|
||||
POPQuadraticSolve((nobounceTension - POPBouncy3FrictionInterpolationMax), // a
|
||||
2 * (POPBouncy3FrictionInterpolationMax - nobounceTension), // b
|
||||
(nobounceTension - qcFriction), // c
|
||||
bounciness1, // x1
|
||||
bounciness2); // x2
|
||||
|
||||
|
||||
// Choose the quadratic solution within the normalized bounciness range
|
||||
CGFloat projectedNormalizedBounciness = (bounciness2 < POPBouncy3BouncinessNormalizedMax) ? bounciness2 : bounciness1;
|
||||
CGFloat projectedNormalizedSpeed = qcTension;
|
||||
|
||||
// Reverse projection + normalization
|
||||
CGFloat bounciness = ((POPBouncy3NormalizationRange * POPBouncy3NormalizationScale) / (POPBouncy3BouncinessNormalizedMax - POPBouncy3BouncinessNormalizedMin)) * (projectedNormalizedBounciness - POPBouncy3BouncinessNormalizedMin);
|
||||
CGFloat speed = ((POPBouncy3NormalizationRange * POPBouncy3NormalizationScale) / (POPBouncy3SpeedNormalizedMax - POPBouncy3SpeedNormalizedMin)) * (projectedNormalizedSpeed - POPBouncy3SpeedNormalizedMin);
|
||||
|
||||
// Write back results
|
||||
if (outBounciness) {
|
||||
*outBounciness = bounciness;
|
||||
}
|
||||
|
||||
if (outSpeed) {
|
||||
*outSpeed = speed;
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
+480
@@ -0,0 +1,480 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <QuartzCore/CAMediaTimingFunction.h>
|
||||
|
||||
#import "POPAnimation.h"
|
||||
#import "POPAnimationRuntime.h"
|
||||
#import "POPAnimationTracerInternal.h"
|
||||
#import "POPSpringSolver.h"
|
||||
#import "POPAction.h"
|
||||
|
||||
using namespace POP;
|
||||
|
||||
/**
|
||||
Enumeration of supported animation types.
|
||||
*/
|
||||
enum POPAnimationType
|
||||
{
|
||||
kPOPAnimationSpring,
|
||||
kPOPAnimationDecay,
|
||||
kPOPAnimationBasic,
|
||||
kPOPAnimationCustom,
|
||||
};
|
||||
|
||||
typedef struct
|
||||
{
|
||||
CGFloat progress;
|
||||
bool reached;
|
||||
} POPProgressMarker;
|
||||
|
||||
typedef void (^POPAnimationCompletionBlock)(POPAnimation *anim, BOOL finished);
|
||||
|
||||
@interface POPAnimation()
|
||||
- (instancetype)_init;
|
||||
|
||||
@property (assign, nonatomic) SpringSolver4d *solver;
|
||||
@property (readonly, nonatomic) POPAnimationType type;
|
||||
|
||||
/**
|
||||
The current animation value, updated while animation is progressing.
|
||||
*/
|
||||
@property (copy, nonatomic, readonly) id currentValue;
|
||||
|
||||
/**
|
||||
An array of optional progress markers. For each marker specified, the animation delegate will be informed when progress meets or exceeds the value specified. Specifying values outside of the [0, 1] range will give undefined results.
|
||||
*/
|
||||
@property (copy, nonatomic) NSArray *progressMarkers;
|
||||
|
||||
/**
|
||||
Return YES to indicate animation should continue animating.
|
||||
*/
|
||||
- (BOOL)_advance:(id)object currentTime:(CFTimeInterval)currentTime elapsedTime:(CFTimeInterval)elapsedTime;
|
||||
|
||||
/**
|
||||
Subclass override point to append animation description.
|
||||
*/
|
||||
- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug;
|
||||
|
||||
@end
|
||||
|
||||
NS_INLINE NSString *describe(VectorConstRef vec)
|
||||
{
|
||||
return NULL == vec ? @"null" : vec->toString();
|
||||
}
|
||||
|
||||
NS_INLINE Vector4r vector4(VectorConstRef vec)
|
||||
{
|
||||
return NULL == vec ? Vector4r::Zero() : vec->vector4r();
|
||||
}
|
||||
|
||||
NS_INLINE Vector4d vector4d(VectorConstRef vec)
|
||||
{
|
||||
if (NULL == vec) {
|
||||
return Vector4d::Zero();
|
||||
} else {
|
||||
return vec->vector4r().cast<double>();
|
||||
}
|
||||
}
|
||||
|
||||
NS_INLINE bool vec_equal(VectorConstRef v1, VectorConstRef v2)
|
||||
{
|
||||
if (v1 == v2) {
|
||||
return true;
|
||||
}
|
||||
if (!v1 || !v2) {
|
||||
return false;
|
||||
}
|
||||
return *v1 == *v2;
|
||||
}
|
||||
|
||||
NS_INLINE CGFloat * vec_data(VectorRef vec)
|
||||
{
|
||||
return NULL == vec ? NULL : vec->data();
|
||||
}
|
||||
|
||||
template<class T>
|
||||
struct ComputeProgressFunctor {
|
||||
CGFloat operator()(const T &value, const T &start, const T &end) const {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
template<>
|
||||
struct ComputeProgressFunctor<Vector4r> {
|
||||
CGFloat operator()(const Vector4r &value, const Vector4r &start, const Vector4r &end) const {
|
||||
CGFloat s = (value - start).squaredNorm(); // distance from start
|
||||
CGFloat e = (value - end).squaredNorm(); // distance from end
|
||||
CGFloat d = (end - start).squaredNorm(); // distance from start to end
|
||||
|
||||
if (0 == d) {
|
||||
return 1;
|
||||
} else if (s > e) {
|
||||
// s -------- p ---- e OR s ------- e ---- p
|
||||
return sqrtr(s/d);
|
||||
} else {
|
||||
// s --- p --------- e OR p ---- s ------- e
|
||||
return 1 - sqrtr(e/d);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct _POPAnimationState;
|
||||
struct _POPDecayAnimationState;
|
||||
struct _POPPropertyAnimationState;
|
||||
|
||||
extern _POPAnimationState *POPAnimationGetState(POPAnimation *a);
|
||||
|
||||
|
||||
#define FB_FLAG_GET(stype, flag, getter) \
|
||||
- (BOOL)getter { \
|
||||
return ((stype *)_state)->flag; \
|
||||
}
|
||||
|
||||
#define FB_FLAG_SET(stype, flag, mutator) \
|
||||
- (void)mutator (BOOL)value { \
|
||||
if (value == ((stype *)_state)->flag) \
|
||||
return; \
|
||||
((stype *)_state)->flag = value; \
|
||||
}
|
||||
|
||||
#define DEFINE_RW_FLAG(stype, flag, getter, mutator) \
|
||||
FB_FLAG_GET (stype, flag, getter) \
|
||||
FB_FLAG_SET (stype, flag, mutator)
|
||||
|
||||
#define FB_PROPERTY_GET(stype, property, ctype) \
|
||||
- (ctype)property { \
|
||||
return ((stype *)_state)->property; \
|
||||
}
|
||||
|
||||
#define FB_PROPERTY_SET(stype, property, mutator, ctype, ...) \
|
||||
- (void)mutator (ctype)value { \
|
||||
if (value == ((stype *)_state)->property) \
|
||||
return; \
|
||||
((stype *)_state)->property = value; \
|
||||
__VA_ARGS__ \
|
||||
}
|
||||
|
||||
#define FB_PROPERTY_SET_OBJ_COPY(stype, property, mutator, ctype, ...) \
|
||||
- (void)mutator (ctype)value { \
|
||||
if (value == ((stype *)_state)->property) \
|
||||
return; \
|
||||
((stype *)_state)->property = [value copy]; \
|
||||
__VA_ARGS__ \
|
||||
}
|
||||
|
||||
#define DEFINE_RW_PROPERTY(stype, flag, mutator, ctype, ...) \
|
||||
FB_PROPERTY_GET (stype, flag, ctype) \
|
||||
FB_PROPERTY_SET (stype, flag, mutator, ctype, __VA_ARGS__)
|
||||
|
||||
#define DEFINE_RW_PROPERTY_OBJ(stype, flag, mutator, ctype, ...) \
|
||||
FB_PROPERTY_GET (stype, flag, ctype) \
|
||||
FB_PROPERTY_SET (stype, flag, mutator, ctype, __VA_ARGS__)
|
||||
|
||||
#define DEFINE_RW_PROPERTY_OBJ_COPY(stype, flag, mutator, ctype, ...) \
|
||||
FB_PROPERTY_GET (stype, flag, ctype) \
|
||||
FB_PROPERTY_SET_OBJ_COPY (stype, flag, mutator, ctype, __VA_ARGS__)
|
||||
|
||||
|
||||
/**
|
||||
Internal delegate definition.
|
||||
*/
|
||||
@interface NSObject (POPAnimationDelegateInternal)
|
||||
- (void)pop_animation:(POPAnimation *)anim didReachProgress:(CGFloat)progress;
|
||||
@end
|
||||
|
||||
struct _POPAnimationState
|
||||
{
|
||||
id __unsafe_unretained self;
|
||||
POPAnimationType type;
|
||||
NSString *name;
|
||||
NSUInteger ID;
|
||||
CFTimeInterval beginTime;
|
||||
CFTimeInterval startTime;
|
||||
CFTimeInterval lastTime;
|
||||
id __weak delegate;
|
||||
POPAnimationCompletionBlock completionBlock;
|
||||
NSMutableDictionary *dict;
|
||||
POPAnimationTracer *tracer;
|
||||
CGFloat progress;
|
||||
NSInteger repeatCount;
|
||||
|
||||
bool active:1;
|
||||
bool paused:1;
|
||||
bool removedOnCompletion:1;
|
||||
|
||||
bool delegateDidStart:1;
|
||||
bool delegateDidStop:1;
|
||||
bool delegateDidProgress:1;
|
||||
bool delegateDidApply:1;
|
||||
bool delegateDidReachToValue:1;
|
||||
|
||||
bool additive:1;
|
||||
bool didReachToValue:1;
|
||||
bool tracing:1; // corresponds to tracer started
|
||||
bool userSpecifiedDynamics:1;
|
||||
bool autoreverses:1;
|
||||
bool repeatForever:1;
|
||||
bool customFinished:1;
|
||||
|
||||
_POPAnimationState(id __unsafe_unretained anim) :
|
||||
self(anim),
|
||||
type((POPAnimationType)0),
|
||||
name(nil),
|
||||
ID(0),
|
||||
beginTime(0),
|
||||
startTime(0),
|
||||
lastTime(0),
|
||||
delegate(nil),
|
||||
completionBlock(nil),
|
||||
dict(nil),
|
||||
tracer(nil),
|
||||
progress(0),
|
||||
repeatCount(0),
|
||||
active(false),
|
||||
paused(true),
|
||||
removedOnCompletion(true),
|
||||
delegateDidStart(false),
|
||||
delegateDidStop(false),
|
||||
delegateDidProgress(false),
|
||||
delegateDidApply(false),
|
||||
delegateDidReachToValue(false),
|
||||
additive(false),
|
||||
didReachToValue(false),
|
||||
tracing(false),
|
||||
userSpecifiedDynamics(false),
|
||||
autoreverses(false),
|
||||
repeatForever(false),
|
||||
customFinished(false) {}
|
||||
|
||||
virtual ~_POPAnimationState()
|
||||
{
|
||||
name = nil;
|
||||
dict = nil;
|
||||
tracer = nil;
|
||||
completionBlock = NULL;
|
||||
}
|
||||
|
||||
bool isCustom() {
|
||||
return kPOPAnimationCustom == type;
|
||||
}
|
||||
|
||||
bool isStarted() {
|
||||
return 0 != startTime;
|
||||
}
|
||||
|
||||
id getDelegate() {
|
||||
return delegate;
|
||||
}
|
||||
|
||||
void setDelegate(id d) {
|
||||
if (d != delegate) {
|
||||
delegate = d;
|
||||
delegateDidStart = [d respondsToSelector:@selector(pop_animationDidStart:)];
|
||||
delegateDidStop = [d respondsToSelector:@selector(pop_animationDidStop:finished:)];
|
||||
delegateDidProgress = [d respondsToSelector:@selector(pop_animation:didReachProgress:)];
|
||||
delegateDidApply = [d respondsToSelector:@selector(pop_animationDidApply:)];
|
||||
delegateDidReachToValue = [d respondsToSelector:@selector(pop_animationDidReachToValue:)];
|
||||
}
|
||||
}
|
||||
|
||||
bool getPaused() {
|
||||
return paused;
|
||||
}
|
||||
|
||||
void setPaused(bool f) {
|
||||
if (f != paused) {
|
||||
paused = f;
|
||||
if (!paused) {
|
||||
reset(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CGFloat getProgress() {
|
||||
return progress;
|
||||
}
|
||||
|
||||
/* returns true if started */
|
||||
bool startIfNeeded(id obj, CFTimeInterval time, CFTimeInterval offset)
|
||||
{
|
||||
bool started = false;
|
||||
|
||||
// detect start based on time
|
||||
if (0 == startTime && time >= beginTime + offset) {
|
||||
|
||||
// activate & unpause
|
||||
active = true;
|
||||
setPaused(false);
|
||||
|
||||
// note start time
|
||||
startTime = lastTime = time;
|
||||
started = true;
|
||||
}
|
||||
|
||||
// ensure values for running animation
|
||||
bool running = active && !paused;
|
||||
if (running) {
|
||||
willRun(started, obj);
|
||||
}
|
||||
|
||||
// handle start
|
||||
if (started) {
|
||||
handleDidStart();
|
||||
}
|
||||
|
||||
return started;
|
||||
}
|
||||
|
||||
void stop(bool removing, bool done) {
|
||||
if (active)
|
||||
{
|
||||
// delegate progress one last time
|
||||
if (done) {
|
||||
delegateProgress();
|
||||
}
|
||||
|
||||
if (removing) {
|
||||
active = false;
|
||||
}
|
||||
|
||||
handleDidStop(done);
|
||||
} else {
|
||||
|
||||
// stopped before even started
|
||||
// delegate start and stop regardless; matches CA behavior
|
||||
if (!isStarted()) {
|
||||
handleDidStart();
|
||||
handleDidStop(false);
|
||||
}
|
||||
}
|
||||
|
||||
setPaused(true);
|
||||
}
|
||||
|
||||
virtual void handleDidStart()
|
||||
{
|
||||
if (delegateDidStart) {
|
||||
ActionEnabler enabler;
|
||||
[delegate pop_animationDidStart:self];
|
||||
}
|
||||
|
||||
if (tracing) {
|
||||
[tracer didStart];
|
||||
}
|
||||
}
|
||||
|
||||
void handleDidStop(BOOL done)
|
||||
{
|
||||
if (delegateDidStop) {
|
||||
ActionEnabler enabler;
|
||||
[delegate pop_animationDidStop:self finished:done];
|
||||
}
|
||||
|
||||
// add another strong reference to completion block before callout
|
||||
POPAnimationCompletionBlock block = completionBlock;
|
||||
if (block != NULL) {
|
||||
ActionEnabler enabler;
|
||||
block(self, done);
|
||||
}
|
||||
|
||||
if (tracing) {
|
||||
[tracer didStop:done];
|
||||
}
|
||||
}
|
||||
|
||||
/* virtual functions */
|
||||
virtual bool isDone() {
|
||||
if (isCustom()) {
|
||||
return customFinished;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool advanceTime(CFTimeInterval time, id obj) {
|
||||
bool advanced = false;
|
||||
bool computedProgress = false;
|
||||
CFTimeInterval dt = time - lastTime;
|
||||
|
||||
switch (type) {
|
||||
case kPOPAnimationSpring:
|
||||
advanced = advance(time, dt, obj);
|
||||
break;
|
||||
case kPOPAnimationDecay:
|
||||
advanced = advance(time, dt, obj);
|
||||
break;
|
||||
case kPOPAnimationBasic: {
|
||||
advanced = advance(time, dt, obj);
|
||||
computedProgress = true;
|
||||
break;
|
||||
}
|
||||
case kPOPAnimationCustom: {
|
||||
customFinished = [self _advance:obj currentTime:time elapsedTime:dt] ? false : true;
|
||||
advanced = true;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (advanced) {
|
||||
|
||||
// estimate progress
|
||||
if (!computedProgress) {
|
||||
computeProgress();
|
||||
}
|
||||
|
||||
// delegate progress
|
||||
delegateProgress();
|
||||
|
||||
// update time
|
||||
lastTime = time;
|
||||
}
|
||||
|
||||
return advanced;
|
||||
}
|
||||
|
||||
virtual void willRun(bool started, id obj) {}
|
||||
virtual bool advance(CFTimeInterval time, CFTimeInterval dt, id obj) { return false; }
|
||||
virtual void computeProgress() {}
|
||||
virtual void delegateProgress() {}
|
||||
|
||||
virtual void delegateApply() {
|
||||
if (delegateDidApply) {
|
||||
ActionEnabler enabler;
|
||||
[delegate pop_animationDidApply:self];
|
||||
}
|
||||
}
|
||||
|
||||
virtual void reset(bool all) {
|
||||
startTime = 0;
|
||||
lastTime = 0;
|
||||
}
|
||||
};
|
||||
|
||||
typedef struct _POPAnimationState POPAnimationState;
|
||||
|
||||
|
||||
@interface POPAnimation ()
|
||||
{
|
||||
@protected
|
||||
struct _POPAnimationState *_state;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
// NSProxy extensions, for testing pursposes
|
||||
@interface NSProxy (POP)
|
||||
- (void)pop_addAnimation:(POPAnimation *)anim forKey:(NSString *)key;
|
||||
- (void)pop_removeAllAnimations;
|
||||
- (void)pop_removeAnimationForKey:(NSString *)key;
|
||||
- (NSArray *)pop_animationKeys;
|
||||
- (POPAnimation *)pop_animationForKey:(NSString *)key;
|
||||
@end
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <pop/POPAnimation.h>
|
||||
|
||||
#define POP_ANIMATION_FRICTION_FOR_QC_FRICTION(qcFriction) (25.0 + (((qcFriction - 8.0) / 2.0) * (25.0 - 19.0)))
|
||||
#define POP_ANIMATION_TENSION_FOR_QC_TENSION(qcTension) (194.0 + (((qcTension - 30.0) / 50.0) * (375.0 - 194.0)))
|
||||
|
||||
#define QC_FRICTION_FOR_POP_ANIMATION_FRICTION(fbFriction) (8.0 + 2.0 * ((fbFriction - 25.0)/(25.0 - 19.0)))
|
||||
#define QC_TENSION_FOR_POP_ANIMATION_TENSION(fbTension) (30.0 + 50.0 * ((fbTension - 194.0)/(375.0 - 194.0)))
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "POPVector.h"
|
||||
|
||||
enum POPValueType
|
||||
{
|
||||
kPOPValueUnknown = 0,
|
||||
kPOPValueInteger,
|
||||
kPOPValueFloat,
|
||||
kPOPValuePoint,
|
||||
kPOPValueSize,
|
||||
kPOPValueRect,
|
||||
kPOPValueEdgeInsets,
|
||||
kPOPValueAffineTransform,
|
||||
kPOPValueTransform,
|
||||
kPOPValueRange,
|
||||
kPOPValueColor,
|
||||
};
|
||||
|
||||
using namespace POP;
|
||||
|
||||
/**
|
||||
Returns value type based on objc type description, given list of supported value types and length.
|
||||
*/
|
||||
extern POPValueType POPSelectValueType(const char *objctype, const POPValueType *types, size_t length);
|
||||
|
||||
/**
|
||||
Returns value type based on objc object, given a list of supported value types and length.
|
||||
*/
|
||||
extern POPValueType POPSelectValueType(id obj, const POPValueType *types, size_t length);
|
||||
|
||||
/**
|
||||
Array of all value types.
|
||||
*/
|
||||
extern const POPValueType kPOPAnimatableAllTypes[10];
|
||||
|
||||
/**
|
||||
Array of all value types supported for animation.
|
||||
*/
|
||||
extern const POPValueType kPOPAnimatableSupportTypes[8];
|
||||
|
||||
/**
|
||||
Returns a string description of a value type.
|
||||
*/
|
||||
extern NSString *POPValueTypeToString(POPValueType t);
|
||||
|
||||
/**
|
||||
Returns a mutable dictionary of weak pointer keys to weak pointer values.
|
||||
*/
|
||||
extern CFMutableDictionaryRef POPDictionaryCreateMutableWeakPointerToWeakPointer(NSUInteger capacity) CF_RETURNS_RETAINED;
|
||||
|
||||
/**
|
||||
Returns a mutable dictionary of weak pointer keys to weak pointer values.
|
||||
*/
|
||||
extern CFMutableDictionaryRef POPDictionaryCreateMutableWeakPointerToStrongObject(NSUInteger capacity) CF_RETURNS_RETAINED;
|
||||
|
||||
/**
|
||||
Box a vector.
|
||||
*/
|
||||
extern id POPBox(VectorConstRef vec, POPValueType type, bool force = false);
|
||||
|
||||
/**
|
||||
Unbox a vector.
|
||||
*/
|
||||
extern VectorRef POPUnbox(id value, POPValueType &type, NSUInteger &count, bool validate);
|
||||
|
||||
/**
|
||||
Read/write block typedefs for convenience.
|
||||
*/
|
||||
typedef void(^pop_animatable_read_block)(id obj, CGFloat *value);
|
||||
typedef void(^pop_animatable_write_block)(id obj, const CGFloat *value);
|
||||
|
||||
/**
|
||||
Read object value and return a Vector4r.
|
||||
*/
|
||||
NS_INLINE Vector4r read_values(pop_animatable_read_block read, id obj, size_t count)
|
||||
{
|
||||
Vector4r vec = Vector4r::Zero();
|
||||
if (0 == count)
|
||||
return vec;
|
||||
|
||||
read(obj, vec.data());
|
||||
|
||||
return vec;
|
||||
}
|
||||
|
||||
NS_INLINE NSString *POPStringFromBOOL(BOOL value)
|
||||
{
|
||||
return value ? @"YES" : @"NO";
|
||||
}
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPAnimationRuntime.h"
|
||||
|
||||
#import <objc/objc.h>
|
||||
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
||||
|
||||
#import "POPVector.h"
|
||||
#import "POPAnimationRuntime.h"
|
||||
#import "POPCGUtils.h"
|
||||
#import "POPGeometry.h"
|
||||
|
||||
static Boolean pointerEqual(const void *ptr1, const void *ptr2) {
|
||||
return ptr1 == ptr2;
|
||||
}
|
||||
|
||||
static CFHashCode pointerHash(const void *ptr) {
|
||||
return (CFHashCode)(ptr);
|
||||
}
|
||||
|
||||
CFMutableDictionaryRef POPDictionaryCreateMutableWeakPointerToWeakPointer(NSUInteger capacity)
|
||||
{
|
||||
CFDictionaryKeyCallBacks kcb = kCFTypeDictionaryKeyCallBacks;
|
||||
|
||||
// weak, pointer keys
|
||||
kcb.retain = NULL;
|
||||
kcb.retain = NULL;
|
||||
kcb.equal = pointerEqual;
|
||||
kcb.hash = pointerHash;
|
||||
|
||||
CFDictionaryValueCallBacks vcb = kCFTypeDictionaryValueCallBacks;
|
||||
|
||||
// weak, pointer values
|
||||
vcb.retain = NULL;
|
||||
vcb.release = NULL;
|
||||
vcb.equal = pointerEqual;
|
||||
|
||||
return CFDictionaryCreateMutable(NULL, capacity, &kcb, &vcb);
|
||||
}
|
||||
|
||||
CFMutableDictionaryRef POPDictionaryCreateMutableWeakPointerToStrongObject(NSUInteger capacity)
|
||||
{
|
||||
CFDictionaryKeyCallBacks kcb = kCFTypeDictionaryKeyCallBacks;
|
||||
|
||||
// weak, pointer keys
|
||||
kcb.retain = NULL;
|
||||
kcb.release = NULL;
|
||||
kcb.equal = pointerEqual;
|
||||
kcb.hash = pointerHash;
|
||||
|
||||
// strong, object values
|
||||
CFDictionaryValueCallBacks vcb = kCFTypeDictionaryValueCallBacks;
|
||||
|
||||
return CFDictionaryCreateMutable(NULL, capacity, &kcb, &vcb);
|
||||
}
|
||||
|
||||
static bool FBCompareTypeEncoding(const char *objctype, POPValueType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case kPOPValueFloat:
|
||||
return (strcmp(objctype, @encode(float)) == 0
|
||||
|| strcmp(objctype, @encode(double)) == 0
|
||||
);
|
||||
|
||||
case kPOPValuePoint:
|
||||
return (strcmp(objctype, @encode(CGPoint)) == 0
|
||||
#if !TARGET_OS_IPHONE
|
||||
|| strcmp(objctype, @encode(NSPoint)) == 0
|
||||
#endif
|
||||
);
|
||||
|
||||
case kPOPValueSize:
|
||||
return (strcmp(objctype, @encode(CGSize)) == 0
|
||||
#if !TARGET_OS_IPHONE
|
||||
|| strcmp(objctype, @encode(NSSize)) == 0
|
||||
#endif
|
||||
);
|
||||
|
||||
case kPOPValueRect:
|
||||
return (strcmp(objctype, @encode(CGRect)) == 0
|
||||
#if !TARGET_OS_IPHONE
|
||||
|| strcmp(objctype, @encode(NSRect)) == 0
|
||||
#endif
|
||||
);
|
||||
case kPOPValueEdgeInsets:
|
||||
#if TARGET_OS_IPHONE
|
||||
return strcmp(objctype, @encode(UIEdgeInsets)) == 0;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
|
||||
case kPOPValueAffineTransform:
|
||||
return strcmp(objctype, @encode(CGAffineTransform)) == 0;
|
||||
|
||||
case kPOPValueTransform:
|
||||
return strcmp(objctype, @encode(CATransform3D)) == 0;
|
||||
|
||||
case kPOPValueRange:
|
||||
return strcmp(objctype, @encode(CFRange)) == 0
|
||||
|| strcmp(objctype, @encode (NSRange)) == 0;
|
||||
|
||||
case kPOPValueInteger:
|
||||
return (strcmp(objctype, @encode(int)) == 0
|
||||
|| strcmp(objctype, @encode(unsigned int)) == 0
|
||||
|| strcmp(objctype, @encode(short)) == 0
|
||||
|| strcmp(objctype, @encode(unsigned short)) == 0
|
||||
|| strcmp(objctype, @encode(long)) == 0
|
||||
|| strcmp(objctype, @encode(unsigned long)) == 0
|
||||
|| strcmp(objctype, @encode(long long)) == 0
|
||||
|| strcmp(objctype, @encode(unsigned long long)) == 0
|
||||
);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
POPValueType POPSelectValueType(const char *objctype, const POPValueType *types, size_t length)
|
||||
{
|
||||
if (NULL != objctype) {
|
||||
for (size_t idx = 0; idx < length; idx++) {
|
||||
if (FBCompareTypeEncoding(objctype, types[idx]))
|
||||
return types[idx];
|
||||
}
|
||||
}
|
||||
return kPOPValueUnknown;
|
||||
}
|
||||
|
||||
POPValueType POPSelectValueType(id obj, const POPValueType *types, size_t length)
|
||||
{
|
||||
if ([obj isKindOfClass:[NSValue class]]) {
|
||||
return POPSelectValueType([obj objCType], types, length);
|
||||
} else if (NULL != POPCGColorWithColor(obj)) {
|
||||
return kPOPValueColor;
|
||||
}
|
||||
return kPOPValueUnknown;
|
||||
}
|
||||
|
||||
const POPValueType kPOPAnimatableAllTypes[10] = {kPOPValueInteger, kPOPValueFloat, kPOPValuePoint, kPOPValueSize, kPOPValueRect, kPOPValueEdgeInsets, kPOPValueAffineTransform, kPOPValueTransform, kPOPValueRange, kPOPValueColor};
|
||||
|
||||
const POPValueType kPOPAnimatableSupportTypes[8] = {kPOPValueInteger, kPOPValueFloat, kPOPValuePoint, kPOPValueSize, kPOPValueRect, kPOPValueEdgeInsets, kPOPValueColor};
|
||||
|
||||
NSString *POPValueTypeToString(POPValueType t)
|
||||
{
|
||||
switch (t) {
|
||||
case kPOPValueUnknown:
|
||||
return @"unknown";
|
||||
case kPOPValueInteger:
|
||||
return @"int";
|
||||
case kPOPValueFloat:
|
||||
return @"CGFloat";
|
||||
case kPOPValuePoint:
|
||||
return @"CGPoint";
|
||||
case kPOPValueSize:
|
||||
return @"CGSize";
|
||||
case kPOPValueRect:
|
||||
return @"CGRect";
|
||||
case kPOPValueEdgeInsets:
|
||||
return @"UIEdgeInsets";
|
||||
case kPOPValueAffineTransform:
|
||||
return @"CGAffineTransform";
|
||||
case kPOPValueTransform:
|
||||
return @"CATransform3D";
|
||||
case kPOPValueRange:
|
||||
return @"CFRange";
|
||||
case kPOPValueColor:
|
||||
return @"CGColorRef";
|
||||
default:
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
id POPBox(VectorConstRef vec, POPValueType type, bool force)
|
||||
{
|
||||
if (NULL == vec)
|
||||
return nil;
|
||||
|
||||
switch (type) {
|
||||
case kPOPValueInteger:
|
||||
case kPOPValueFloat:
|
||||
return @(vec->data()[0]);
|
||||
break;
|
||||
case kPOPValuePoint:
|
||||
return [NSValue valueWithCGPoint:vec->cg_point()];
|
||||
break;
|
||||
case kPOPValueSize:
|
||||
return [NSValue valueWithCGSize:vec->cg_size()];
|
||||
break;
|
||||
case kPOPValueRect:
|
||||
return [NSValue valueWithCGRect:vec->cg_rect()];
|
||||
break;
|
||||
#if TARGET_OS_IPHONE
|
||||
case kPOPValueEdgeInsets:
|
||||
return [NSValue valueWithUIEdgeInsets:vec->ui_edge_insets()];
|
||||
break;
|
||||
#endif
|
||||
case kPOPValueColor: {
|
||||
return (__bridge_transfer id)vec->cg_color();
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return force ? [NSValue valueWithCGPoint:vec->cg_point()] : nil;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static VectorRef vectorize(id value, POPValueType type)
|
||||
{
|
||||
Vector *vec = NULL;
|
||||
|
||||
switch (type) {
|
||||
case kPOPValueInteger:
|
||||
case kPOPValueFloat:
|
||||
vec = Vector::new_cg_float([value floatValue]);
|
||||
break;
|
||||
case kPOPValuePoint:
|
||||
vec = Vector::new_cg_point([value CGPointValue]);
|
||||
break;
|
||||
case kPOPValueSize:
|
||||
vec = Vector::new_cg_size([value CGSizeValue]);
|
||||
break;
|
||||
case kPOPValueRect:
|
||||
vec = Vector::new_cg_rect([value CGRectValue]);
|
||||
break;
|
||||
#if TARGET_OS_IPHONE
|
||||
case kPOPValueEdgeInsets:
|
||||
vec = Vector::new_ui_edge_insets([value UIEdgeInsetsValue]);
|
||||
break;
|
||||
#endif
|
||||
case kPOPValueAffineTransform:
|
||||
vec = Vector::new_cg_affine_transform([value CGAffineTransformValue]);
|
||||
break;
|
||||
case kPOPValueColor:
|
||||
vec = Vector::new_cg_color(POPCGColorWithColor(value));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return VectorRef(vec);
|
||||
}
|
||||
|
||||
VectorRef POPUnbox(id value, POPValueType &animationType, NSUInteger &count, bool validate)
|
||||
{
|
||||
if (nil == value) {
|
||||
count = 0;
|
||||
return VectorRef(NULL);
|
||||
}
|
||||
|
||||
// determine type of value
|
||||
POPValueType valueType = POPSelectValueType(value, kPOPAnimatableSupportTypes, POP_ARRAY_COUNT(kPOPAnimatableSupportTypes));
|
||||
|
||||
// handle unknown types
|
||||
if (kPOPValueUnknown == valueType) {
|
||||
NSString *valueDesc = kPOPValueUnknown != valueType ? POPValueTypeToString(valueType) : [[value class] description];
|
||||
[NSException raise:@"Unsuported value" format:@"Animating %@ values is not supported", valueDesc];
|
||||
}
|
||||
|
||||
// vectorize
|
||||
VectorRef vec = vectorize(value, valueType);
|
||||
|
||||
if (kPOPValueUnknown == animationType || 0 == count) {
|
||||
// update animation type based on value type
|
||||
animationType = valueType;
|
||||
if (NULL != vec) {
|
||||
count = vec->size();
|
||||
}
|
||||
} else if (validate) {
|
||||
// allow for mismatched types, so long as vector size matches
|
||||
if (count != vec->size()) {
|
||||
[NSException raise:@"Invalid value" format:@"%@ should be of type %@", value, POPValueTypeToString(animationType)];
|
||||
}
|
||||
}
|
||||
|
||||
return vec;
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <pop/POPAnimationEvent.h>
|
||||
|
||||
@class POPAnimation;
|
||||
|
||||
/**
|
||||
@abstract Tracer of animation events to fasciliate unit testing & debugging.
|
||||
*/
|
||||
@interface POPAnimationTracer : NSObject
|
||||
|
||||
/**
|
||||
@abstract Start recording events.
|
||||
*/
|
||||
- (void)start;
|
||||
|
||||
/**
|
||||
@abstract Stop recording events.
|
||||
*/
|
||||
- (void)stop;
|
||||
|
||||
/**
|
||||
@abstract Resets any recoded events. Continues recording events if already started.
|
||||
*/
|
||||
- (void)reset;
|
||||
|
||||
/**
|
||||
@abstract Property representing all recorded events.
|
||||
@discussion Events are returned in order of occurence.
|
||||
*/
|
||||
@property (nonatomic, assign, readonly) NSArray *allEvents;
|
||||
|
||||
/**
|
||||
@abstract Property representing all recorded write events for convenience.
|
||||
@discussion Events are returned in order of occurence.
|
||||
*/
|
||||
@property (nonatomic, assign, readonly) NSArray *writeEvents;
|
||||
|
||||
/**
|
||||
@abstract Queries for events of specified type.
|
||||
@param type The type of event to return.
|
||||
@returns An array of events of specified type in order of occurence.
|
||||
*/
|
||||
- (NSArray *)eventsWithType:(POPAnimationEventType)type;
|
||||
|
||||
/**
|
||||
@abstract Property indicating whether tracer should automatically log events and reset collection on animation completion.
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL shouldLogAndResetOnCompletion;
|
||||
|
||||
@end
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPAnimationTracer.h"
|
||||
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
|
||||
#import "POPAnimationEventInternal.h"
|
||||
#import "POPAnimationInternal.h"
|
||||
#import "POPSpringAnimation.h"
|
||||
|
||||
@implementation POPAnimationTracer
|
||||
{
|
||||
__weak POPAnimation *_animation;
|
||||
POPAnimationState *_animationState;
|
||||
NSMutableArray *_events;
|
||||
BOOL _animationHasVelocity;
|
||||
}
|
||||
@synthesize shouldLogAndResetOnCompletion = _shouldLogAndResetOnCompletion;
|
||||
|
||||
static POPAnimationEvent *create_event(POPAnimationTracer *self, POPAnimationEventType type, id value = nil, bool recordAnimation = false)
|
||||
{
|
||||
bool useLocalTime = 0 != self->_animationState->startTime;
|
||||
CFTimeInterval time = useLocalTime
|
||||
? self->_animationState->lastTime - self->_animationState->startTime
|
||||
: self->_animationState->lastTime;
|
||||
|
||||
POPAnimationEvent *event;
|
||||
|
||||
if (!value) {
|
||||
event = [[POPAnimationEvent alloc] initWithType:type time:time];
|
||||
} else {
|
||||
event = [[POPAnimationValueEvent alloc] initWithType:type time:time value:value];
|
||||
if (self->_animationHasVelocity) {
|
||||
[(POPAnimationValueEvent *)event setVelocity:[(POPSpringAnimation *)self->_animation velocity]];
|
||||
}
|
||||
}
|
||||
|
||||
if (recordAnimation) {
|
||||
event.animationDescription = [self->_animation description];
|
||||
}
|
||||
|
||||
return event;
|
||||
}
|
||||
|
||||
- (id)initWithAnimation:(POPAnimation *)anAnim
|
||||
{
|
||||
self = [super init];
|
||||
if (nil != self) {
|
||||
_animation = anAnim;
|
||||
_animationState = POPAnimationGetState(anAnim);
|
||||
_events = [[NSMutableArray alloc] initWithCapacity:50];
|
||||
_animationHasVelocity = [anAnim respondsToSelector:@selector(velocity)];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)readPropertyValue:(id)aValue
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventPropertyRead, aValue);
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)writePropertyValue:(id)aValue
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventPropertyWrite, aValue);
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)updateToValue:(id)aValue
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventToValueUpdate, aValue);
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)updateFromValue:(id)aValue
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventFromValueUpdate, aValue);
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)updateVelocity:(id)aValue
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventVelocityUpdate, aValue);
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)updateSpeed:(float)aFloat
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventSpeedUpdate, @(aFloat));
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)updateBounciness:(float)aFloat
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventBouncinessUpdate, @(aFloat));
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)updateFriction:(float)aFloat
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventFrictionUpdate, @(aFloat));
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)updateMass:(float)aFloat
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventMassUpdate, @(aFloat));
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)updateTension:(float)aFloat
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventTensionUpdate, @(aFloat));
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)didStart
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventDidStart, nil, true);
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)didStop:(BOOL)finished
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventDidStop, @(finished), true);
|
||||
[_events addObject:event];
|
||||
|
||||
if (_shouldLogAndResetOnCompletion) {
|
||||
NSLog(@"events:%@", self.allEvents);
|
||||
[self reset];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)didReachToValue:(id)aValue
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventDidReachToValue, aValue);
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)autoreversed
|
||||
{
|
||||
POPAnimationEvent *event = create_event(self, kPOPAnimationEventAutoreversed);
|
||||
[_events addObject:event];
|
||||
}
|
||||
|
||||
- (void)start
|
||||
{
|
||||
POPAnimationState *s = POPAnimationGetState(_animation);
|
||||
s->tracing = true;
|
||||
}
|
||||
|
||||
- (void)stop
|
||||
{
|
||||
POPAnimationState *s = POPAnimationGetState(_animation);
|
||||
s->tracing = false;
|
||||
}
|
||||
|
||||
- (void)reset
|
||||
{
|
||||
[_events removeAllObjects];
|
||||
}
|
||||
|
||||
- (NSArray *)allEvents
|
||||
{
|
||||
return [_events copy];
|
||||
}
|
||||
|
||||
- (NSArray *)writeEvents
|
||||
{
|
||||
return [self eventsWithType:kPOPAnimationEventPropertyWrite];
|
||||
}
|
||||
|
||||
- (NSArray *)eventsWithType:(POPAnimationEventType)aType
|
||||
{
|
||||
NSMutableArray *array = [NSMutableArray array];
|
||||
for (POPAnimationEvent *event in _events) {
|
||||
if (aType == event.type) {
|
||||
[array addObject:event];
|
||||
}
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
@end
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <pop/POPAnimationTracer.h>
|
||||
|
||||
@interface POPAnimationTracer (Internal)
|
||||
|
||||
/**
|
||||
@abstract Designated initalizer. Pass the animation being traced.
|
||||
*/
|
||||
- (instancetype)initWithAnimation:(POPAnimation *)anAnim;
|
||||
|
||||
/**
|
||||
@abstract Records read value.
|
||||
*/
|
||||
- (void)readPropertyValue:(id)aValue;
|
||||
|
||||
/**
|
||||
@abstract Records write value.
|
||||
*/
|
||||
- (void)writePropertyValue:(id)aValue;
|
||||
|
||||
/**
|
||||
Records to value update.
|
||||
*/
|
||||
- (void)updateToValue:(id)aValue;
|
||||
|
||||
/**
|
||||
@abstract Records from value update.
|
||||
*/
|
||||
- (void)updateFromValue:(id)aValue;
|
||||
|
||||
/**
|
||||
@abstract Records from value update.
|
||||
*/
|
||||
- (void)updateVelocity:(id)aValue;
|
||||
|
||||
/**
|
||||
@abstract Records bounciness update.
|
||||
*/
|
||||
- (void)updateBounciness:(float)aFloat;
|
||||
|
||||
/**
|
||||
@abstract Records speed update.
|
||||
*/
|
||||
- (void)updateSpeed:(float)aFloat;
|
||||
|
||||
/**
|
||||
@abstract Records friction update.
|
||||
*/
|
||||
- (void)updateFriction:(float)aFloat;
|
||||
|
||||
/**
|
||||
@abstract Records mass update.
|
||||
*/
|
||||
- (void)updateMass:(float)aFloat;
|
||||
|
||||
/**
|
||||
@abstract Records tension update.
|
||||
*/
|
||||
- (void)updateTension:(float)aFloat;
|
||||
|
||||
/**
|
||||
@abstract Records did add.
|
||||
*/
|
||||
- (void)didAdd;
|
||||
|
||||
/**
|
||||
@abstract Records did start.
|
||||
*/
|
||||
- (void)didStart;
|
||||
|
||||
/**
|
||||
@abstract Records did stop.
|
||||
*/
|
||||
- (void)didStop:(BOOL)finished;
|
||||
|
||||
/**
|
||||
@abstract Records did reach to value.
|
||||
*/
|
||||
- (void)didReachToValue:(id)aValue;
|
||||
|
||||
/**
|
||||
@abstract Records when an autoreverse animation takes place.
|
||||
*/
|
||||
- (void)autoreversed;
|
||||
|
||||
@end
|
||||
Generated
+47
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <Foundation/NSObject.h>
|
||||
|
||||
@protocol POPAnimatorDelegate;
|
||||
|
||||
/**
|
||||
@abstract The animator class renders animations.
|
||||
*/
|
||||
@interface POPAnimator : NSObject
|
||||
|
||||
/**
|
||||
@abstract The shared animator instance.
|
||||
@discussion Consumers should generally use the shared instance in lieu of creating new instances.
|
||||
*/
|
||||
+ (instancetype)sharedAnimator;
|
||||
|
||||
/**
|
||||
@abstract The optional animator delegate.
|
||||
*/
|
||||
@property (weak, nonatomic) id<POPAnimatorDelegate> delegate;
|
||||
|
||||
@end
|
||||
|
||||
/**
|
||||
@abstract The animator delegate.
|
||||
*/
|
||||
@protocol POPAnimatorDelegate <NSObject>
|
||||
|
||||
/**
|
||||
@abstract Called on each frame before animation application.
|
||||
*/
|
||||
- (void)animatorWillAnimate:(POPAnimator *)animator;
|
||||
|
||||
/**
|
||||
@abstract Called on each frame after animation application.
|
||||
*/
|
||||
- (void)animatorDidAnimate:(POPAnimator *)animator;
|
||||
|
||||
@end
|
||||
Generated
+794
@@ -0,0 +1,794 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPAnimator.h"
|
||||
#import "POPAnimatorPrivate.h"
|
||||
|
||||
#import <list>
|
||||
#import <objc/objc-auto.h>
|
||||
#import <vector>
|
||||
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
|
||||
#import "POPAnimation.h"
|
||||
#import "POPAnimationExtras.h"
|
||||
#import "POPBasicAnimationInternal.h"
|
||||
#import "POPDecayAnimation.h"
|
||||
|
||||
using namespace std;
|
||||
using namespace POP;
|
||||
|
||||
#define ENABLE_LOGGING_DEBUG 0
|
||||
#define ENABLE_LOGGING_INFO 0
|
||||
|
||||
#if ENABLE_LOGGING_DEBUG
|
||||
#define FBLogAnimDebug NSLog
|
||||
#else
|
||||
#define FBLogAnimDebug(...)
|
||||
#endif
|
||||
|
||||
#if ENABLE_LOGGING_INFO
|
||||
#define FBLogAnimInfo NSLog
|
||||
#else
|
||||
#define FBLogAnimInfo(...)
|
||||
#endif
|
||||
|
||||
class POPAnimatorItem
|
||||
{
|
||||
public:
|
||||
id __weak object;
|
||||
NSString *key;
|
||||
POPAnimation *animation;
|
||||
NSInteger refCount;
|
||||
id __unsafe_unretained unretainedObject;
|
||||
|
||||
POPAnimatorItem(id o, NSString *k, POPAnimation *a) POP_NOTHROW
|
||||
{
|
||||
object = o;
|
||||
key = [k copy];
|
||||
animation = a;
|
||||
refCount = 1;
|
||||
unretainedObject = o;
|
||||
}
|
||||
|
||||
~POPAnimatorItem()
|
||||
{
|
||||
}
|
||||
|
||||
bool operator==(const POPAnimatorItem& o) const {
|
||||
return unretainedObject == o.unretainedObject && animation == o.animation && [key isEqualToString:o.key];
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
typedef std::shared_ptr<POPAnimatorItem> POPAnimatorItemRef;
|
||||
typedef std::shared_ptr<const POPAnimatorItem> POPAnimatorItemConstRef;
|
||||
|
||||
typedef std::list<POPAnimatorItemRef> POPAnimatorItemList;
|
||||
typedef POPAnimatorItemList::iterator POPAnimatorItemListIterator;
|
||||
typedef POPAnimatorItemList::const_iterator POPAnimatorItemListConstIterator;
|
||||
|
||||
static BOOL _disableBackgroundThread = YES;
|
||||
|
||||
@interface POPAnimator ()
|
||||
{
|
||||
#if TARGET_OS_IPHONE
|
||||
CADisplayLink *_displayLink;
|
||||
#else
|
||||
CVDisplayLinkRef _displayLink;
|
||||
#endif
|
||||
POPAnimatorItemList _list;
|
||||
CFMutableDictionaryRef _dict;
|
||||
NSMutableArray *_observers;
|
||||
POPAnimatorItemList _pendingList;
|
||||
CFRunLoopObserverRef _pendingListObserver;
|
||||
CFTimeInterval _slowMotionStartTime;
|
||||
CFTimeInterval _slowMotionLastTime;
|
||||
CFTimeInterval _slowMotionAccumulator;
|
||||
CFTimeInterval _beginTime;
|
||||
OSSpinLock _lock;
|
||||
BOOL _disableDisplayLink;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation POPAnimator
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize disableDisplayLink = _disableDisplayLink;
|
||||
@synthesize beginTime = _beginTime;
|
||||
|
||||
#if !TARGET_OS_IPHONE
|
||||
static CVReturn displayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp *now, const CVTimeStamp *outputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *context)
|
||||
{
|
||||
if (_disableBackgroundThread) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[(__bridge POPAnimator*)context render];
|
||||
});
|
||||
} else {
|
||||
[(__bridge POPAnimator*)context render];
|
||||
}
|
||||
return kCVReturnSuccess;
|
||||
}
|
||||
#endif
|
||||
|
||||
// call while holding lock
|
||||
static void updateDisplayLink(POPAnimator *self)
|
||||
{
|
||||
BOOL paused = (0 == self->_observers.count && self->_list.empty()) || self->_disableDisplayLink;
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
if (paused != self->_displayLink.paused) {
|
||||
FBLogAnimInfo(paused ? @"pausing display link" : @"unpausing display link");
|
||||
self->_displayLink.paused = paused;
|
||||
}
|
||||
#else
|
||||
if (paused == CVDisplayLinkIsRunning(self->_displayLink)) {
|
||||
FBLogAnimInfo(paused ? @"pausing display link" : @"unpausing display link");
|
||||
if (paused) {
|
||||
CVDisplayLinkStop(self->_displayLink);
|
||||
} else {
|
||||
CVDisplayLinkStart(self->_displayLink);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
static void updateAnimatable(id obj, POPPropertyAnimationState *anim, bool shouldAvoidExtraneousWrite = false)
|
||||
{
|
||||
// handle user-initiated stop or pause; hault animation
|
||||
if (!anim->active || anim->paused)
|
||||
return;
|
||||
|
||||
if (anim->hasValue()) {
|
||||
pop_animatable_write_block write = anim->property.writeBlock;
|
||||
if (NULL == write)
|
||||
return;
|
||||
|
||||
// current animation value
|
||||
VectorRef currentVec = anim->currentValue();
|
||||
|
||||
if (!anim->additive) {
|
||||
|
||||
// if avoiding extraneous writes and we have a read block defined
|
||||
if (shouldAvoidExtraneousWrite) {
|
||||
|
||||
pop_animatable_read_block read = anim->property.readBlock;
|
||||
if (read) {
|
||||
// compare current animation value with object value
|
||||
Vector4r currentValue = currentVec->vector4r();
|
||||
Vector4r objectValue = read_values(read, obj, anim->valueCount);
|
||||
if (objectValue == currentValue) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// update previous values; support animation convergence
|
||||
anim->previous2Vec = anim->previousVec;
|
||||
anim->previousVec = currentVec;
|
||||
|
||||
// write value
|
||||
write(obj, currentVec->data());
|
||||
if (anim->tracing) {
|
||||
[anim->tracer writePropertyValue:POPBox(currentVec, anim->valueType, true)];
|
||||
}
|
||||
} else {
|
||||
pop_animatable_read_block read = anim->property.readBlock;
|
||||
NSCAssert(read, @"additive requires an animatable property readBlock");
|
||||
if (NULL == read) {
|
||||
return;
|
||||
}
|
||||
|
||||
// object value
|
||||
Vector4r objectValue = read_values(read, obj, anim->valueCount);
|
||||
|
||||
// current value
|
||||
Vector4r currentValue = currentVec->vector4r();
|
||||
|
||||
// determine animation change
|
||||
if (anim->previousVec) {
|
||||
Vector4r previousValue = anim->previousVec->vector4r();
|
||||
currentValue -= previousValue;
|
||||
}
|
||||
|
||||
// avoid writing no change
|
||||
if (shouldAvoidExtraneousWrite && currentValue == Vector4r::Zero()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// add to object value
|
||||
currentValue += objectValue;
|
||||
|
||||
// update previous values; support animation convergence
|
||||
anim->previous2Vec = anim->previousVec;
|
||||
anim->previousVec = currentVec;
|
||||
|
||||
// write value
|
||||
write(obj, currentValue.data());
|
||||
if (anim->tracing) {
|
||||
[anim->tracer writePropertyValue:POPBox(currentVec, anim->valueType, true)];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void applyAnimationTime(id obj, POPAnimationState *state, CFTimeInterval time)
|
||||
{
|
||||
if (!state->advanceTime(time, obj)) {
|
||||
return;
|
||||
}
|
||||
|
||||
POPPropertyAnimationState *ps = dynamic_cast<POPPropertyAnimationState*>(state);
|
||||
if (NULL != ps) {
|
||||
updateAnimatable(obj, ps);
|
||||
}
|
||||
|
||||
state->delegateApply();
|
||||
}
|
||||
|
||||
static void applyAnimationToValue(id obj, POPAnimationState *state)
|
||||
{
|
||||
POPPropertyAnimationState *ps = dynamic_cast<POPPropertyAnimationState*>(state);
|
||||
|
||||
if (NULL != ps) {
|
||||
|
||||
// finalize progress
|
||||
ps->finalizeProgress();
|
||||
|
||||
// write to value, updating only if needed
|
||||
updateAnimatable(obj, ps, true);
|
||||
}
|
||||
|
||||
state->delegateApply();
|
||||
}
|
||||
|
||||
static POPAnimation *deleteDictEntry(POPAnimator *self, id __unsafe_unretained obj, NSString *key, BOOL cleanup = YES)
|
||||
{
|
||||
POPAnimation *anim = nil;
|
||||
|
||||
// lock
|
||||
OSSpinLockLock(&self->_lock);
|
||||
|
||||
NSMutableDictionary *keyAnimationsDict = (__bridge id)CFDictionaryGetValue(self->_dict, (__bridge void *)obj);
|
||||
if (keyAnimationsDict) {
|
||||
|
||||
anim = keyAnimationsDict[key];
|
||||
if (anim) {
|
||||
|
||||
// remove key
|
||||
[keyAnimationsDict removeObjectForKey:key];
|
||||
|
||||
// cleanup empty dictionaries
|
||||
if (cleanup && 0 == keyAnimationsDict.count) {
|
||||
CFDictionaryRemoveValue(self->_dict, (__bridge void *)obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&self->_lock);
|
||||
return anim;
|
||||
}
|
||||
|
||||
static void stopAndCleanup(POPAnimator *self, POPAnimatorItemRef item, bool shouldRemove, bool finished)
|
||||
{
|
||||
// remove
|
||||
if (shouldRemove) {
|
||||
deleteDictEntry(self, item->unretainedObject, item->key);
|
||||
}
|
||||
|
||||
// stop
|
||||
POPAnimationState *state = POPAnimationGetState(item->animation);
|
||||
state->stop(shouldRemove, finished);
|
||||
|
||||
if (shouldRemove) {
|
||||
// lock
|
||||
OSSpinLockLock(&self->_lock);
|
||||
|
||||
// find item in list
|
||||
// may have already been removed on animationDidStop:
|
||||
POPAnimatorItemListIterator find_iter = find(self->_list.begin(), self->_list.end(), item);
|
||||
BOOL found = find_iter != self->_list.end();
|
||||
|
||||
if (found) {
|
||||
self->_list.erase(find_iter);
|
||||
}
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&self->_lock);
|
||||
}
|
||||
}
|
||||
|
||||
+ (id)sharedAnimator
|
||||
{
|
||||
static POPAnimator* _animator = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
_animator = [[POPAnimator alloc] init];
|
||||
});
|
||||
return _animator;
|
||||
}
|
||||
|
||||
+ (BOOL)disableBackgroundThread
|
||||
{
|
||||
return _disableBackgroundThread;
|
||||
}
|
||||
|
||||
+ (void)setDisableBackgroundThread:(BOOL)flag
|
||||
{
|
||||
_disableBackgroundThread = flag;
|
||||
}
|
||||
|
||||
#pragma mark - Lifecycle
|
||||
|
||||
- (id)init
|
||||
{
|
||||
self = [super init];
|
||||
if (nil == self) return nil;
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(render)];
|
||||
_displayLink.paused = YES;
|
||||
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
|
||||
#else
|
||||
CVDisplayLinkCreateWithActiveCGDisplays(&_displayLink);
|
||||
CVDisplayLinkSetOutputCallback(_displayLink, displayLinkCallback, (__bridge void *)self);
|
||||
#endif
|
||||
|
||||
_dict = POPDictionaryCreateMutableWeakPointerToStrongObject(5);
|
||||
_lock = OS_SPINLOCK_INIT;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
#if TARGET_OS_IPHONE
|
||||
[_displayLink invalidate];
|
||||
#else
|
||||
CVDisplayLinkStop(_displayLink);
|
||||
CVDisplayLinkRelease(_displayLink);
|
||||
#endif
|
||||
[self _clearPendingListObserver];
|
||||
}
|
||||
|
||||
#pragma mark - Utility
|
||||
|
||||
- (void)_processPendingList
|
||||
{
|
||||
// rendering pending animations
|
||||
CFTimeInterval time = [self _currentRenderTime];
|
||||
[self _renderTime:(0 != _beginTime) ? _beginTime : time items:_pendingList];
|
||||
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
// clear list and observer
|
||||
_pendingList.clear();
|
||||
[self _clearPendingListObserver];
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
}
|
||||
|
||||
- (void)_clearPendingListObserver
|
||||
{
|
||||
if (_pendingListObserver) {
|
||||
CFRunLoopRemoveObserver(CFRunLoopGetMain(), _pendingListObserver, kCFRunLoopCommonModes);
|
||||
CFRelease(_pendingListObserver);
|
||||
_pendingListObserver = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_scheduleProcessPendingList
|
||||
{
|
||||
// see WebKit for magic numbers, eg http://trac.webkit.org/changeset/166540
|
||||
static const CFIndex CATransactionCommitRunLoopOrder = 2000000;
|
||||
static const CFIndex POPAnimationApplyRunLoopOrder = CATransactionCommitRunLoopOrder - 1;
|
||||
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
if (!_pendingListObserver) {
|
||||
__weak POPAnimator *weakSelf = self;
|
||||
|
||||
_pendingListObserver = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopBeforeWaiting | kCFRunLoopExit, false, POPAnimationApplyRunLoopOrder, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
|
||||
[weakSelf _processPendingList];
|
||||
});
|
||||
|
||||
if (_pendingListObserver) {
|
||||
CFRunLoopAddObserver(CFRunLoopGetMain(), _pendingListObserver, kCFRunLoopCommonModes);
|
||||
}
|
||||
}
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
}
|
||||
|
||||
- (void)_renderTime:(CFTimeInterval)time items:(std::list<POPAnimatorItemRef>)items
|
||||
{
|
||||
// begin transaction with actions disabled
|
||||
[CATransaction begin];
|
||||
[CATransaction setDisableActions:YES];
|
||||
|
||||
// notify delegate
|
||||
__strong __typeof__(_delegate) delegate = _delegate;
|
||||
[delegate animatorWillAnimate:self];
|
||||
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
// count active animations
|
||||
const NSUInteger count = items.size();
|
||||
if (0 == count) {
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
} else {
|
||||
// copy list into vectory
|
||||
std::vector<POPAnimatorItemRef> vector{ std::begin(items), std::end(items) };
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
|
||||
for (auto item : vector) {
|
||||
[self _renderTime:time item:item];
|
||||
}
|
||||
}
|
||||
|
||||
// notify observers
|
||||
for (id observer in self.observers) {
|
||||
[observer animatorDidAnimate:(id)self];
|
||||
}
|
||||
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
// update display link
|
||||
updateDisplayLink(self);
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
|
||||
// notify delegate and commit
|
||||
[delegate animatorDidAnimate:self];
|
||||
[CATransaction commit];
|
||||
}
|
||||
|
||||
- (void)_renderTime:(CFTimeInterval)time item:(POPAnimatorItemRef)item
|
||||
{
|
||||
id obj = item->object;
|
||||
POPAnimation *anim = item->animation;
|
||||
POPAnimationState *state = POPAnimationGetState(anim);
|
||||
|
||||
if (nil == obj) {
|
||||
// object exists not; stop animating
|
||||
NSAssert(item->unretainedObject, @"object should exist");
|
||||
stopAndCleanup(self, item, true, false);
|
||||
} else {
|
||||
|
||||
// start if needed
|
||||
state->startIfNeeded(obj, time, _slowMotionAccumulator);
|
||||
|
||||
// only run active, not paused animations
|
||||
if (state->active && !state->paused) {
|
||||
// object exists; animate
|
||||
applyAnimationTime(obj, state, time);
|
||||
|
||||
FBLogAnimDebug(@"time:%f running:%@", time, item->animation);
|
||||
if (state->isDone()) {
|
||||
// set end value
|
||||
applyAnimationToValue(obj, state);
|
||||
|
||||
state->repeatCount--;
|
||||
if (state->repeatForever || state->repeatCount > 0) {
|
||||
if ([anim isKindOfClass:[POPPropertyAnimation class]]) {
|
||||
POPPropertyAnimation *propAnim = (POPPropertyAnimation *)anim;
|
||||
id oldFromValue = propAnim.fromValue;
|
||||
propAnim.fromValue = propAnim.toValue;
|
||||
|
||||
if (state->autoreverses) {
|
||||
if (state->tracing) {
|
||||
[state->tracer autoreversed];
|
||||
}
|
||||
|
||||
if (state->type == kPOPAnimationDecay) {
|
||||
POPDecayAnimation *decayAnimation = (POPDecayAnimation *)propAnim;
|
||||
decayAnimation.velocity = [decayAnimation reversedVelocity];
|
||||
} else {
|
||||
propAnim.toValue = oldFromValue;
|
||||
}
|
||||
} else {
|
||||
if (state->type == kPOPAnimationDecay) {
|
||||
POPDecayAnimation *decayAnimation = (POPDecayAnimation *)propAnim;
|
||||
id originalVelocity = decayAnimation.originalVelocity;
|
||||
decayAnimation.velocity = originalVelocity;
|
||||
} else {
|
||||
propAnim.fromValue = oldFromValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
state->stop(NO, NO);
|
||||
state->reset(true);
|
||||
|
||||
state->startIfNeeded(obj, time, _slowMotionAccumulator);
|
||||
} else {
|
||||
stopAndCleanup(self, item, state->removedOnCompletion, YES);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - API
|
||||
|
||||
- (NSArray *)observers
|
||||
{
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
// get observers
|
||||
NSArray *observers = 0 != _observers.count ? [_observers copy] : nil;
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
return observers;
|
||||
}
|
||||
|
||||
- (void)addAnimation:(POPAnimation *)anim forObject:(id)obj key:(NSString *)key
|
||||
{
|
||||
if (!anim || !obj) {
|
||||
return;
|
||||
}
|
||||
|
||||
// support arbitrarily many nil keys
|
||||
if (!key) {
|
||||
key = [[NSUUID UUID] UUIDString];
|
||||
}
|
||||
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
// get key, animation dict associated with object
|
||||
NSMutableDictionary *keyAnimationDict = (__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj);
|
||||
|
||||
// update associated animation state
|
||||
if (nil == keyAnimationDict) {
|
||||
keyAnimationDict = [NSMutableDictionary dictionary];
|
||||
CFDictionarySetValue(_dict, (__bridge void *)obj, (__bridge void *)keyAnimationDict);
|
||||
} else {
|
||||
// if the animation instance already exists, avoid cancelling only to restart
|
||||
POPAnimation *existingAnim = keyAnimationDict[key];
|
||||
if (existingAnim) {
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
|
||||
if (existingAnim == anim) {
|
||||
return;
|
||||
}
|
||||
[self removeAnimationForObject:obj key:key cleanupDict:NO];
|
||||
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
}
|
||||
}
|
||||
keyAnimationDict[key] = anim;
|
||||
|
||||
// create entry after potential removal
|
||||
POPAnimatorItemRef item(new POPAnimatorItem(obj, key, anim));
|
||||
|
||||
// add to list and pending list
|
||||
_list.push_back(item);
|
||||
_pendingList.push_back(item);
|
||||
|
||||
// support animation re-use, reset all animation state
|
||||
POPAnimationGetState(anim)->reset(true);
|
||||
|
||||
// update display link
|
||||
updateDisplayLink(self);
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
|
||||
// schedule runloop processing of pending animations
|
||||
[self _scheduleProcessPendingList];
|
||||
}
|
||||
|
||||
- (void)removeAllAnimationsForObject:(id)obj
|
||||
{
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
NSArray *animations = [(__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj) allValues];
|
||||
CFDictionaryRemoveValue(_dict, (__bridge void *)obj);
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
|
||||
if (0 == animations.count) {
|
||||
return;
|
||||
}
|
||||
|
||||
NSHashTable *animationSet = [[NSHashTable alloc] initWithOptions:NSHashTableObjectPointerPersonality capacity:animations.count];
|
||||
for (id animation in animations) {
|
||||
[animationSet addObject:animation];
|
||||
}
|
||||
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
POPAnimatorItemRef item;
|
||||
for (auto iter = _list.begin(); iter != _list.end();) {
|
||||
item = *iter;
|
||||
if(![animationSet containsObject:item->animation]) {
|
||||
iter++;
|
||||
} else {
|
||||
iter = _list.erase(iter);
|
||||
}
|
||||
}
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
|
||||
for (POPAnimation *anim in animations) {
|
||||
POPAnimationState *state = POPAnimationGetState(anim);
|
||||
state->stop(true, !state->active);
|
||||
}
|
||||
}
|
||||
|
||||
- (void)removeAnimationForObject:(id)obj key:(NSString *)key cleanupDict:(BOOL)cleanupDict
|
||||
{
|
||||
POPAnimation *anim = deleteDictEntry(self, obj, key, cleanupDict);
|
||||
if (nil == anim) {
|
||||
return;
|
||||
}
|
||||
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
// remove from list
|
||||
POPAnimatorItemRef item;
|
||||
for (auto iter = _list.begin(); iter != _list.end();) {
|
||||
item = *iter;
|
||||
if(anim == item->animation) {
|
||||
_list.erase(iter);
|
||||
break;
|
||||
} else {
|
||||
iter++;
|
||||
}
|
||||
}
|
||||
|
||||
// remove from pending list
|
||||
for (auto iter = _pendingList.begin(); iter != _pendingList.end();) {
|
||||
item = *iter;
|
||||
if(anim == item->animation) {
|
||||
_pendingList.erase(iter);
|
||||
break;
|
||||
} else {
|
||||
iter++;
|
||||
}
|
||||
}
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
|
||||
// stop animation and callout
|
||||
POPAnimationState *state = POPAnimationGetState(anim);
|
||||
state->stop(true, (!state->active && !state->paused));
|
||||
}
|
||||
|
||||
- (void)removeAnimationForObject:(id)obj key:(NSString *)key
|
||||
{
|
||||
[self removeAnimationForObject:obj key:key cleanupDict:YES];
|
||||
}
|
||||
|
||||
- (NSArray *)animationKeysForObject:(id)obj
|
||||
{
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
// get keys
|
||||
NSArray *keys = [(__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj) allKeys];
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
return keys;
|
||||
}
|
||||
|
||||
- (id)animationForObject:(id)obj key:(NSString *)key
|
||||
{
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
// lookup animation
|
||||
NSDictionary *keyAnimationsDict = (__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj);
|
||||
POPAnimation *animation = keyAnimationsDict[key];
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
return animation;
|
||||
}
|
||||
|
||||
- (CFTimeInterval)_currentRenderTime
|
||||
{
|
||||
CFTimeInterval time = CACurrentMediaTime();
|
||||
|
||||
#if TARGET_IPHONE_SIMULATOR
|
||||
// support slow-motion animations
|
||||
time += _slowMotionAccumulator;
|
||||
float f = POPAnimationDragCoefficient();
|
||||
|
||||
if (f > 1.0) {
|
||||
if (!_slowMotionStartTime) {
|
||||
_slowMotionStartTime = time;
|
||||
} else {
|
||||
time = (time - _slowMotionStartTime) / f + _slowMotionStartTime;
|
||||
_slowMotionLastTime = time;
|
||||
}
|
||||
} else if (_slowMotionStartTime) {
|
||||
CFTimeInterval dt = (_slowMotionLastTime - time);
|
||||
time += dt;
|
||||
_slowMotionAccumulator += dt;
|
||||
_slowMotionStartTime = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
return time;
|
||||
}
|
||||
|
||||
- (void)render
|
||||
{
|
||||
CFTimeInterval time = [self _currentRenderTime];
|
||||
[self renderTime:time];
|
||||
}
|
||||
|
||||
- (void)renderTime:(CFTimeInterval)time
|
||||
{
|
||||
[self _renderTime:time items:_list];
|
||||
}
|
||||
|
||||
- (void)addObserver:(id<POPAnimatorObserving>)observer
|
||||
{
|
||||
NSAssert(nil != observer, @"attempting to add nil %@ observer", self);
|
||||
if (nil == observer) {
|
||||
return;
|
||||
}
|
||||
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
if (!_observers) {
|
||||
// use ordered collection for deterministic callout
|
||||
_observers = [[NSMutableArray alloc] initWithCapacity:1];
|
||||
}
|
||||
|
||||
[_observers addObject:observer];
|
||||
updateDisplayLink(self);
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
}
|
||||
|
||||
- (void)removeObserver:(id<POPAnimatorObserving>)observer
|
||||
{
|
||||
NSAssert(nil != observer, @"attempting to remove nil %@ observer", self);
|
||||
if (nil == observer) {
|
||||
return;
|
||||
}
|
||||
|
||||
// lock
|
||||
OSSpinLockLock(&_lock);
|
||||
|
||||
[_observers removeObject:observer];
|
||||
updateDisplayLink(self);
|
||||
|
||||
// unlock
|
||||
OSSpinLockUnlock(&_lock);
|
||||
}
|
||||
|
||||
@end
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <pop/POPAnimator.h>
|
||||
|
||||
@class POPAnimation;
|
||||
|
||||
@protocol POPAnimatorObserving <NSObject>
|
||||
@required
|
||||
|
||||
/**
|
||||
@abstract Called on each observer after animator has advanced. Core Animation actions are disabled by default.
|
||||
*/
|
||||
- (void)animatorDidAnimate:(POPAnimator *)animator;
|
||||
|
||||
@end
|
||||
|
||||
@interface POPAnimator ()
|
||||
|
||||
#if !TARGET_OS_IPHONE
|
||||
/**
|
||||
Determines whether or not to use a high priority background thread for animation updates. Using a background thread can result in faster, more responsive updates, but may be less compatible. Defaults to YES.
|
||||
*/
|
||||
+ (BOOL)disableBackgroundThread;
|
||||
+ (void)setDisableBackgroundThread:(BOOL)flag;
|
||||
#endif
|
||||
|
||||
/**
|
||||
Used for externally driven animator instances.
|
||||
*/
|
||||
@property (assign, nonatomic) BOOL disableDisplayLink;
|
||||
|
||||
/**
|
||||
Time used when starting animations. Defaults to 0 meaning current media time is used. Exposed for unit testing.
|
||||
*/
|
||||
@property (assign, nonatomic) CFTimeInterval beginTime;
|
||||
|
||||
/**
|
||||
Exposed for unit testing.
|
||||
*/
|
||||
- (void)renderTime:(CFTimeInterval)time;
|
||||
|
||||
/**
|
||||
Funnel methods for category additions.
|
||||
*/
|
||||
- (void)addAnimation:(POPAnimation *)anim forObject:(id)obj key:(NSString *)key;
|
||||
- (void)removeAllAnimationsForObject:(id)obj;
|
||||
- (void)removeAnimationForObject:(id)obj key:(NSString *)key;
|
||||
- (NSArray *)animationKeysForObject:(id)obj;
|
||||
- (POPAnimation *)animationForObject:(id)obj key:(NSString *)key;
|
||||
|
||||
/**
|
||||
@abstract Add an animator observer. Observer will be notified of each subsequent animator advance until removal.
|
||||
*/
|
||||
- (void)addObserver:(id<POPAnimatorObserving>)observer;
|
||||
|
||||
/**
|
||||
@abstract Remove an animator observer.
|
||||
*/
|
||||
- (void)removeObserver:(id<POPAnimatorObserving>)observer;
|
||||
|
||||
@end
|
||||
Generated
+71
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <pop/POPPropertyAnimation.h>
|
||||
|
||||
/**
|
||||
@abstract A concrete basic animation class.
|
||||
@discussion Animation is achieved through interpolation.
|
||||
*/
|
||||
@interface POPBasicAnimation : POPPropertyAnimation
|
||||
|
||||
/**
|
||||
@abstract The designated initializer.
|
||||
@returns An instance of a basic animation.
|
||||
*/
|
||||
+ (instancetype)animation;
|
||||
|
||||
/**
|
||||
@abstract Convenience initializer that returns an animation with animatable property of name.
|
||||
@param name The name of the animatable property.
|
||||
@returns An instance of a basic animation configured with specified animatable property.
|
||||
*/
|
||||
+ (instancetype)animationWithPropertyNamed:(NSString *)name;
|
||||
|
||||
/**
|
||||
@abstract Convenience constructor.
|
||||
@returns Returns a basic animation with kCAMediaTimingFunctionDefault timing function.
|
||||
*/
|
||||
+ (instancetype)defaultAnimation;
|
||||
|
||||
/**
|
||||
@abstract Convenience constructor.
|
||||
@returns Returns a basic animation with kCAMediaTimingFunctionLinear timing function.
|
||||
*/
|
||||
+ (instancetype)linearAnimation;
|
||||
|
||||
/**
|
||||
@abstract Convenience constructor.
|
||||
@returns Returns a basic animation with kCAMediaTimingFunctionEaseIn timing function.
|
||||
*/
|
||||
+ (instancetype)easeInAnimation;
|
||||
|
||||
/**
|
||||
@abstract Convenience constructor.
|
||||
@returns Returns a basic animation with kCAMediaTimingFunctionEaseOut timing function.
|
||||
*/
|
||||
+ (instancetype)easeOutAnimation;
|
||||
|
||||
/**
|
||||
@abstract Convenience constructor.
|
||||
@returns Returns a basic animation with kCAMediaTimingFunctionEaseInEaseOut timing function.
|
||||
*/
|
||||
+ (instancetype)easeInEaseOutAnimation;
|
||||
|
||||
/**
|
||||
@abstract The duration in seconds. Defaults to 0.4.
|
||||
*/
|
||||
@property (assign, nonatomic) CFTimeInterval duration;
|
||||
|
||||
/**
|
||||
@abstract A timing function defining the pacing of the animation. Defaults to nil indicating pacing according to kCAMediaTimingFunctionDefault.
|
||||
*/
|
||||
@property (strong, nonatomic) CAMediaTimingFunction *timingFunction;
|
||||
|
||||
@end
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPBasicAnimationInternal.h"
|
||||
|
||||
@implementation POPBasicAnimation
|
||||
|
||||
#undef __state
|
||||
#define __state ((POPBasicAnimationState *)_state)
|
||||
|
||||
#pragma mark - Lifecycle
|
||||
|
||||
+ (instancetype)animation
|
||||
{
|
||||
return [[self alloc] init];
|
||||
}
|
||||
|
||||
+ (instancetype)animationWithPropertyNamed:(NSString *)aName
|
||||
{
|
||||
POPBasicAnimation *anim = [self animation];
|
||||
anim.property = [POPAnimatableProperty propertyWithName:aName];
|
||||
return anim;
|
||||
}
|
||||
|
||||
- (void)_initState
|
||||
{
|
||||
_state = new POPBasicAnimationState(self);
|
||||
}
|
||||
|
||||
+ (instancetype)linearAnimation
|
||||
{
|
||||
POPBasicAnimation *anim = [self animation];
|
||||
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
|
||||
return anim;
|
||||
}
|
||||
|
||||
+ (instancetype)easeInAnimation
|
||||
{
|
||||
POPBasicAnimation *anim = [self animation];
|
||||
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
|
||||
return anim;
|
||||
}
|
||||
|
||||
+ (instancetype)easeOutAnimation
|
||||
{
|
||||
POPBasicAnimation *anim = [self animation];
|
||||
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
|
||||
return anim;
|
||||
}
|
||||
|
||||
+ (instancetype)easeInEaseOutAnimation
|
||||
{
|
||||
POPBasicAnimation *anim = [self animation];
|
||||
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
|
||||
return anim;
|
||||
}
|
||||
|
||||
+ (instancetype)defaultAnimation
|
||||
{
|
||||
POPBasicAnimation *anim = [self animation];
|
||||
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
|
||||
return anim;
|
||||
}
|
||||
|
||||
- (id)init
|
||||
{
|
||||
return [self _init];
|
||||
}
|
||||
|
||||
#pragma mark - Properties
|
||||
|
||||
DEFINE_RW_PROPERTY(POPBasicAnimationState, duration, setDuration:, CFTimeInterval);
|
||||
DEFINE_RW_PROPERTY_OBJ(POPBasicAnimationState, timingFunction, setTimingFunction:, CAMediaTimingFunction*, __state->updatedTimingFunction(););
|
||||
|
||||
#pragma mark - Utility
|
||||
|
||||
- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug
|
||||
{
|
||||
[super _appendDescription:s debug:debug];
|
||||
if (__state->duration)
|
||||
[s appendFormat:@"; duration = %f", __state->duration];
|
||||
}
|
||||
|
||||
@end
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPBasicAnimation.h"
|
||||
#import "POPPropertyAnimationInternal.h"
|
||||
|
||||
// default animation duration
|
||||
static CGFloat const kPOPAnimationDurationDefault = 0.4;
|
||||
|
||||
// progress threshold for computing done
|
||||
static CGFloat const kPOPProgressThreshold = 1e-6;
|
||||
|
||||
static void interpolate(POPValueType valueType, NSUInteger count, const CGFloat *fromVec, const CGFloat *toVec, CGFloat *outVec, CGFloat p)
|
||||
{
|
||||
switch (valueType) {
|
||||
case kPOPValueInteger:
|
||||
case kPOPValueFloat:
|
||||
case kPOPValuePoint:
|
||||
case kPOPValueSize:
|
||||
case kPOPValueRect:
|
||||
case kPOPValueEdgeInsets:
|
||||
case kPOPValueColor:
|
||||
POPInterpolateVector(count, outVec, fromVec, toVec, p);
|
||||
break;
|
||||
default:
|
||||
NSCAssert(false, @"unhandled type %d", valueType);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
struct _POPBasicAnimationState : _POPPropertyAnimationState
|
||||
{
|
||||
CAMediaTimingFunction *timingFunction;
|
||||
double timingControlPoints[4];
|
||||
CFTimeInterval duration;
|
||||
CFTimeInterval timeProgress;
|
||||
|
||||
_POPBasicAnimationState(id __unsafe_unretained anim) : _POPPropertyAnimationState(anim),
|
||||
timingFunction(nil),
|
||||
timingControlPoints{0.},
|
||||
duration(kPOPAnimationDurationDefault),
|
||||
timeProgress(0.)
|
||||
{
|
||||
type = kPOPAnimationBasic;
|
||||
}
|
||||
|
||||
bool isDone() {
|
||||
if (_POPPropertyAnimationState::isDone()) {
|
||||
return true;
|
||||
}
|
||||
return timeProgress + kPOPProgressThreshold >= 1.;
|
||||
}
|
||||
|
||||
void updatedTimingFunction()
|
||||
{
|
||||
float vec[4] = {0.};
|
||||
[timingFunction getControlPointAtIndex:1 values:&vec[0]];
|
||||
[timingFunction getControlPointAtIndex:2 values:&vec[2]];
|
||||
for (NSUInteger idx = 0; idx < POP_ARRAY_COUNT(vec); idx++) {
|
||||
timingControlPoints[idx] = vec[idx];
|
||||
}
|
||||
}
|
||||
|
||||
bool advance(CFTimeInterval time, CFTimeInterval dt, id obj) {
|
||||
// default timing function
|
||||
if (!timingFunction) {
|
||||
((POPBasicAnimation *)self).timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
|
||||
}
|
||||
|
||||
// solve for normalized time, aka progresss [0, 1]
|
||||
CGFloat p = 1.0f;
|
||||
if (duration > 0.0f) {
|
||||
// cap local time to duration
|
||||
CFTimeInterval t = MIN(time - startTime, duration) / duration;
|
||||
p = POPTimingFunctionSolve(timingControlPoints, t, SOLVE_EPS(duration));
|
||||
timeProgress = t;
|
||||
} else {
|
||||
timeProgress = 1.;
|
||||
}
|
||||
|
||||
// interpolate and advance
|
||||
interpolate(valueType, valueCount, fromVec->data(), toVec->data(), currentVec->data(), p);
|
||||
progress = p;
|
||||
clampCurrentValue();
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
typedef struct _POPBasicAnimationState POPBasicAnimationState;
|
||||
Generated
+107
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
#if TARGET_OS_IPHONE
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
||||
#import "POPDefines.h"
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
@class UIColor;
|
||||
#endif
|
||||
|
||||
POP_EXTERN_C_BEGIN
|
||||
|
||||
NS_INLINE CGPoint values_to_point(const CGFloat values[])
|
||||
{
|
||||
return CGPointMake(values[0], values[1]);
|
||||
}
|
||||
|
||||
NS_INLINE CGSize values_to_size(const CGFloat values[])
|
||||
{
|
||||
return CGSizeMake(values[0], values[1]);
|
||||
}
|
||||
|
||||
NS_INLINE CGRect values_to_rect(const CGFloat values[])
|
||||
{
|
||||
return CGRectMake(values[0], values[1], values[2], values[3]);
|
||||
}
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
|
||||
NS_INLINE UIEdgeInsets values_to_edge_insets(const CGFloat values[])
|
||||
{
|
||||
return UIEdgeInsetsMake(values[0], values[1], values[2], values[3]);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
NS_INLINE void values_from_point(CGFloat values[], CGPoint p)
|
||||
{
|
||||
values[0] = p.x;
|
||||
values[1] = p.y;
|
||||
}
|
||||
|
||||
NS_INLINE void values_from_size(CGFloat values[], CGSize s)
|
||||
{
|
||||
values[0] = s.width;
|
||||
values[1] = s.height;
|
||||
}
|
||||
|
||||
NS_INLINE void values_from_rect(CGFloat values[], CGRect r)
|
||||
{
|
||||
values[0] = r.origin.x;
|
||||
values[1] = r.origin.y;
|
||||
values[2] = r.size.width;
|
||||
values[3] = r.size.height;
|
||||
}
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
|
||||
NS_INLINE void values_from_edge_insets(CGFloat values[], UIEdgeInsets i)
|
||||
{
|
||||
values[0] = i.top;
|
||||
values[1] = i.left;
|
||||
values[2] = i.bottom;
|
||||
values[3] = i.right;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/**
|
||||
Takes a CGColorRef and converts it into RGBA components, if necessary.
|
||||
*/
|
||||
extern void POPCGColorGetRGBAComponents(CGColorRef color, CGFloat components[]);
|
||||
|
||||
/**
|
||||
Takes RGBA components and returns a CGColorRef.
|
||||
*/
|
||||
extern CGColorRef POPCGColorRGBACreate(const CGFloat components[]) CF_RETURNS_RETAINED;
|
||||
|
||||
/**
|
||||
Takes a color reference and returns a CGColor.
|
||||
*/
|
||||
extern CGColorRef POPCGColorWithColor(id color);
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
|
||||
/**
|
||||
Takes a UIColor and converts it into RGBA components, if necessary.
|
||||
*/
|
||||
extern void POPUIColorGetRGBAComponents(UIColor *color, CGFloat components[]);
|
||||
|
||||
/**
|
||||
Takes RGBA components and returns a UIColor.
|
||||
*/
|
||||
extern UIColor *POPUIColorRGBACreate(const CGFloat components[]) NS_RETURNS_RETAINED;
|
||||
|
||||
#endif
|
||||
|
||||
POP_EXTERN_C_END
|
||||
Generated
+96
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPCGUtils.h"
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
#import <UIKit/UIColor.h>
|
||||
#else
|
||||
#import <AppKit/NSColor.h>
|
||||
#endif
|
||||
|
||||
void POPCGColorGetRGBAComponents(CGColorRef color, CGFloat components[])
|
||||
{
|
||||
if (!color) {
|
||||
#if TARGET_OS_IPHONE
|
||||
color = [UIColor clearColor].CGColor;
|
||||
#else
|
||||
color = [NSColor clearColor].CGColor;
|
||||
#endif
|
||||
}
|
||||
|
||||
const CGFloat *colors = CGColorGetComponents(color);
|
||||
size_t count = CGColorGetNumberOfComponents(color);
|
||||
|
||||
if (4 == count) {
|
||||
// RGB colorspace
|
||||
components[0] = colors[0];
|
||||
components[1] = colors[1];
|
||||
components[2] = colors[2];
|
||||
components[3] = colors[3];
|
||||
} else if (2 == count) {
|
||||
// Grey colorspace
|
||||
components[0] = components[1] = components[2] = colors[0];
|
||||
components[3] = colors[1];
|
||||
} else {
|
||||
// Use CI to convert
|
||||
CIColor *ciColor = [CIColor colorWithCGColor:color];
|
||||
components[0] = ciColor.red;
|
||||
components[1] = ciColor.green;
|
||||
components[2] = ciColor.blue;
|
||||
components[3] = ciColor.alpha;
|
||||
}
|
||||
}
|
||||
|
||||
CGColorRef POPCGColorRGBACreate(const CGFloat components[])
|
||||
{
|
||||
#if TARGET_OS_IPHONE
|
||||
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
|
||||
CGColorRef color = CGColorCreate(space, components);
|
||||
CGColorSpaceRelease(space);
|
||||
return color;
|
||||
#else
|
||||
return CGColorCreateGenericRGB(components[0], components[1], components[2], components[3]);
|
||||
#endif
|
||||
}
|
||||
|
||||
CGColorRef POPCGColorWithColor(id color)
|
||||
{
|
||||
if (CFGetTypeID((__bridge CFTypeRef)color) == CGColorGetTypeID()) {
|
||||
return ((__bridge CGColorRef)color);
|
||||
}
|
||||
#if TARGET_OS_IPHONE
|
||||
else if ([color isKindOfClass:[UIColor class]]) {
|
||||
return [color CGColor];
|
||||
}
|
||||
#else
|
||||
else if ([color isKindOfClass:[NSColor class]]) {
|
||||
return [color CGColor];
|
||||
}
|
||||
#endif
|
||||
return nil;
|
||||
}
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
|
||||
void POPUIColorGetRGBAComponents(UIColor *color, CGFloat components[])
|
||||
{
|
||||
return POPCGColorGetRGBAComponents(color.CGColor, components);
|
||||
}
|
||||
|
||||
UIColor *POPUIColorRGBACreate(const CGFloat components[])
|
||||
{
|
||||
CGColorRef colorRef = POPCGColorRGBACreate(components);
|
||||
UIColor *color = [[UIColor alloc] initWithCGColor:colorRef];
|
||||
CGColorRelease(colorRef);
|
||||
return color;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <pop/POPAnimation.h>
|
||||
|
||||
@class POPCustomAnimation;
|
||||
|
||||
/**
|
||||
@abstract POPCustomAnimationBlock is the callback block of a custom animation.
|
||||
@discussion This block will be executed for each animation frame and should update the property or properties being animated based on current timing.
|
||||
@param target The object being animated. Reference the passed in target to help avoid retain loops.
|
||||
@param animation The custom animation instance. Use to determine the current and elapsed time since last callback. Reference the passed in animation to help avoid retain loops.
|
||||
@return Flag indicating whether the animation should continue animating. Return NO to indicate animation is done.
|
||||
*/
|
||||
typedef BOOL (^POPCustomAnimationBlock)(id target, POPCustomAnimation *animation);
|
||||
|
||||
/**
|
||||
@abstract POPCustomAnimation is a concrete animation subclass for custom animations.
|
||||
*/
|
||||
@interface POPCustomAnimation : POPAnimation
|
||||
|
||||
/**
|
||||
@abstract Creates and returns an initialized custom animation instance.
|
||||
@discussion This is the designated initializer.
|
||||
@param block The custom animation callback block. See {@ref POPCustomAnimationBlock}.
|
||||
@return The initialized custom animation instance.
|
||||
*/
|
||||
+ (instancetype)animationWithBlock:(POPCustomAnimationBlock)block;
|
||||
|
||||
/**
|
||||
@abstract The current animation time at time of callback.
|
||||
*/
|
||||
@property (readonly, nonatomic) CFTimeInterval currentTime;
|
||||
|
||||
/**
|
||||
@abstract The elapsed animation time since last callback.
|
||||
*/
|
||||
@property (readonly, nonatomic) CFTimeInterval elapsedTime;
|
||||
|
||||
@end
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPCustomAnimation.h"
|
||||
#import "POPAnimationInternal.h"
|
||||
|
||||
@interface POPCustomAnimation ()
|
||||
@property (nonatomic, copy) POPCustomAnimationBlock animate;
|
||||
@end
|
||||
|
||||
@implementation POPCustomAnimation
|
||||
@synthesize currentTime = _currentTime;
|
||||
@synthesize elapsedTime = _elapsedTime;
|
||||
@synthesize animate = _animate;
|
||||
|
||||
+ (instancetype)animationWithBlock:(BOOL(^)(id target, POPCustomAnimation *))block
|
||||
{
|
||||
POPCustomAnimation *b = [[self alloc] _init];
|
||||
b.animate = block;
|
||||
return b;
|
||||
}
|
||||
|
||||
- (id)_init
|
||||
{
|
||||
self = [super _init];
|
||||
if (nil != self) {
|
||||
_state->type = kPOPAnimationCustom;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (CFTimeInterval)beginTime
|
||||
{
|
||||
POPAnimationState *s = POPAnimationGetState(self);
|
||||
return s->startTime > 0 ? s->startTime : s->beginTime;
|
||||
}
|
||||
|
||||
- (BOOL)_advance:(id)object currentTime:(CFTimeInterval)currentTime elapsedTime:(CFTimeInterval)elapsedTime
|
||||
{
|
||||
_currentTime = currentTime;
|
||||
_elapsedTime = elapsedTime;
|
||||
return _animate(object, self);
|
||||
}
|
||||
|
||||
- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug
|
||||
{
|
||||
[s appendFormat:@"; elapsedTime = %f; currentTime = %f;", _elapsedTime, _currentTime];
|
||||
}
|
||||
|
||||
@end
|
||||
Generated
+66
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <pop/POPPropertyAnimation.h>
|
||||
|
||||
/**
|
||||
@abstract A concrete decay animation class.
|
||||
@discussion Animation is achieved through gradual decay of animation value.
|
||||
*/
|
||||
@interface POPDecayAnimation : POPPropertyAnimation
|
||||
|
||||
/**
|
||||
@abstract The designated initializer.
|
||||
@returns An instance of a decay animation.
|
||||
*/
|
||||
+ (instancetype)animation;
|
||||
|
||||
/**
|
||||
@abstract Convenience initializer that returns an animation with animatable property of name.
|
||||
@param name The name of the animatable property.
|
||||
@returns An instance of a decay animation configured with specified animatable property.
|
||||
*/
|
||||
+ (instancetype)animationWithPropertyNamed:(NSString *)name;
|
||||
|
||||
/**
|
||||
@abstract The current velocity value.
|
||||
@discussion Set before animation start to account for initial velocity. Expressed in change of value units per second. The only POPValueTypes supported for velocity are: kPOPValuePoint, kPOPValueInteger, kPOPValueFloat, kPOPValueRect, and kPOPValueSize.
|
||||
*/
|
||||
@property (copy, nonatomic) id velocity;
|
||||
|
||||
/**
|
||||
@abstract The original velocity value.
|
||||
@discussion Since the velocity property is modified as the animation progresses, this property stores the original, passed in velocity to support autoreverse and repeatCount.
|
||||
*/
|
||||
@property (copy, nonatomic, readonly) id originalVelocity;
|
||||
|
||||
/**
|
||||
@abstract The deceleration factor.
|
||||
@discussion Values specifies should be in the range [0, 1]. Lower values results in faster deceleration. Defaults to 0.998.
|
||||
*/
|
||||
@property (assign, nonatomic) CGFloat deceleration;
|
||||
|
||||
/**
|
||||
@abstract The expected duration.
|
||||
@discussion Derived based on input velocity and deceleration values.
|
||||
*/
|
||||
@property (readonly, assign, nonatomic) CFTimeInterval duration;
|
||||
|
||||
/**
|
||||
The to value is derived based on input velocity and deceleration.
|
||||
*/
|
||||
- (void)setToValue:(id)toValue NS_UNAVAILABLE;
|
||||
|
||||
/**
|
||||
@abstract The reversed velocity.
|
||||
@discussion The reversed velocity based on the originalVelocity when the animation was set up.
|
||||
*/
|
||||
- (id)reversedVelocity;
|
||||
|
||||
@end
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPDecayAnimationInternal.h"
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
||||
|
||||
const POPValueType supportedVelocityTypes[6] = { kPOPValuePoint, kPOPValueInteger, kPOPValueFloat, kPOPValueRect, kPOPValueSize, kPOPValueEdgeInsets };
|
||||
|
||||
@implementation POPDecayAnimation
|
||||
|
||||
#pragma mark - Lifecycle
|
||||
|
||||
#undef __state
|
||||
#define __state ((POPDecayAnimationState *)_state)
|
||||
|
||||
+ (instancetype)animation
|
||||
{
|
||||
return [[self alloc] init];
|
||||
}
|
||||
|
||||
+ (instancetype)animationWithPropertyNamed:(NSString *)aName
|
||||
{
|
||||
POPDecayAnimation *anim = [self animation];
|
||||
anim.property = [POPAnimatableProperty propertyWithName:aName];
|
||||
return anim;
|
||||
}
|
||||
|
||||
- (id)init
|
||||
{
|
||||
return [self _init];
|
||||
}
|
||||
|
||||
- (void)_initState
|
||||
{
|
||||
_state = new POPDecayAnimationState(self);
|
||||
}
|
||||
|
||||
#pragma mark - Properties
|
||||
|
||||
DEFINE_RW_PROPERTY(POPDecayAnimationState, deceleration, setDeceleration:, CGFloat, __state->toVec = NULL;);
|
||||
|
||||
@dynamic velocity;
|
||||
|
||||
- (id)toValue
|
||||
{
|
||||
[self _ensureComputedProperties];
|
||||
return POPBox(__state->toVec, __state->valueType);
|
||||
}
|
||||
|
||||
- (CFTimeInterval)duration
|
||||
{
|
||||
[self _ensureComputedProperties];
|
||||
return __state->duration;
|
||||
}
|
||||
|
||||
- (void)setFromValue:(id)fromValue
|
||||
{
|
||||
super.fromValue = fromValue;
|
||||
[self _invalidateComputedProperties];
|
||||
}
|
||||
|
||||
- (void)setToValue:(id)aValue
|
||||
{
|
||||
// no-op
|
||||
NSLog(@"ignoring to value on decay animation %@", self);
|
||||
}
|
||||
|
||||
- (id)reversedVelocity
|
||||
{
|
||||
id reversedVelocity = nil;
|
||||
|
||||
POPValueType velocityType = POPSelectValueType(self.originalVelocity, supportedVelocityTypes, POP_ARRAY_COUNT(supportedVelocityTypes));
|
||||
if (velocityType == kPOPValueFloat) {
|
||||
CGFloat originalVelocityFloat = [(NSNumber *)self.originalVelocity floatValue];
|
||||
NSNumber *negativeOriginalVelocityNumber = @(-originalVelocityFloat);
|
||||
reversedVelocity = negativeOriginalVelocityNumber;
|
||||
} else if (velocityType == kPOPValueInteger) {
|
||||
NSInteger originalVelocityInteger = [(NSNumber *)self.originalVelocity integerValue];
|
||||
NSNumber *negativeOriginalVelocityNumber = @(-originalVelocityInteger);
|
||||
reversedVelocity = negativeOriginalVelocityNumber;
|
||||
} else if (velocityType == kPOPValuePoint) {
|
||||
CGPoint originalVelocityPoint = [self.originalVelocity CGPointValue];
|
||||
CGPoint negativeOriginalVelocityPoint = CGPointMake(-originalVelocityPoint.x, -originalVelocityPoint.y);
|
||||
reversedVelocity = [NSValue valueWithCGPoint:negativeOriginalVelocityPoint];
|
||||
} else if (velocityType == kPOPValueRect) {
|
||||
CGRect originalVelocityRect = [self.originalVelocity CGRectValue];
|
||||
CGRect negativeOriginalVelocityRect = CGRectMake(-originalVelocityRect.origin.x, -originalVelocityRect.origin.y, -originalVelocityRect.size.width, -originalVelocityRect.size.height);
|
||||
reversedVelocity = [NSValue valueWithCGRect:negativeOriginalVelocityRect];
|
||||
} else if (velocityType == kPOPValueSize) {
|
||||
CGSize originalVelocitySize = [self.originalVelocity CGSizeValue];
|
||||
CGSize negativeOriginalVelocitySize = CGSizeMake(-originalVelocitySize.width, -originalVelocitySize.height);
|
||||
reversedVelocity = [NSValue valueWithCGSize:negativeOriginalVelocitySize];
|
||||
} else if (velocityType == kPOPValueEdgeInsets) {
|
||||
#if TARGET_OS_IPHONE
|
||||
UIEdgeInsets originalVelocityInsets = [self.originalVelocity UIEdgeInsetsValue];
|
||||
UIEdgeInsets negativeOriginalVelocityInsets = UIEdgeInsetsMake(-originalVelocityInsets.top, -originalVelocityInsets.left, -originalVelocityInsets.bottom, -originalVelocityInsets.right);
|
||||
reversedVelocity = [NSValue valueWithUIEdgeInsets:negativeOriginalVelocityInsets];
|
||||
#endif
|
||||
}
|
||||
|
||||
return reversedVelocity;
|
||||
}
|
||||
|
||||
- (id)originalVelocity
|
||||
{
|
||||
return POPBox(__state->originalVelocityVec, __state->valueType);
|
||||
}
|
||||
|
||||
- (id)velocity
|
||||
{
|
||||
return POPBox(__state->velocityVec, __state->valueType);
|
||||
}
|
||||
|
||||
- (void)setVelocity:(id)aValue
|
||||
{
|
||||
POPValueType valueType = POPSelectValueType(aValue, supportedVelocityTypes, POP_ARRAY_COUNT(supportedVelocityTypes));
|
||||
if (valueType != kPOPValueUnknown) {
|
||||
VectorRef vec = POPUnbox(aValue, __state->valueType, __state->valueCount, YES);
|
||||
VectorRef origVec = POPUnbox(aValue, __state->valueType, __state->valueCount, YES);
|
||||
|
||||
if (!vec_equal(vec, __state->velocityVec)) {
|
||||
__state->velocityVec = vec;
|
||||
__state->originalVelocityVec = origVec;
|
||||
|
||||
if (__state->tracing) {
|
||||
[__state->tracer updateVelocity:aValue];
|
||||
}
|
||||
|
||||
[self _invalidateComputedProperties];
|
||||
|
||||
// automatically unpause active animations
|
||||
if (__state->active && __state->paused) {
|
||||
__state->fromVec = NULL;
|
||||
__state->setPaused(false);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
__state->velocityVec = NULL;
|
||||
NSLog(@"Invalid velocity value for the decayAnimation: %@", aValue);
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Utility
|
||||
|
||||
- (void)_ensureComputedProperties
|
||||
{
|
||||
if (NULL == __state->toVec) {
|
||||
__state->computeDuration();
|
||||
__state->computeToValue();
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_invalidateComputedProperties
|
||||
{
|
||||
__state->toVec = NULL;
|
||||
__state->duration = 0;
|
||||
}
|
||||
|
||||
- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug
|
||||
{
|
||||
[super _appendDescription:s debug:debug];
|
||||
|
||||
if (0 != self.duration) {
|
||||
[s appendFormat:@"; duration = %f", self.duration];
|
||||
}
|
||||
|
||||
if (__state->deceleration) {
|
||||
[s appendFormat:@"; deceleration = %f", __state->deceleration];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPDecayAnimation.h"
|
||||
#import "POPPropertyAnimationInternal.h"
|
||||
|
||||
// minimal velocity factor before decay animation is considered complete, in units / s
|
||||
static CGFloat kPOPAnimationDecayMinimalVelocityFactor = 5.;
|
||||
|
||||
// default decay animation deceleration
|
||||
static CGFloat kPOPAnimationDecayDecelerationDefault = 0.998;
|
||||
|
||||
static void decay_position(CGFloat *x, CGFloat *v, NSUInteger count, CFTimeInterval dt, CGFloat deceleration)
|
||||
{
|
||||
dt *= 1000;
|
||||
|
||||
// v0 = v / 1000
|
||||
// v = v0 * powf(deceleration, dt);
|
||||
// v = v * 1000;
|
||||
|
||||
// x0 = x;
|
||||
// x = x0 + v0 * deceleration * (1 - powf(deceleration, dt)) / (1 - deceleration)
|
||||
float v0[count];
|
||||
float kv = powf(deceleration, dt);
|
||||
float kx = deceleration * (1 - kv) / (1 - deceleration);
|
||||
|
||||
for (NSUInteger idx = 0; idx < count; idx++) {
|
||||
v0[idx] = v[idx] / 1000.;
|
||||
v[idx] = v0[idx] * kv * 1000.;
|
||||
x[idx] = x[idx] + v0[idx] * kx;
|
||||
}
|
||||
}
|
||||
|
||||
struct _POPDecayAnimationState : _POPPropertyAnimationState
|
||||
{
|
||||
double deceleration;
|
||||
CFTimeInterval duration;
|
||||
|
||||
_POPDecayAnimationState(id __unsafe_unretained anim) :
|
||||
_POPPropertyAnimationState(anim),
|
||||
deceleration(kPOPAnimationDecayDecelerationDefault),
|
||||
duration(0)
|
||||
{
|
||||
type = kPOPAnimationDecay;
|
||||
}
|
||||
|
||||
bool isDone() {
|
||||
if (_POPPropertyAnimationState::isDone()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
CGFloat f = dynamicsThreshold * kPOPAnimationDecayMinimalVelocityFactor;
|
||||
const CGFloat *velocityValues = vec_data(velocityVec);
|
||||
for (NSUInteger idx = 0; idx < valueCount; idx++) {
|
||||
if (fabsf(velocityValues[idx]) >= f)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
void computeDuration() {
|
||||
|
||||
// compute duration till threshold velocity
|
||||
Vector4r scaledVelocity = vector4(velocityVec) / 1000.;
|
||||
|
||||
double k = dynamicsThreshold * kPOPAnimationDecayMinimalVelocityFactor / 1000.;
|
||||
double vx = k / scaledVelocity.x;
|
||||
double vy = k / scaledVelocity.y;
|
||||
double vz = k / scaledVelocity.z;
|
||||
double vw = k / scaledVelocity.w;
|
||||
double d = log(deceleration) * 1000.;
|
||||
duration = MAX(MAX(MAX(log(fabs(vx)) / d, log(fabs(vy)) / d), log(fabs(vz)) / d), log(fabs(vw)) / d);
|
||||
|
||||
// ensure velocity threshold is exceeded
|
||||
if (isnan(duration) || duration < 0) {
|
||||
duration = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void computeToValue() {
|
||||
// to value assuming final velocity as a factor of dynamics threshold
|
||||
// derived from v' = v * d^dt used in decay_position
|
||||
// to compute the to value with maximal dt, p' = p + (v * d) / (1 - d)
|
||||
VectorRef fromValue = NULL != currentVec ? currentVec : fromVec;
|
||||
if (!fromValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ensure duration is computed
|
||||
if (0 == duration) {
|
||||
computeDuration();
|
||||
}
|
||||
|
||||
// compute to value
|
||||
VectorRef toValue(Vector::new_vector(fromValue.get()));
|
||||
Vector4r velocity = velocityVec->vector4r();
|
||||
decay_position(toValue->data(), velocity.data(), valueCount, duration, deceleration);
|
||||
toVec = toValue;
|
||||
}
|
||||
|
||||
void computeDestinationValues() {
|
||||
// to value assuming final velocity as a factor of dynamics threshold
|
||||
// derived from v' = v * d^dt used in decay_position
|
||||
// to compute the to value with maximal dt, p' = p + (v * d) / (1 - d)
|
||||
VectorRef fromValue = NULL != currentVec ? currentVec : fromVec;
|
||||
if (!fromValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
VectorRef toValue(Vector::new_vector(fromValue.get()));
|
||||
|
||||
// compute duration till threshold velocity
|
||||
Vector4r scaledVelocity = vector4(velocityVec) / 1000.;
|
||||
|
||||
double k = dynamicsThreshold * kPOPAnimationDecayMinimalVelocityFactor / 1000.;
|
||||
double vx = k / scaledVelocity.x;
|
||||
double vy = k / scaledVelocity.y;
|
||||
double vz = k / scaledVelocity.z;
|
||||
double vw = k / scaledVelocity.w;
|
||||
double d = log(deceleration) * 1000.;
|
||||
duration = MAX(MAX(MAX(log(fabs(vx)) / d, log(fabs(vy)) / d), log(fabs(vz)) / d), log(fabs(vw)) / d);
|
||||
|
||||
// ensure velocity threshold is exceeded
|
||||
if (isnan(duration) || duration < 0) {
|
||||
duration = 0;
|
||||
} else {
|
||||
// compute to value
|
||||
Vector4r velocity = velocityVec->vector4r();
|
||||
decay_position(toValue->data(), velocity.data(), valueCount, duration, deceleration);
|
||||
}
|
||||
|
||||
toVec = toValue;
|
||||
}
|
||||
|
||||
bool advance(CFTimeInterval time, CFTimeInterval dt, id obj) {
|
||||
// advance past not yet initialized animations
|
||||
if (NULL == currentVec) {
|
||||
return false;
|
||||
}
|
||||
|
||||
decay_position(currentVec->data(), velocityVec->data(), valueCount, dt, deceleration);
|
||||
|
||||
// clamp to compute end value; avoid possibility of decaying past
|
||||
clampCurrentValue(kPOPAnimationClampEnd | clampMode);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
typedef struct _POPDecayAnimationState POPDecayAnimationState;
|
||||
Generated
+29
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#ifndef POP_POPDefines_h
|
||||
#define POP_POPDefines_h
|
||||
|
||||
#ifdef __cplusplus
|
||||
# define POP_EXTERN_C_BEGIN extern "C" {
|
||||
# define POP_EXTERN_C_END }
|
||||
#else
|
||||
# define POP_EXTERN_C_BEGIN
|
||||
# define POP_EXTERN_C_END
|
||||
#endif
|
||||
|
||||
#define POP_ARRAY_COUNT(x) sizeof(x) / sizeof(x[0])
|
||||
|
||||
#if defined (__cplusplus) && defined (__GNUC__)
|
||||
# define POP_NOTHROW __attribute__ ((nothrow))
|
||||
#else
|
||||
# define POP_NOTHROW
|
||||
#endif
|
||||
|
||||
#endif
|
||||
Generated
+73
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
#import <UIKit/UIGeometry.h>
|
||||
#endif
|
||||
|
||||
#if !TARGET_OS_IPHONE
|
||||
|
||||
/** NSValue extensions to support animatable types. */
|
||||
@interface NSValue (POP)
|
||||
|
||||
/**
|
||||
@abstract Creates an NSValue given a CGPoint.
|
||||
*/
|
||||
+ (NSValue *)valueWithCGPoint:(CGPoint)point;
|
||||
|
||||
/**
|
||||
@abstract Creates an NSValue given a CGSize.
|
||||
*/
|
||||
+ (NSValue *)valueWithCGSize:(CGSize)size;
|
||||
|
||||
/**
|
||||
@abstract Creates an NSValue given a CGRect.
|
||||
*/
|
||||
+ (NSValue *)valueWithCGRect:(CGRect)rect;
|
||||
|
||||
/**
|
||||
@abstract Creates an NSValue given a CFRange.
|
||||
*/
|
||||
+ (NSValue *)valueWithCFRange:(CFRange)range;
|
||||
|
||||
/**
|
||||
@abstract Creates an NSValue given a CGAffineTransform.
|
||||
*/
|
||||
+ (NSValue *)valueWithCGAffineTransform:(CGAffineTransform)transform;
|
||||
|
||||
/**
|
||||
@abstract Returns the underlying CGPoint value.
|
||||
*/
|
||||
- (CGPoint)CGPointValue;
|
||||
|
||||
/**
|
||||
@abstract Returns the underlying CGSize value.
|
||||
*/
|
||||
- (CGSize)CGSizeValue;
|
||||
|
||||
/**
|
||||
@abstract Returns the underlying CGRect value.
|
||||
*/
|
||||
- (CGRect)CGRectValue;
|
||||
|
||||
/**
|
||||
@abstract Returns the underlying CFRange value.
|
||||
*/
|
||||
- (CFRange)CFRangeValue;
|
||||
|
||||
/**
|
||||
@abstract Returns the underlying CGAffineTransform value.
|
||||
*/
|
||||
- (CGAffineTransform)CGAffineTransformValue;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
Generated
+67
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPGeometry.h"
|
||||
|
||||
#if !TARGET_OS_IPHONE
|
||||
@implementation NSValue (POP)
|
||||
|
||||
+ (NSValue *)valueWithCGPoint:(CGPoint)point {
|
||||
return [NSValue valueWithBytes:&point objCType:@encode(CGPoint)];
|
||||
}
|
||||
|
||||
+ (NSValue *)valueWithCGSize:(CGSize)size {
|
||||
return [NSValue valueWithBytes:&size objCType:@encode(CGSize)];
|
||||
}
|
||||
|
||||
+ (NSValue *)valueWithCGRect:(CGRect)rect {
|
||||
return [NSValue valueWithBytes:&rect objCType:@encode(CGRect)];
|
||||
}
|
||||
|
||||
+ (NSValue *)valueWithCFRange:(CFRange)range {
|
||||
return [NSValue valueWithBytes:&range objCType:@encode(CFRange)];
|
||||
}
|
||||
|
||||
+ (NSValue *)valueWithCGAffineTransform:(CGAffineTransform)transform
|
||||
{
|
||||
return [NSValue valueWithBytes:&transform objCType:@encode(CGAffineTransform)];
|
||||
}
|
||||
|
||||
- (CGPoint)CGPointValue {
|
||||
CGPoint result;
|
||||
[self getValue:&result];
|
||||
return result;
|
||||
}
|
||||
|
||||
- (CGSize)CGSizeValue {
|
||||
CGSize result;
|
||||
[self getValue:&result];
|
||||
return result;
|
||||
}
|
||||
|
||||
- (CGRect)CGRectValue {
|
||||
CGRect result;
|
||||
[self getValue:&result];
|
||||
return result;
|
||||
}
|
||||
|
||||
- (CFRange)CFRangeValue {
|
||||
CFRange result;
|
||||
[self getValue:&result];
|
||||
return result;
|
||||
}
|
||||
|
||||
- (CGAffineTransform)CGAffineTransformValue {
|
||||
CGAffineTransform result;
|
||||
[self getValue:&result];
|
||||
return result;
|
||||
}
|
||||
@end
|
||||
|
||||
#endif
|
||||
Generated
+196
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
|
||||
#import <pop/POPDefines.h>
|
||||
|
||||
POP_EXTERN_C_BEGIN
|
||||
|
||||
#pragma mark - Scale
|
||||
|
||||
/**
|
||||
@abstract Returns layer scale factor for the x axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetScaleX(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Set layer scale factor for the x axis.
|
||||
*/
|
||||
extern void POPLayerSetScaleX(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns layer scale factor for the y axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetScaleY(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Set layer scale factor for the y axis.
|
||||
*/
|
||||
extern void POPLayerSetScaleY(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns layer scale factor for the z axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetScaleZ(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Set layer scale factor for the z axis.
|
||||
*/
|
||||
extern void POPLayerSetScaleZ(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns layer scale factors for x and y access as point.
|
||||
*/
|
||||
extern CGPoint POPLayerGetScaleXY(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Sets layer x and y scale factors given point.
|
||||
*/
|
||||
extern void POPLayerSetScaleXY(CALayer *l, CGPoint p);
|
||||
|
||||
#pragma mark - Translation
|
||||
|
||||
/**
|
||||
@abstract Returns layer translation factor for the x axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetTranslationX(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Set layer translation factor for the x axis.
|
||||
*/
|
||||
extern void POPLayerSetTranslationX(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns layer translation factor for the y axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetTranslationY(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Set layer translation factor for the y axis.
|
||||
*/
|
||||
extern void POPLayerSetTranslationY(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns layer translation factor for the z axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetTranslationZ(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Set layer translation factor for the z axis.
|
||||
*/
|
||||
extern void POPLayerSetTranslationZ(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns layer translation factors for x and y access as point.
|
||||
*/
|
||||
extern CGPoint POPLayerGetTranslationXY(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Sets layer x and y translation factors given point.
|
||||
*/
|
||||
extern void POPLayerSetTranslationXY(CALayer *l, CGPoint p);
|
||||
|
||||
#pragma mark - Rotation
|
||||
|
||||
/**
|
||||
@abstract Returns layer rotation, in radians, in the X axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetRotationX(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Sets layer rotation, in radians, in the X axis.
|
||||
*/
|
||||
extern void POPLayerSetRotationX(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns layer rotation, in radians, in the Y axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetRotationY(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Sets layer rotation, in radians, in the Y axis.
|
||||
*/
|
||||
extern void POPLayerSetRotationY(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns layer rotation, in radians, in the Z axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetRotationZ(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Sets layer rotation, in radians, in the Z axis.
|
||||
*/
|
||||
extern void POPLayerSetRotationZ(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns layer rotation, in radians, in the Z axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetRotation(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Sets layer rotation, in radians, in the Z axis.
|
||||
*/
|
||||
extern void POPLayerSetRotation(CALayer *l, CGFloat f);
|
||||
|
||||
#pragma mark - Sublayer Scale
|
||||
|
||||
/**
|
||||
@abstract Returns sublayer scale factors for x and y access as point.
|
||||
*/
|
||||
extern CGPoint POPLayerGetSubScaleXY(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Sets sublayer x and y scale factors given point.
|
||||
*/
|
||||
extern void POPLayerSetSubScaleXY(CALayer *l, CGPoint p);
|
||||
|
||||
#pragma mark - Sublayer Translation
|
||||
|
||||
/**
|
||||
@abstract Returns sublayer translation factor for the x axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetSubTranslationX(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Set sublayer translation factor for the x axis.
|
||||
*/
|
||||
extern void POPLayerSetSubTranslationX(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns sublayer translation factor for the y axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetSubTranslationY(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Set sublayer translation factor for the y axis.
|
||||
*/
|
||||
extern void POPLayerSetSubTranslationY(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns sublayer translation factor for the z axis.
|
||||
*/
|
||||
extern CGFloat POPLayerGetSubTranslationZ(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Set sublayer translation factor for the z axis.
|
||||
*/
|
||||
extern void POPLayerSetSubTranslationZ(CALayer *l, CGFloat f);
|
||||
|
||||
/**
|
||||
@abstract Returns sublayer translation factors for x and y access as point.
|
||||
*/
|
||||
extern CGPoint POPLayerGetSubTranslationXY(CALayer *l);
|
||||
|
||||
/**
|
||||
@abstract Sets sublayer x and y translation factors given point.
|
||||
*/
|
||||
extern void POPLayerSetSubTranslationXY(CALayer *l, CGPoint p);
|
||||
|
||||
POP_EXTERN_C_END
|
||||
Generated
+288
@@ -0,0 +1,288 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPLayerExtras.h"
|
||||
|
||||
#include "TransformationMatrix.h"
|
||||
|
||||
using namespace WebCore;
|
||||
|
||||
#define DECOMPOSE_TRANSFORM(L) \
|
||||
TransformationMatrix _m(L.transform); \
|
||||
TransformationMatrix::DecomposedType _d; \
|
||||
_m.decompose(_d);
|
||||
|
||||
#define RECOMPOSE_TRANSFORM(L) \
|
||||
_m.recompose(_d); \
|
||||
L.transform = _m.transform3d();
|
||||
|
||||
#define RECOMPOSE_ROT_TRANSFORM(L) \
|
||||
_m.recompose(_d, true); \
|
||||
L.transform = _m.transform3d();
|
||||
|
||||
#define DECOMPOSE_SUBLAYER_TRANSFORM(L) \
|
||||
TransformationMatrix _m(L.sublayerTransform); \
|
||||
TransformationMatrix::DecomposedType _d; \
|
||||
_m.decompose(_d);
|
||||
|
||||
#define RECOMPOSE_SUBLAYER_TRANSFORM(L) \
|
||||
_m.recompose(_d); \
|
||||
L.sublayerTransform = _m.transform3d();
|
||||
|
||||
#pragma mark - Scale
|
||||
|
||||
NS_INLINE void ensureNonZeroValue(CGFloat &f)
|
||||
{
|
||||
if (f == 0) {
|
||||
f = 1e-6;
|
||||
}
|
||||
}
|
||||
|
||||
NS_INLINE void ensureNonZeroValue(CGPoint &p)
|
||||
{
|
||||
if (p.x == 0 && p.y == 0) {
|
||||
p.x = 1e-6;
|
||||
p.y = 1e-6;
|
||||
}
|
||||
}
|
||||
|
||||
CGFloat POPLayerGetScaleX(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
return _d.scaleX;
|
||||
}
|
||||
|
||||
void POPLayerSetScaleX(CALayer *l, CGFloat f)
|
||||
{
|
||||
ensureNonZeroValue(f);
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
_d.scaleX = f;
|
||||
RECOMPOSE_TRANSFORM(l);
|
||||
}
|
||||
|
||||
CGFloat POPLayerGetScaleY(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
return _d.scaleY;
|
||||
}
|
||||
|
||||
void POPLayerSetScaleY(CALayer *l, CGFloat f)
|
||||
{
|
||||
ensureNonZeroValue(f);
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
_d.scaleY = f;
|
||||
RECOMPOSE_TRANSFORM(l);
|
||||
}
|
||||
|
||||
CGFloat POPLayerGetScaleZ(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
return _d.scaleZ;
|
||||
}
|
||||
|
||||
void POPLayerSetScaleZ(CALayer *l, CGFloat f)
|
||||
{
|
||||
ensureNonZeroValue(f);
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
_d.scaleZ = f;
|
||||
RECOMPOSE_TRANSFORM(l);
|
||||
}
|
||||
|
||||
CGPoint POPLayerGetScaleXY(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
return CGPointMake(_d.scaleX, _d.scaleY);
|
||||
}
|
||||
|
||||
void POPLayerSetScaleXY(CALayer *l, CGPoint p)
|
||||
{
|
||||
ensureNonZeroValue(p);
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
_d.scaleX = p.x;
|
||||
_d.scaleY = p.y;
|
||||
RECOMPOSE_TRANSFORM(l);
|
||||
}
|
||||
|
||||
#pragma mark - Translation
|
||||
|
||||
CGFloat POPLayerGetTranslationX(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
return _d.translateX;
|
||||
}
|
||||
|
||||
void POPLayerSetTranslationX(CALayer *l, CGFloat f)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
_d.translateX = f;
|
||||
RECOMPOSE_TRANSFORM(l);
|
||||
}
|
||||
|
||||
CGFloat POPLayerGetTranslationY(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
return _d.translateY;
|
||||
}
|
||||
|
||||
void POPLayerSetTranslationY(CALayer *l, CGFloat f)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
_d.translateY = f;
|
||||
RECOMPOSE_TRANSFORM(l);
|
||||
}
|
||||
|
||||
CGFloat POPLayerGetTranslationZ(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
return _d.translateZ;
|
||||
}
|
||||
|
||||
void POPLayerSetTranslationZ(CALayer *l, CGFloat f)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
_d.translateZ = f;
|
||||
RECOMPOSE_TRANSFORM(l);
|
||||
}
|
||||
|
||||
CGPoint POPLayerGetTranslationXY(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
return CGPointMake(_d.translateX, _d.translateY);
|
||||
}
|
||||
|
||||
void POPLayerSetTranslationXY(CALayer *l, CGPoint p)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
_d.translateX = p.x;
|
||||
_d.translateY = p.y;
|
||||
RECOMPOSE_TRANSFORM(l);
|
||||
}
|
||||
|
||||
#pragma mark - Rotation
|
||||
|
||||
CGFloat POPLayerGetRotationX(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
return _d.rotateX;
|
||||
}
|
||||
|
||||
void POPLayerSetRotationX(CALayer *l, CGFloat f)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
_d.rotateX = f;
|
||||
RECOMPOSE_ROT_TRANSFORM(l);
|
||||
}
|
||||
|
||||
CGFloat POPLayerGetRotationY(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
return _d.rotateY;
|
||||
}
|
||||
|
||||
void POPLayerSetRotationY(CALayer *l, CGFloat f)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
_d.rotateY = f;
|
||||
RECOMPOSE_ROT_TRANSFORM(l);
|
||||
}
|
||||
|
||||
CGFloat POPLayerGetRotationZ(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
return _d.rotateZ;
|
||||
}
|
||||
|
||||
void POPLayerSetRotationZ(CALayer *l, CGFloat f)
|
||||
{
|
||||
DECOMPOSE_TRANSFORM(l);
|
||||
_d.rotateZ = f;
|
||||
RECOMPOSE_ROT_TRANSFORM(l);
|
||||
}
|
||||
|
||||
CGFloat POPLayerGetRotation(CALayer *l)
|
||||
{
|
||||
return POPLayerGetRotationZ(l);
|
||||
}
|
||||
|
||||
void POPLayerSetRotation(CALayer *l, CGFloat f)
|
||||
{
|
||||
POPLayerSetRotationZ(l, f);
|
||||
}
|
||||
|
||||
#pragma mark - Sublayer Scale
|
||||
|
||||
CGPoint POPLayerGetSubScaleXY(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
return CGPointMake(_d.scaleX, _d.scaleY);
|
||||
}
|
||||
|
||||
void POPLayerSetSubScaleXY(CALayer *l, CGPoint p)
|
||||
{
|
||||
ensureNonZeroValue(p);
|
||||
DECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
_d.scaleX = p.x;
|
||||
_d.scaleY = p.y;
|
||||
RECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
}
|
||||
|
||||
#pragma mark - Sublayer Translation
|
||||
|
||||
extern CGFloat POPLayerGetSubTranslationX(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
return _d.translateX;
|
||||
}
|
||||
|
||||
extern void POPLayerSetSubTranslationX(CALayer *l, CGFloat f)
|
||||
{
|
||||
DECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
_d.translateX = f;
|
||||
RECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
}
|
||||
|
||||
extern CGFloat POPLayerGetSubTranslationY(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
return _d.translateY;
|
||||
}
|
||||
|
||||
extern void POPLayerSetSubTranslationY(CALayer *l, CGFloat f)
|
||||
{
|
||||
DECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
_d.translateY = f;
|
||||
RECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
}
|
||||
|
||||
extern CGFloat POPLayerGetSubTranslationZ(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
return _d.translateZ;
|
||||
}
|
||||
|
||||
extern void POPLayerSetSubTranslationZ(CALayer *l, CGFloat f)
|
||||
{
|
||||
DECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
_d.translateZ = f;
|
||||
RECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
}
|
||||
|
||||
extern CGPoint POPLayerGetSubTranslationXY(CALayer *l)
|
||||
{
|
||||
DECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
return CGPointMake(_d.translateX, _d.translateY);
|
||||
}
|
||||
|
||||
extern void POPLayerSetSubTranslationXY(CALayer *l, CGPoint p)
|
||||
{
|
||||
DECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
_d.translateX = p.x;
|
||||
_d.translateY = p.y;
|
||||
RECOMPOSE_SUBLAYER_TRANSFORM(l);
|
||||
}
|
||||
Generated
+55
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
|
||||
#import "POPDefines.h"
|
||||
#import "POPVector.h"
|
||||
|
||||
NS_INLINE CGFloat sqrtr(CGFloat f)
|
||||
{
|
||||
#if CGFLOAT_IS_DOUBLE
|
||||
return sqrt(f);
|
||||
#else
|
||||
return sqrtf(f);
|
||||
#endif
|
||||
}
|
||||
|
||||
// round to nearest sub; pass 2.0 to round to every 0.5 (eg: retina pixels)
|
||||
NS_INLINE CGFloat POPSubRound(CGFloat f, CGFloat sub)
|
||||
{
|
||||
return round(f * sub) / sub;
|
||||
}
|
||||
|
||||
#define MIX(a, b, f) ((a) + (f) * ((b) - (a)))
|
||||
|
||||
// the longer the duration, the higher the necessary precision
|
||||
#define SOLVE_EPS(dur) (1. / (1000. * (dur)))
|
||||
|
||||
#define _EQLF_(x, y, epsilon) (fabsf ((x) - (y)) < epsilon)
|
||||
|
||||
extern void POPInterpolateVector(NSUInteger count, CGFloat *dst, const CGFloat *from, const CGFloat *to, CGFloat f);
|
||||
|
||||
extern double POPTimingFunctionSolve(const double vec[4], double t, double eps);
|
||||
|
||||
// quadratic mapping of t [0, 1] to [start, end]
|
||||
extern double POPQuadraticOutInterpolation(double t, double start, double end);
|
||||
|
||||
// normalize value to [0, 1] based on its range [startValue, endValue]
|
||||
extern double POPNormalize(double value, double startValue, double endValue);
|
||||
|
||||
// project a normalized value [0, 1] to a given range [start, end]
|
||||
extern double POPProjectNormal(double n, double start, double end);
|
||||
|
||||
// solve a quadratic equation of the form a * x^2 + b * x + c = 0
|
||||
extern void POPQuadraticSolve(CGFloat a, CGFloat b, CGFloat c, CGFloat &x1, CGFloat &x2);
|
||||
|
||||
// for a given tension return the bouncy 3 friction that produces no bounce
|
||||
extern double POPBouncy3NoBounce(double tension);
|
||||
Generated
+82
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPMath.h"
|
||||
#import "UnitBezier.h"
|
||||
#import "POPAnimationPrivate.h"
|
||||
|
||||
void POPInterpolateVector(NSUInteger count, CGFloat *dst, const CGFloat *from, const CGFloat *to, CGFloat f)
|
||||
{
|
||||
for (NSUInteger idx = 0; idx < count; idx++) {
|
||||
dst[idx] = MIX(from[idx], to[idx], f);
|
||||
}
|
||||
}
|
||||
|
||||
double POPTimingFunctionSolve(const double vec[4], double t, double eps)
|
||||
{
|
||||
WebCore::UnitBezier bezier(vec[0], vec[1], vec[2], vec[3]);
|
||||
return bezier.solve(t, eps);
|
||||
}
|
||||
|
||||
double POPNormalize(double value, double startValue, double endValue)
|
||||
{
|
||||
return (value - startValue) / (endValue - startValue);
|
||||
}
|
||||
|
||||
double POPProjectNormal(double n, double start, double end)
|
||||
{
|
||||
return start + (n * (end - start));
|
||||
}
|
||||
|
||||
static double linear_interpolation(double t, double start, double end)
|
||||
{
|
||||
return t * end + (1.f - t) * start;
|
||||
}
|
||||
|
||||
double POPQuadraticOutInterpolation(double t, double start, double end)
|
||||
{
|
||||
return linear_interpolation(2*t - t*t, start, end);
|
||||
}
|
||||
|
||||
static double b3_friction1(double x)
|
||||
{
|
||||
return (0.0007 * pow(x, 3)) - (0.031 * pow(x, 2)) + 0.64 * x + 1.28;
|
||||
}
|
||||
|
||||
static double b3_friction2(double x)
|
||||
{
|
||||
return (0.000044 * pow(x, 3)) - (0.006 * pow(x, 2)) + 0.36 * x + 2.;
|
||||
}
|
||||
|
||||
static double b3_friction3(double x)
|
||||
{
|
||||
return (0.00000045 * pow(x, 3)) - (0.000332 * pow(x, 2)) + 0.1078 * x + 5.84;
|
||||
}
|
||||
|
||||
double POPBouncy3NoBounce(double tension)
|
||||
{
|
||||
double friction = 0;
|
||||
if (tension <= 18.) {
|
||||
friction = b3_friction1(tension);
|
||||
} else if (tension > 18 && tension <= 44) {
|
||||
friction = b3_friction2(tension);
|
||||
} else if (tension > 44) {
|
||||
friction = b3_friction3(tension);
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
return friction;
|
||||
}
|
||||
|
||||
void POPQuadraticSolve(CGFloat a, CGFloat b, CGFloat c, CGFloat &x1, CGFloat &x2)
|
||||
{
|
||||
CGFloat discriminant = sqrt(b * b - 4 * a * c);
|
||||
x1 = (-b + discriminant) / (2 * a);
|
||||
x2 = (-b - discriminant) / (2 * a);
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <pop/POPAnimatableProperty.h>
|
||||
#import <pop/POPAnimation.h>
|
||||
|
||||
/**
|
||||
@abstract Flags for clamping animation values.
|
||||
@discussion Animation values can optionally be clamped to avoid overshoot. kPOPAnimationClampStart ensures values are more than fromValue and kPOPAnimationClampEnd ensures values are less than toValue.
|
||||
*/
|
||||
typedef NS_OPTIONS(NSUInteger, POPAnimationClampFlags)
|
||||
{
|
||||
kPOPAnimationClampNone = 0,
|
||||
kPOPAnimationClampStart = 1UL << 0,
|
||||
kPOPAnimationClampEnd = 1UL << 1,
|
||||
kPOPAnimationClampBoth = kPOPAnimationClampStart | kPOPAnimationClampEnd,
|
||||
};
|
||||
|
||||
/**
|
||||
@abstract The semi-concrete property animation subclass.
|
||||
*/
|
||||
@interface POPPropertyAnimation : POPAnimation
|
||||
|
||||
/**
|
||||
@abstract The property to animate.
|
||||
*/
|
||||
@property (strong, nonatomic) POPAnimatableProperty *property;
|
||||
|
||||
/**
|
||||
@abstract The value to animate from.
|
||||
@discussion The value type should match the property. If unspecified, the value is initialized to the object's current value on animation start.
|
||||
*/
|
||||
@property (copy, nonatomic) id fromValue;
|
||||
|
||||
/**
|
||||
@abstract The value to animate to.
|
||||
@discussion The value type should match the property. If unspecified, the value is initialized to the object's current value on animation start.
|
||||
*/
|
||||
@property (copy, nonatomic) id toValue;
|
||||
|
||||
/**
|
||||
@abstract The rounding factor applied to the current animated value.
|
||||
@discussion Specify 1.0 to animate between integral values. Defaults to 0 meaning no rounding.
|
||||
*/
|
||||
@property (assign, nonatomic) CGFloat roundingFactor;
|
||||
|
||||
/**
|
||||
@abstract The clamp mode applied to the current animated value.
|
||||
@discussion See {@ref POPAnimationClampFlags} for possible values. Defaults to kPOPAnimationClampNone.
|
||||
*/
|
||||
@property (assign, nonatomic) NSUInteger clampMode;
|
||||
|
||||
/**
|
||||
@abstract The flag indicating whether values should be "added" each frame, rather than set.
|
||||
@discussion Addition may be type dependent. Defaults to NO.
|
||||
*/
|
||||
@property (assign, nonatomic, getter = isAdditive) BOOL additive;
|
||||
|
||||
@end
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPPropertyAnimationInternal.h"
|
||||
|
||||
@implementation POPPropertyAnimation
|
||||
|
||||
#pragma mark - Lifecycle
|
||||
|
||||
#undef __state
|
||||
#define __state ((POPPropertyAnimationState *)_state)
|
||||
|
||||
- (void)_initState
|
||||
{
|
||||
_state = new POPPropertyAnimationState(self);
|
||||
}
|
||||
|
||||
#pragma mark - Properties
|
||||
|
||||
DEFINE_RW_FLAG(POPPropertyAnimationState, additive, isAdditive, setAdditive:);
|
||||
DEFINE_RW_PROPERTY(POPPropertyAnimationState, roundingFactor, setRoundingFactor:, CGFloat);
|
||||
DEFINE_RW_PROPERTY(POPPropertyAnimationState, clampMode, setClampMode:, NSUInteger);
|
||||
DEFINE_RW_PROPERTY_OBJ(POPPropertyAnimationState, property, setProperty:, POPAnimatableProperty*, ((POPPropertyAnimationState*)_state)->updatedDynamicsThreshold(););
|
||||
DEFINE_RW_PROPERTY_OBJ_COPY(POPPropertyAnimationState, progressMarkers, setProgressMarkers:, NSArray*, ((POPPropertyAnimationState*)_state)->updatedProgressMarkers(););
|
||||
|
||||
- (id)fromValue
|
||||
{
|
||||
return POPBox(__state->fromVec, __state->valueType);
|
||||
}
|
||||
|
||||
- (void)setFromValue:(id)aValue
|
||||
{
|
||||
POPPropertyAnimationState *s = __state;
|
||||
VectorRef vec = POPUnbox(aValue, s->valueType, s->valueCount, YES);
|
||||
if (!vec_equal(vec, s->fromVec)) {
|
||||
s->fromVec = vec;
|
||||
|
||||
if (s->tracing) {
|
||||
[s->tracer updateFromValue:aValue];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (id)toValue
|
||||
{
|
||||
return POPBox(__state->toVec, __state->valueType);
|
||||
}
|
||||
|
||||
- (void)setToValue:(id)aValue
|
||||
{
|
||||
POPPropertyAnimationState *s = __state;
|
||||
VectorRef vec = POPUnbox(aValue, s->valueType, s->valueCount, YES);
|
||||
|
||||
if (!vec_equal(vec, s->toVec)) {
|
||||
s->toVec = vec;
|
||||
|
||||
// invalidate to dependent state
|
||||
s->didReachToValue = false;
|
||||
s->distanceVec = NULL;
|
||||
|
||||
if (s->tracing) {
|
||||
[s->tracer updateToValue:aValue];
|
||||
}
|
||||
|
||||
// automatically unpause active animations
|
||||
if (s->active && s->paused) {
|
||||
s->setPaused(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (id)currentValue
|
||||
{
|
||||
return POPBox(__state->currentValue(), __state->valueType);
|
||||
}
|
||||
|
||||
#pragma mark - Utility
|
||||
|
||||
- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug
|
||||
{
|
||||
[s appendFormat:@"; from = %@; to = %@", describe(__state->fromVec), describe(__state->toVec)];
|
||||
|
||||
if (_state->active)
|
||||
[s appendFormat:@"; currentValue = %@", describe(__state->currentValue())];
|
||||
|
||||
if (__state->velocityVec && 0 != __state->velocityVec->norm())
|
||||
[s appendFormat:@"; velocity = %@", describe(__state->velocityVec)];
|
||||
|
||||
if (!self.removedOnCompletion)
|
||||
[s appendFormat:@"; removedOnCompletion = %@", POPStringFromBOOL(self.removedOnCompletion)];
|
||||
|
||||
if (__state->progressMarkers)
|
||||
[s appendFormat:@"; progressMarkers = [%@]", [__state->progressMarkers componentsJoinedByString:@", "]];
|
||||
|
||||
if (_state->active)
|
||||
[s appendFormat:@"; progress = %f", __state->progress];
|
||||
}
|
||||
|
||||
@end
|
||||
+353
@@ -0,0 +1,353 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPAnimationInternal.h"
|
||||
#import "POPPropertyAnimation.h"
|
||||
|
||||
static void clampValue(CGFloat &value, CGFloat fromValue, CGFloat toValue, NSUInteger clamp)
|
||||
{
|
||||
BOOL increasing = (toValue > fromValue);
|
||||
|
||||
// Clamp start of animation.
|
||||
if ((kPOPAnimationClampStart & clamp) &&
|
||||
((increasing && (value < fromValue)) || (!increasing && (value > fromValue)))) {
|
||||
value = fromValue;
|
||||
}
|
||||
|
||||
// Clamp end of animation.
|
||||
if ((kPOPAnimationClampEnd & clamp) &&
|
||||
((increasing && (value > toValue)) || (!increasing && (value < toValue)))) {
|
||||
value = toValue;
|
||||
}
|
||||
}
|
||||
|
||||
struct _POPPropertyAnimationState : _POPAnimationState
|
||||
{
|
||||
POPAnimatableProperty *property;
|
||||
POPValueType valueType;
|
||||
NSUInteger valueCount;
|
||||
VectorRef fromVec;
|
||||
VectorRef toVec;
|
||||
VectorRef currentVec;
|
||||
VectorRef previousVec;
|
||||
VectorRef previous2Vec;
|
||||
VectorRef velocityVec;
|
||||
VectorRef originalVelocityVec;
|
||||
VectorRef distanceVec;
|
||||
CGFloat roundingFactor;
|
||||
NSUInteger clampMode;
|
||||
NSArray *progressMarkers;
|
||||
POPProgressMarker *progressMarkerState;
|
||||
NSUInteger progressMarkerCount;
|
||||
NSUInteger nextProgressMarkerIdx;
|
||||
CGFloat dynamicsThreshold;
|
||||
|
||||
_POPPropertyAnimationState(id __unsafe_unretained anim) : _POPAnimationState(anim),
|
||||
property(nil),
|
||||
valueType((POPValueType)0),
|
||||
valueCount(0),
|
||||
fromVec(nullptr),
|
||||
toVec(nullptr),
|
||||
currentVec(nullptr),
|
||||
previousVec(nullptr),
|
||||
previous2Vec(nullptr),
|
||||
velocityVec(nullptr),
|
||||
originalVelocityVec(nullptr),
|
||||
distanceVec(nullptr),
|
||||
roundingFactor(0),
|
||||
clampMode(0),
|
||||
progressMarkers(nil),
|
||||
progressMarkerState(nil),
|
||||
progressMarkerCount(0),
|
||||
nextProgressMarkerIdx(0),
|
||||
dynamicsThreshold(0)
|
||||
{
|
||||
type = kPOPAnimationBasic;
|
||||
}
|
||||
|
||||
~_POPPropertyAnimationState()
|
||||
{
|
||||
if (progressMarkerState) {
|
||||
free(progressMarkerState);
|
||||
progressMarkerState = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
bool canProgress() {
|
||||
return hasValue();
|
||||
}
|
||||
|
||||
bool shouldRound() {
|
||||
return 0 != roundingFactor;
|
||||
}
|
||||
|
||||
bool hasValue() {
|
||||
return 0 != valueCount;
|
||||
}
|
||||
|
||||
bool isDone() {
|
||||
// inherit done
|
||||
if (_POPAnimationState::isDone()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// consider an animation with no values done
|
||||
if (!hasValue() && !isCustom()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// returns a copy of the currentVec, rounding if needed
|
||||
VectorRef currentValue() {
|
||||
VectorRef vec = VectorRef(Vector::new_vector(currentVec.get()));
|
||||
if (shouldRound()) {
|
||||
vec->subRound(1 / roundingFactor);
|
||||
}
|
||||
return vec;
|
||||
}
|
||||
|
||||
void resetProgressMarkerState()
|
||||
{
|
||||
for (NSUInteger idx = 0; idx < progressMarkerCount; idx++)
|
||||
progressMarkerState[idx].reached = false;
|
||||
|
||||
nextProgressMarkerIdx = 0;
|
||||
}
|
||||
|
||||
void updatedProgressMarkers()
|
||||
{
|
||||
if (progressMarkerState) {
|
||||
free(progressMarkerState);
|
||||
progressMarkerState = NULL;
|
||||
}
|
||||
|
||||
progressMarkerCount = progressMarkers.count;
|
||||
|
||||
if (0 != progressMarkerCount) {
|
||||
progressMarkerState = (POPProgressMarker *)malloc(progressMarkerCount * sizeof(POPProgressMarker));
|
||||
[progressMarkers enumerateObjectsUsingBlock:^(NSNumber *progressMarker, NSUInteger idx, BOOL *stop) {
|
||||
progressMarkerState[idx].reached = false;
|
||||
progressMarkerState[idx].progress = [progressMarker floatValue];
|
||||
}];
|
||||
}
|
||||
|
||||
nextProgressMarkerIdx = 0;
|
||||
}
|
||||
|
||||
virtual void updatedDynamicsThreshold()
|
||||
{
|
||||
dynamicsThreshold = property.threshold;
|
||||
}
|
||||
|
||||
void finalizeProgress()
|
||||
{
|
||||
progress = 1.0;
|
||||
NSUInteger count = valueCount;
|
||||
VectorRef outVec(Vector::new_vector(count, NULL));
|
||||
|
||||
if (outVec && toVec) {
|
||||
*outVec = *toVec;
|
||||
}
|
||||
|
||||
currentVec = outVec;
|
||||
clampCurrentValue();
|
||||
delegateProgress();
|
||||
}
|
||||
|
||||
void computeProgress() {
|
||||
if (!canProgress()) {
|
||||
return;
|
||||
}
|
||||
|
||||
static ComputeProgressFunctor<Vector4r> func;
|
||||
Vector4r v = vector4(currentVec);
|
||||
Vector4r f = vector4(fromVec);
|
||||
Vector4r t = vector4(toVec);
|
||||
progress = func(v, f, t);
|
||||
}
|
||||
|
||||
void delegateProgress() {
|
||||
if (!canProgress()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (delegateDidProgress && progressMarkerState) {
|
||||
|
||||
while (nextProgressMarkerIdx < progressMarkerCount) {
|
||||
if (progress < progressMarkerState[nextProgressMarkerIdx].progress)
|
||||
break;
|
||||
|
||||
if (!progressMarkerState[nextProgressMarkerIdx].reached) {
|
||||
ActionEnabler enabler;
|
||||
[delegate pop_animation:self didReachProgress:progressMarkerState[nextProgressMarkerIdx].progress];
|
||||
progressMarkerState[nextProgressMarkerIdx].reached = true;
|
||||
}
|
||||
|
||||
nextProgressMarkerIdx++;
|
||||
}
|
||||
}
|
||||
|
||||
if (!didReachToValue) {
|
||||
bool didReachToValue = false;
|
||||
if (0 == valueCount) {
|
||||
didReachToValue = true;
|
||||
} else {
|
||||
Vector4r distance = toVec->vector4r();
|
||||
distance -= currentVec->vector4r();
|
||||
|
||||
if (0 == distance.squaredNorm()) {
|
||||
didReachToValue = true;
|
||||
} else {
|
||||
// components
|
||||
if (distanceVec) {
|
||||
didReachToValue = true;
|
||||
const CGFloat *distanceValues = distanceVec->data();
|
||||
for (NSUInteger idx = 0; idx < valueCount; idx++) {
|
||||
didReachToValue &= (signbit(distance[idx]) != signbit(distanceValues[idx]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (didReachToValue) {
|
||||
handleDidReachToValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void handleDidReachToValue() {
|
||||
didReachToValue = true;
|
||||
|
||||
if (delegateDidReachToValue) {
|
||||
ActionEnabler enabler;
|
||||
[delegate pop_animationDidReachToValue:self];
|
||||
}
|
||||
|
||||
if (tracing) {
|
||||
[tracer didReachToValue:POPBox(currentValue(), valueType, true)];
|
||||
}
|
||||
}
|
||||
|
||||
void readObjectValue(VectorRef *ptrVec, id obj)
|
||||
{
|
||||
// use current object value as from value
|
||||
pop_animatable_read_block read = property.readBlock;
|
||||
if (NULL != read) {
|
||||
|
||||
Vector4r vec = read_values(read, obj, valueCount);
|
||||
*ptrVec = VectorRef(Vector::new_vector(valueCount, vec));
|
||||
|
||||
if (tracing) {
|
||||
[tracer readPropertyValue:POPBox(*ptrVec, valueType, true)];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
virtual void willRun(bool started, id obj) {
|
||||
// ensure from value initialized
|
||||
if (NULL == fromVec) {
|
||||
readObjectValue(&fromVec, obj);
|
||||
}
|
||||
|
||||
// ensure to value initialized
|
||||
if (NULL == toVec) {
|
||||
// compute decay to value
|
||||
if (kPOPAnimationDecay == type) {
|
||||
[self toValue];
|
||||
} else {
|
||||
// read to value
|
||||
readObjectValue(&toVec, obj);
|
||||
}
|
||||
}
|
||||
|
||||
// handle one time value initialization on start
|
||||
if (started) {
|
||||
|
||||
// initialize current vec
|
||||
if (!currentVec) {
|
||||
currentVec = VectorRef(Vector::new_vector(valueCount, NULL));
|
||||
|
||||
// initialize current value with from value
|
||||
// only do this on initial creation to avoid overwriting current value
|
||||
// on paused animation continuation
|
||||
if (currentVec && fromVec) {
|
||||
*currentVec = *fromVec;
|
||||
}
|
||||
}
|
||||
|
||||
// ensure velocity values
|
||||
if (!velocityVec) {
|
||||
velocityVec = VectorRef(Vector::new_vector(valueCount, NULL));
|
||||
}
|
||||
if (!originalVelocityVec) {
|
||||
originalVelocityVec = VectorRef(Vector::new_vector(valueCount, NULL));
|
||||
}
|
||||
}
|
||||
|
||||
// ensure distance value initialized
|
||||
// depends on current value set on one time start
|
||||
if (NULL == distanceVec) {
|
||||
|
||||
// not yet started animations may not have current value
|
||||
VectorRef fromVec2 = NULL != currentVec ? currentVec : fromVec;
|
||||
|
||||
if (fromVec2 && toVec) {
|
||||
Vector4r distance = toVec->vector4r();
|
||||
distance -= fromVec2->vector4r();
|
||||
|
||||
if (0 != distance.squaredNorm()) {
|
||||
distanceVec = VectorRef(Vector::new_vector(valueCount, distance));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
virtual void reset(bool all) {
|
||||
_POPAnimationState::reset(all);
|
||||
|
||||
if (all) {
|
||||
currentVec = NULL;
|
||||
previousVec = NULL;
|
||||
previous2Vec = NULL;
|
||||
}
|
||||
progress = 0;
|
||||
resetProgressMarkerState();
|
||||
didReachToValue = false;
|
||||
distanceVec = NULL;
|
||||
}
|
||||
|
||||
void clampCurrentValue(NSUInteger clamp)
|
||||
{
|
||||
if (kPOPAnimationClampNone == clamp)
|
||||
return;
|
||||
|
||||
// Clamp all vector values
|
||||
CGFloat *currentValues = currentVec->data();
|
||||
const CGFloat *fromValues = fromVec->data();
|
||||
const CGFloat *toValues = toVec->data();
|
||||
|
||||
for (NSUInteger idx = 0; idx < valueCount; idx++) {
|
||||
clampValue(currentValues[idx], fromValues[idx], toValues[idx], clamp);
|
||||
}
|
||||
}
|
||||
|
||||
void clampCurrentValue()
|
||||
{
|
||||
clampCurrentValue(clampMode);
|
||||
}
|
||||
};
|
||||
|
||||
typedef struct _POPPropertyAnimationState POPPropertyAnimationState;
|
||||
|
||||
@interface POPPropertyAnimation ()
|
||||
|
||||
@end
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <pop/POPPropertyAnimation.h>
|
||||
|
||||
/**
|
||||
@abstract A concrete spring animation class.
|
||||
@discussion Animation is achieved through modeling spring dynamics.
|
||||
*/
|
||||
@interface POPSpringAnimation : POPPropertyAnimation
|
||||
|
||||
/**
|
||||
@abstract The designated initializer.
|
||||
@returns An instance of a spring animation.
|
||||
*/
|
||||
+ (instancetype)animation;
|
||||
|
||||
/**
|
||||
@abstract Convenience initializer that returns an animation with animatable property of name.
|
||||
@param name The name of the animatable property.
|
||||
@returns An instance of a spring animation configured with specified animatable property.
|
||||
*/
|
||||
+ (instancetype)animationWithPropertyNamed:(NSString *)name;
|
||||
|
||||
/**
|
||||
@abstract The current velocity value.
|
||||
@discussion Set before animation start to account for initial velocity. Expressed in change of value units per second.
|
||||
*/
|
||||
@property (copy, nonatomic) id velocity;
|
||||
|
||||
/**
|
||||
@abstract The effective bounciness.
|
||||
@discussion Use in conjunction with 'springSpeed' to change animation effect. Values are converted into corresponding dynamics constants. Defined as a value in the range [0, 20]. Defaults to 4.
|
||||
*/
|
||||
@property (assign, nonatomic) CGFloat springBounciness;
|
||||
|
||||
/**
|
||||
@abstract The effective speed.
|
||||
@discussion Use in conjunction with 'springBounciness' to change animation effect. Values are converted into corresponding dynamics constants. Defined as a value in the range [0, 20]. Defaults to 12.
|
||||
*/
|
||||
@property (assign, nonatomic) CGFloat springSpeed;
|
||||
|
||||
/**
|
||||
@abstract The tension used in the dynamics simulation.
|
||||
@discussion Can be used over bounciness and speed for finer grain tweaking of animation effect.
|
||||
*/
|
||||
@property (assign, nonatomic) CGFloat dynamicsTension;
|
||||
|
||||
/**
|
||||
@abstract The friction used in the dynamics simulation.
|
||||
@discussion Can be used over bounciness and speed for finer grain tweaking of animation effect.
|
||||
*/
|
||||
@property (assign, nonatomic) CGFloat dynamicsFriction;
|
||||
|
||||
/**
|
||||
@abstract The mass used in the dynamics simulation.
|
||||
@discussion Can be used over bounciness and speed for finer grain tweaking of animation effect.
|
||||
*/
|
||||
@property (assign, nonatomic) CGFloat dynamicsMass;
|
||||
|
||||
@end
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPSpringAnimationInternal.h"
|
||||
|
||||
@implementation POPSpringAnimation
|
||||
|
||||
#pragma mark - Lifecycle
|
||||
|
||||
#undef __state
|
||||
#define __state ((POPSpringAnimationState *)_state)
|
||||
|
||||
+ (instancetype)animation
|
||||
{
|
||||
return [[self alloc] init];
|
||||
}
|
||||
|
||||
+ (instancetype)animationWithPropertyNamed:(NSString *)aName
|
||||
{
|
||||
POPSpringAnimation *anim = [self animation];
|
||||
anim.property = [POPAnimatableProperty propertyWithName:aName];
|
||||
return anim;
|
||||
}
|
||||
|
||||
- (void)_initState
|
||||
{
|
||||
_state = new POPSpringAnimationState(self);
|
||||
}
|
||||
|
||||
- (id)init
|
||||
{
|
||||
self = [super _init];
|
||||
if (nil != self) {
|
||||
__state->solver = new SpringSolver4d(1, 1, 1);
|
||||
__state->updatedDynamicsThreshold();
|
||||
__state->updatedBouncinessAndSpeed();
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
if (__state) {
|
||||
delete __state->solver;
|
||||
__state->solver = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Properties
|
||||
|
||||
- (id)velocity
|
||||
{
|
||||
return POPBox(__state->velocityVec, __state->valueType);
|
||||
}
|
||||
|
||||
- (void)setVelocity:(id)aValue
|
||||
{
|
||||
POPPropertyAnimationState *s = __state;
|
||||
VectorRef vec = POPUnbox(aValue, s->valueType, s->valueCount, YES);
|
||||
if (!vec_equal(vec, s->velocityVec)) {
|
||||
s->velocityVec = vec;
|
||||
|
||||
if (s->tracing) {
|
||||
[s->tracer updateVelocity:aValue];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DEFINE_RW_PROPERTY(POPSpringAnimationState, dynamicsTension, setDynamicsTension:, CGFloat, [self _updatedDynamicsTension];);
|
||||
DEFINE_RW_PROPERTY(POPSpringAnimationState, dynamicsFriction, setDynamicsFriction:, CGFloat, [self _updatedDynamicsFriction];);
|
||||
DEFINE_RW_PROPERTY(POPSpringAnimationState, dynamicsMass, setDynamicsMass:, CGFloat, [self _updatedDynamicsMass];);
|
||||
|
||||
FB_PROPERTY_GET(POPSpringAnimationState, springSpeed, CGFloat);
|
||||
- (void)setSpringSpeed:(CGFloat)aFloat
|
||||
{
|
||||
POPSpringAnimationState *s = __state;
|
||||
if (s->userSpecifiedDynamics || aFloat != s->springSpeed) {
|
||||
s->springSpeed = aFloat;
|
||||
s->userSpecifiedDynamics = false;
|
||||
s->updatedBouncinessAndSpeed();
|
||||
if (s->tracing) {
|
||||
[s->tracer updateSpeed:aFloat];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
FB_PROPERTY_GET(POPSpringAnimationState, springBounciness, CGFloat);
|
||||
- (void)setSpringBounciness:(CGFloat)aFloat
|
||||
{
|
||||
POPSpringAnimationState *s = __state;
|
||||
if (s->userSpecifiedDynamics || aFloat != s->springBounciness) {
|
||||
s->springBounciness = aFloat;
|
||||
s->userSpecifiedDynamics = false;
|
||||
s->updatedBouncinessAndSpeed();
|
||||
if (s->tracing) {
|
||||
[s->tracer updateBounciness:aFloat];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (SpringSolver4d *)solver
|
||||
{
|
||||
return __state->solver;
|
||||
}
|
||||
|
||||
- (void)setSolver:(SpringSolver4d *)aSolver
|
||||
{
|
||||
if (aSolver != __state->solver) {
|
||||
if (__state->solver) {
|
||||
delete(__state->solver);
|
||||
}
|
||||
__state->solver = aSolver;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Utility
|
||||
|
||||
- (void)_updatedDynamicsTension
|
||||
{
|
||||
__state->userSpecifiedDynamics = true;
|
||||
if(__state->tracing) {
|
||||
[__state->tracer updateTension:__state->dynamicsTension];
|
||||
}
|
||||
__state->updatedDynamics();
|
||||
}
|
||||
|
||||
- (void)_updatedDynamicsFriction
|
||||
{
|
||||
__state->userSpecifiedDynamics = true;
|
||||
if(__state->tracing) {
|
||||
[__state->tracer updateFriction:__state->dynamicsFriction];
|
||||
}
|
||||
__state->updatedDynamics();
|
||||
}
|
||||
|
||||
- (void)_updatedDynamicsMass
|
||||
{
|
||||
__state->userSpecifiedDynamics = true;
|
||||
if(__state->tracing) {
|
||||
[__state->tracer updateMass:__state->dynamicsMass];
|
||||
}
|
||||
__state->updatedDynamics();
|
||||
}
|
||||
|
||||
- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug
|
||||
{
|
||||
[super _appendDescription:s debug:debug];
|
||||
|
||||
if (debug) {
|
||||
if (_state->userSpecifiedDynamics) {
|
||||
[s appendFormat:@"; dynamics = (tension:%f, friction:%f, mass:%f)", __state->dynamicsTension, __state->dynamicsFriction, __state->dynamicsMass];
|
||||
} else {
|
||||
[s appendFormat:@"; bounciness = %f; speed = %f", __state->springBounciness, __state->springSpeed];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPAnimationExtras.h"
|
||||
#import "POPPropertyAnimationInternal.h"
|
||||
|
||||
struct _POPSpringAnimationState : _POPPropertyAnimationState
|
||||
{
|
||||
SpringSolver4d *solver;
|
||||
CGFloat springSpeed;
|
||||
CGFloat springBounciness; // normalized springiness
|
||||
CGFloat dynamicsTension; // tension
|
||||
CGFloat dynamicsFriction; // friction
|
||||
CGFloat dynamicsMass; // mass
|
||||
|
||||
_POPSpringAnimationState(id __unsafe_unretained anim) : _POPPropertyAnimationState(anim),
|
||||
solver(nullptr),
|
||||
springSpeed(12.),
|
||||
springBounciness(4.),
|
||||
dynamicsTension(0),
|
||||
dynamicsFriction(0),
|
||||
dynamicsMass(0)
|
||||
{
|
||||
type = kPOPAnimationSpring;
|
||||
}
|
||||
|
||||
bool hasConverged()
|
||||
{
|
||||
NSUInteger count = valueCount;
|
||||
if (shouldRound()) {
|
||||
return vec_equal(previous2Vec, previousVec) && vec_equal(previousVec, toVec);
|
||||
} else {
|
||||
if (!previousVec || !previous2Vec)
|
||||
return false;
|
||||
|
||||
CGFloat t = dynamicsThreshold / 5;
|
||||
|
||||
const CGFloat *toValues = toVec->data();
|
||||
const CGFloat *previousValues = previousVec->data();
|
||||
const CGFloat *previous2Values = previous2Vec->data();
|
||||
|
||||
for (NSUInteger idx = 0; idx < count; idx++) {
|
||||
if ((fabsf(toValues[idx] - previousValues[idx]) >= t) || (fabsf(previous2Values[idx] - previousValues[idx]) >= t)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool isDone() {
|
||||
if (_POPPropertyAnimationState::isDone()) {
|
||||
return true;
|
||||
}
|
||||
return solver->started() && (hasConverged() || solver->hasConverged());
|
||||
}
|
||||
|
||||
void updatedDynamics()
|
||||
{
|
||||
if (NULL != solver) {
|
||||
solver->setConstants(dynamicsTension, dynamicsFriction, dynamicsMass);
|
||||
}
|
||||
}
|
||||
|
||||
void updatedDynamicsThreshold()
|
||||
{
|
||||
_POPPropertyAnimationState::updatedDynamicsThreshold();
|
||||
if (NULL != solver) {
|
||||
solver->setThreshold(dynamicsThreshold);
|
||||
}
|
||||
}
|
||||
|
||||
void updatedBouncinessAndSpeed() {
|
||||
[POPSpringAnimation convertBounciness:springBounciness speed:springSpeed toTension:&dynamicsTension friction:&dynamicsFriction mass:&dynamicsMass];
|
||||
updatedDynamics();
|
||||
}
|
||||
|
||||
bool advance(CFTimeInterval time, CFTimeInterval dt, id obj) {
|
||||
// advance past not yet initialized animations
|
||||
if (NULL == currentVec) {
|
||||
return false;
|
||||
}
|
||||
|
||||
CFTimeInterval localTime = time - startTime;
|
||||
|
||||
Vector4d value = vector4d(currentVec);
|
||||
Vector4d toValue = vector4d(toVec);
|
||||
Vector4d velocity = vector4d(velocityVec);
|
||||
|
||||
SSState4d state;
|
||||
state.p = toValue - value;
|
||||
|
||||
// the solver assumes a spring of size zero
|
||||
// flip the velocity from user perspective to solver perspective
|
||||
state.v = velocity * -1;
|
||||
|
||||
solver->advance(state, localTime, dt);
|
||||
value = toValue - state.p;
|
||||
|
||||
// flip velocity back to user perspective
|
||||
velocity = state.v * -1;
|
||||
|
||||
*currentVec = value;
|
||||
|
||||
if (velocityVec) {
|
||||
*velocityVec = velocity;
|
||||
}
|
||||
|
||||
clampCurrentValue();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual void reset(bool all) {
|
||||
_POPPropertyAnimationState::reset(all);
|
||||
|
||||
if (solver) {
|
||||
solver->setConstants(dynamicsTension, dynamicsFriction, dynamicsMass);
|
||||
solver->reset();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
typedef struct _POPSpringAnimationState POPSpringAnimationState;
|
||||
Generated
+190
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "POPVector.h"
|
||||
|
||||
namespace POP {
|
||||
|
||||
template <typename T>
|
||||
struct SSState
|
||||
{
|
||||
T p;
|
||||
T v;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct SSDerivative
|
||||
{
|
||||
T dp;
|
||||
T dv;
|
||||
};
|
||||
|
||||
typedef SSState<Vector4d> SSState4d;
|
||||
typedef SSDerivative<Vector4d> SSDerivative4d;
|
||||
|
||||
const CFTimeInterval solverDt = 0.001f;
|
||||
const CFTimeInterval maxSolverDt = 30.0f;
|
||||
|
||||
/**
|
||||
Templated spring solver class.
|
||||
*/
|
||||
template <typename T>
|
||||
class SpringSolver
|
||||
{
|
||||
double _k; // stiffness
|
||||
double _b; // dampening
|
||||
double _m; // mass
|
||||
|
||||
double _tp; // threshold
|
||||
double _tv; // threshold velocity
|
||||
double _ta; // threshold acceleration
|
||||
|
||||
CFTimeInterval _accumulatedTime;
|
||||
SSState<T> _lastState;
|
||||
T _lastDv;
|
||||
bool _started;
|
||||
|
||||
public:
|
||||
SpringSolver(double k, double b, double m = 1) : _k(k), _b(b), _m(m), _started(false)
|
||||
{
|
||||
_accumulatedTime = 0;
|
||||
_lastState.p = T::Zero();
|
||||
_lastState.v = T::Zero();
|
||||
_lastDv = T::Zero();
|
||||
setThreshold(1.);
|
||||
}
|
||||
|
||||
~SpringSolver()
|
||||
{
|
||||
}
|
||||
|
||||
bool started()
|
||||
{
|
||||
return _started;
|
||||
}
|
||||
|
||||
void setConstants(double k, double b, double m)
|
||||
{
|
||||
_k = k;
|
||||
_b = b;
|
||||
_m = m;
|
||||
}
|
||||
|
||||
void setThreshold(double t)
|
||||
{
|
||||
_tp = t / 2; // half a unit
|
||||
_tv = 25.0 * t; // 5 units per second, squared for comparison
|
||||
_ta = 625.0 * t * t; // 5 units per second squared, squared for comparison
|
||||
}
|
||||
|
||||
T acceleration(const SSState<T> &state, double t)
|
||||
{
|
||||
return state.p*(-_k/_m) - state.v*(_b/_m);
|
||||
}
|
||||
|
||||
SSDerivative<T> evaluate(const SSState<T> &initial, double t)
|
||||
{
|
||||
SSDerivative<T> output;
|
||||
output.dp = initial.v;
|
||||
output.dv = acceleration(initial, t);
|
||||
return output;
|
||||
}
|
||||
|
||||
SSDerivative<T> evaluate(const SSState<T> &initial, double t, double dt, const SSDerivative<T> &d)
|
||||
{
|
||||
SSState<T> state;
|
||||
state.p = initial.p + d.dp*dt;
|
||||
state.v = initial.v + d.dv*dt;
|
||||
SSDerivative<T> output;
|
||||
output.dp = state.v;
|
||||
output.dv = acceleration(state, t+dt);
|
||||
return output;
|
||||
}
|
||||
|
||||
void integrate(SSState<T> &state, double t, double dt)
|
||||
{
|
||||
SSDerivative<T> a = evaluate(state, t);
|
||||
SSDerivative<T> b = evaluate(state, t, dt*0.5, a);
|
||||
SSDerivative<T> c = evaluate(state, t, dt*0.5, b);
|
||||
SSDerivative<T> d = evaluate(state, t, dt, c);
|
||||
|
||||
T dpdt = (a.dp + (b.dp + c.dp)*2.0 + d.dp) * (1.0/6.0);
|
||||
T dvdt = (a.dv + (b.dv + c.dv)*2.0 + d.dv) * (1.0/6.0);
|
||||
|
||||
state.p = state.p + dpdt*dt;
|
||||
state.v = state.v + dvdt*dt;
|
||||
|
||||
_lastDv = dvdt;
|
||||
}
|
||||
|
||||
SSState<T> interpolate(const SSState<T> &previous, const SSState<T> ¤t, double alpha)
|
||||
{
|
||||
SSState<T> state;
|
||||
state.p = current.p*alpha + previous.p*(1-alpha);
|
||||
state.v = current.v*alpha + previous.v*(1-alpha);
|
||||
return state;
|
||||
}
|
||||
|
||||
void advance(SSState<T> &state, double t, double dt)
|
||||
{
|
||||
_started = true;
|
||||
|
||||
if (dt > maxSolverDt) {
|
||||
// excessive time step, force shut down
|
||||
_lastDv = _lastState.v = _lastState.p = T::Zero();
|
||||
} else {
|
||||
_accumulatedTime += dt;
|
||||
|
||||
SSState<T> previousState = state, currentState = state;
|
||||
while (_accumulatedTime >= solverDt) {
|
||||
previousState = currentState;
|
||||
this->integrate(currentState, t, solverDt);
|
||||
t += solverDt;
|
||||
_accumulatedTime -= solverDt;
|
||||
}
|
||||
CFTimeInterval alpha = _accumulatedTime / solverDt;
|
||||
_lastState = state = this->interpolate(previousState, currentState, alpha);
|
||||
}
|
||||
}
|
||||
|
||||
bool hasConverged()
|
||||
{
|
||||
if (!_started) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (size_t idx = 0; idx < _lastState.p.size(); idx++) {
|
||||
if (fabs(_lastState.p(idx)) >= _tp) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return (_lastState.v.squaredNorm() < _tv) && (_lastDv.squaredNorm() < _ta);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
_accumulatedTime = 0;
|
||||
_lastState.p = T::Zero();
|
||||
_lastState.v = T::Zero();
|
||||
_lastDv = T::Zero();
|
||||
_started = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
Convenience spring solver type definitions.
|
||||
*/
|
||||
typedef SpringSolver<Vector2d> SpringSolver2d;
|
||||
typedef SpringSolver<Vector3d> SpringSolver3d;
|
||||
typedef SpringSolver<Vector4d> SpringSolver4d;
|
||||
}
|
||||
|
||||
Generated
+375
@@ -0,0 +1,375 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#ifndef __POP__FBVector__
|
||||
#define __POP__FBVector__
|
||||
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
#import <objc/NSObjCRuntime.h>
|
||||
#if TARGET_OS_IPHONE
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
||||
#import "POPMath.h"
|
||||
|
||||
namespace POP {
|
||||
|
||||
/** Fixed two-size vector class */
|
||||
template <typename T>
|
||||
struct Vector2
|
||||
{
|
||||
private:
|
||||
typedef T Vector2<T>::* const _data[2];
|
||||
static const _data _v;
|
||||
|
||||
public:
|
||||
T x;
|
||||
T y;
|
||||
|
||||
// Zero vector
|
||||
static const Vector2 Zero() { return Vector2(0); }
|
||||
|
||||
// Constructors
|
||||
Vector2() {}
|
||||
explicit Vector2(T v) { x = v; y = v; };
|
||||
explicit Vector2(T x0, T y0) : x(x0), y(y0) {};
|
||||
explicit Vector2(const CGPoint &p) : x(p.x), y (p.y) {}
|
||||
explicit Vector2(const CGSize &s) : x(s.width), y (s.height) {}
|
||||
|
||||
// Copy constructor
|
||||
template<typename U> explicit Vector2(const Vector2<U> &v) : x(v.x), y(v.y) {}
|
||||
|
||||
// Index operators
|
||||
const T& operator[](size_t i) const { return this->*_v[i]; }
|
||||
T& operator[](size_t i) { return this->*_v[i]; }
|
||||
const T& operator()(size_t i) const { return this->*_v[i]; }
|
||||
T& operator()(size_t i) { return this->*_v[i]; }
|
||||
|
||||
// Backing data
|
||||
T * data() { return &(this->*_v[0]); }
|
||||
const T * data() const { return &(this->*_v[0]); }
|
||||
|
||||
// Size
|
||||
inline size_t size() const { return 2; }
|
||||
|
||||
// Assignment
|
||||
Vector2 &operator= (T v) { x = v; y = v; return *this;}
|
||||
template<typename U> Vector2 &operator= (const Vector2<U> &v) { x = v.x; y = v.y; return *this;}
|
||||
|
||||
// Negation
|
||||
Vector2 operator- (void) const { return Vector2<T>(-x, -y); }
|
||||
|
||||
// Equality
|
||||
bool operator== (T v) const { return (x == v && y == v); }
|
||||
bool operator== (const Vector2 &v) const { return (x == v.x && y == v.y); }
|
||||
|
||||
// Inequality
|
||||
bool operator!= (T v) const {return (x != v || y != v); }
|
||||
bool operator!= (const Vector2 &v) const { return (x != v.x || y != v.y); }
|
||||
|
||||
// Scalar Math
|
||||
Vector2 operator+ (T v) const { return Vector2(x + v, y + v); }
|
||||
Vector2 operator- (T v) const { return Vector2(x - v, y - v); }
|
||||
Vector2 operator* (T v) const { return Vector2(x * v, y * v); }
|
||||
Vector2 operator/ (T v) const { return Vector2(x / v, y / v); }
|
||||
Vector2 &operator+= (T v) { x += v; y += v; return *this; };
|
||||
Vector2 &operator-= (T v) { x -= v; y -= v; return *this; };
|
||||
Vector2 &operator*= (T v) { x *= v; y *= v; return *this; };
|
||||
Vector2 &operator/= (T v) { x /= v; y /= v; return *this; };
|
||||
|
||||
// Vector Math
|
||||
Vector2 operator+ (const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
|
||||
Vector2 operator- (const Vector2 &v) const { return Vector2(x - v.x, y - v.y); }
|
||||
Vector2 &operator+= (const Vector2 &v) { x += v.x; y += v.y; return *this; };
|
||||
Vector2 &operator-= (const Vector2 &v) { x -= v.x; y -= v.y; return *this; };
|
||||
|
||||
// Norms
|
||||
CGFloat norm() const { return sqrtr(squaredNorm()); }
|
||||
CGFloat squaredNorm() const { return x * x + y * y; }
|
||||
|
||||
// Cast
|
||||
template<typename U> Vector2<U> cast() const { return Vector2<U>(x, y); }
|
||||
CGPoint cg_point() const { return CGPointMake(x, y); };
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
const typename Vector2<T>::_data Vector2<T>::_v = { &Vector2<T>::x, &Vector2<T>::y };
|
||||
|
||||
/** Fixed three-size vector class */
|
||||
template <typename T>
|
||||
struct Vector3
|
||||
{
|
||||
private:
|
||||
typedef T Vector3<T>::* const _data[3];
|
||||
static const _data _v;
|
||||
|
||||
public:
|
||||
T x;
|
||||
T y;
|
||||
T z;
|
||||
|
||||
// Zero vector
|
||||
static const Vector3 Zero() { return Vector3(0); };
|
||||
|
||||
// Constructors
|
||||
Vector3() {}
|
||||
explicit Vector3(T v) : x(v), y(v), z(v) {};
|
||||
explicit Vector3(T x0, T y0, T z0) : x(x0), y(y0), z(z0) {};
|
||||
|
||||
// Copy constructor
|
||||
template<typename U> explicit Vector3(const Vector3<U> &v) : x(v.x), y(v.y), z(v.z) {}
|
||||
|
||||
// Index operators
|
||||
const T& operator[](size_t i) const { return this->*_v[i]; }
|
||||
T& operator[](size_t i) { return this->*_v[i]; }
|
||||
const T& operator()(size_t i) const { return this->*_v[i]; }
|
||||
T& operator()(size_t i) { return this->*_v[i]; }
|
||||
|
||||
// Backing data
|
||||
T * data() { return &(this->*_v[0]); }
|
||||
const T * data() const { return &(this->*_v[0]); }
|
||||
|
||||
// Size
|
||||
inline size_t size() const { return 3; }
|
||||
|
||||
// Assignment
|
||||
Vector3 &operator= (T v) { x = v; y = v; z = v; return *this;}
|
||||
template<typename U> Vector3 &operator= (const Vector3<U> &v) { x = v.x; y = v.y; z = v.z; return *this;}
|
||||
|
||||
// Negation
|
||||
Vector3 operator- (void) const { return Vector3<T>(-x, -y, -z); }
|
||||
|
||||
// Equality
|
||||
bool operator== (T v) const { return (x == v && y == v && z = v); }
|
||||
bool operator== (const Vector3 &v) const { return (x == v.x && y == v.y && z == v.z); }
|
||||
|
||||
// Inequality
|
||||
bool operator!= (T v) const {return (x != v || y != v || z != v); }
|
||||
bool operator!= (const Vector3 &v) const { return (x != v.x || y != v.y || z != v.z); }
|
||||
|
||||
// Scalar Math
|
||||
Vector3 operator+ (T v) const { return Vector3(x + v, y + v, z + v); }
|
||||
Vector3 operator- (T v) const { return Vector3(x - v, y - v, z - v); }
|
||||
Vector3 operator* (T v) const { return Vector3(x * v, y * v, z * v); }
|
||||
Vector3 operator/ (T v) const { return Vector3(x / v, y / v, z / v); }
|
||||
Vector3 &operator+= (T v) { x += v; y += v; z += v; return *this; };
|
||||
Vector3 &operator-= (T v) { x -= v; y -= v; z -= v; return *this; };
|
||||
Vector3 &operator*= (T v) { x *= v; y *= v; z *= v; return *this; };
|
||||
Vector3 &operator/= (T v) { x /= v; y /= v; z /= v; return *this; };
|
||||
|
||||
// Vector Math
|
||||
Vector3 operator+ (const Vector3 &v) const { return Vector3(x + v.x, y + v.y, z + v.z); }
|
||||
Vector3 operator- (const Vector3 &v) const { return Vector3(x - v.x, y - v.y, z - v.z); }
|
||||
Vector3 &operator+= (const Vector3 &v) { x += v.x; y += v.y; z += v.z; return *this; };
|
||||
Vector3 &operator-= (const Vector3 &v) { x -= v.x; y -= v.y; z -= v.z; return *this; };
|
||||
|
||||
// Norms
|
||||
CGFloat norm() const { return sqrtr(squaredNorm()); }
|
||||
CGFloat squaredNorm() const { return x * x + y * y + z * z; }
|
||||
|
||||
// Cast
|
||||
template<typename U> Vector3<U> cast() const { return Vector3<U>(x, y, z); }
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
const typename Vector3<T>::_data Vector3<T>::_v = { &Vector3<T>::x, &Vector3<T>::y, &Vector3<T>::z };
|
||||
|
||||
/** Fixed four-size vector class */
|
||||
template <typename T>
|
||||
struct Vector4
|
||||
{
|
||||
private:
|
||||
typedef T Vector4<T>::* const _data[4];
|
||||
static const _data _v;
|
||||
|
||||
public:
|
||||
T x;
|
||||
T y;
|
||||
T z;
|
||||
T w;
|
||||
|
||||
// Zero vector
|
||||
static const Vector4 Zero() { return Vector4(0); };
|
||||
|
||||
// Constructors
|
||||
Vector4() {}
|
||||
explicit Vector4(T v) : x(v), y(v), z(v), w(v) {};
|
||||
explicit Vector4(T x0, T y0, T z0, T w0) : x(x0), y(y0), z(z0), w(w0) {};
|
||||
|
||||
// Copy constructor
|
||||
template<typename U> explicit Vector4(const Vector4<U> &v) : x(v.x), y(v.y), z(v.z), w(v.w) {}
|
||||
|
||||
// Index operators
|
||||
const T& operator[](size_t i) const { return this->*_v[i]; }
|
||||
T& operator[](size_t i) { return this->*_v[i]; }
|
||||
const T& operator()(size_t i) const { return this->*_v[i]; }
|
||||
T& operator()(size_t i) { return this->*_v[i]; }
|
||||
|
||||
// Backing data
|
||||
T * data() { return &(this->*_v[0]); }
|
||||
const T * data() const { return &(this->*_v[0]); }
|
||||
|
||||
// Size
|
||||
inline size_t size() const { return 4; }
|
||||
|
||||
// Assignment
|
||||
Vector4 &operator= (T v) { x = v; y = v; z = v; w = v; return *this;}
|
||||
template<typename U> Vector4 &operator= (const Vector4<U> &v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this;}
|
||||
|
||||
// Negation
|
||||
Vector4 operator- (void) const { return Vector4<T>(-x, -y, -z, -w); }
|
||||
|
||||
// Equality
|
||||
bool operator== (T v) const { return (x == v && y == v && z = v, w = v); }
|
||||
bool operator== (const Vector4 &v) const { return (x == v.x && y == v.y && z == v.z && w == v.w); }
|
||||
|
||||
// Inequality
|
||||
bool operator!= (T v) const {return (x != v || y != v || z != v || w != v); }
|
||||
bool operator!= (const Vector4 &v) const { return (x != v.x || y != v.y || z != v.z || w != v.w); }
|
||||
|
||||
// Scalar Math
|
||||
Vector4 operator+ (T v) const { return Vector4(x + v, y + v, z + v, w + v); }
|
||||
Vector4 operator- (T v) const { return Vector4(x - v, y - v, z - v, w - v); }
|
||||
Vector4 operator* (T v) const { return Vector4(x * v, y * v, z * v, w * v); }
|
||||
Vector4 operator/ (T v) const { return Vector4(x / v, y / v, z / v, w / v); }
|
||||
Vector4 &operator+= (T v) { x += v; y += v; z += v; w += v; return *this; };
|
||||
Vector4 &operator-= (T v) { x -= v; y -= v; z -= v; w -= v; return *this; };
|
||||
Vector4 &operator*= (T v) { x *= v; y *= v; z *= v; w *= v; return *this; };
|
||||
Vector4 &operator/= (T v) { x /= v; y /= v; z /= v; w /= v; return *this; };
|
||||
|
||||
// Vector Math
|
||||
Vector4 operator+ (const Vector4 &v) const { return Vector4(x + v.x, y + v.y, z + v.z, w + v.w); }
|
||||
Vector4 operator- (const Vector4 &v) const { return Vector4(x - v.x, y - v.y, z - v.z, w - v.w); }
|
||||
Vector4 &operator+= (const Vector4 &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; };
|
||||
Vector4 &operator-= (const Vector4 &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; };
|
||||
|
||||
// Norms
|
||||
CGFloat norm() const { return sqrtr(squaredNorm()); }
|
||||
CGFloat squaredNorm() const { return x * x + y * y + z * z + w * w; }
|
||||
|
||||
// Cast
|
||||
template<typename U> Vector4<U> cast() const { return Vector4<U>(x, y, z, w); }
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
const typename Vector4<T>::_data Vector4<T>::_v = { &Vector4<T>::x, &Vector4<T>::y, &Vector4<T>::z, &Vector4<T>::w };
|
||||
|
||||
/** Convenience typedefs */
|
||||
typedef Vector2<float> Vector2f;
|
||||
typedef Vector2<double> Vector2d;
|
||||
typedef Vector2<CGFloat> Vector2r;
|
||||
typedef Vector3<float> Vector3f;
|
||||
typedef Vector3<double> Vector3d;
|
||||
typedef Vector3<CGFloat> Vector3r;
|
||||
typedef Vector4<float> Vector4f;
|
||||
typedef Vector4<double> Vector4d;
|
||||
typedef Vector4<CGFloat> Vector4r;
|
||||
|
||||
/** Variable-sized vector class */
|
||||
class Vector
|
||||
{
|
||||
size_t _count;
|
||||
CGFloat *_values;
|
||||
|
||||
private:
|
||||
Vector(size_t);
|
||||
Vector(const Vector& other);
|
||||
|
||||
public:
|
||||
~Vector();
|
||||
|
||||
// Creates a new vector instance of count with values. Initializing a vector of size 0 returns NULL.
|
||||
static Vector *new_vector(NSUInteger count, const CGFloat *values);
|
||||
|
||||
// Creates a new vector given a pointer to another. Can return NULL.
|
||||
static Vector *new_vector(const Vector * const other);
|
||||
|
||||
// Creates a variable size vector given a static vector and count.
|
||||
static Vector *new_vector(NSUInteger count, Vector4r vec);
|
||||
|
||||
// Size of vector
|
||||
NSUInteger size() const { return _count; }
|
||||
|
||||
// Returns array of values
|
||||
CGFloat *data () { return _values; }
|
||||
const CGFloat *data () const { return _values; };
|
||||
|
||||
// Vector2r support
|
||||
Vector2r vector2r() const;
|
||||
|
||||
// Vector4r support
|
||||
Vector4r vector4r() const;
|
||||
|
||||
// CGFloat support
|
||||
static Vector *new_cg_float(CGFloat f);
|
||||
|
||||
// CGPoint support
|
||||
CGPoint cg_point() const;
|
||||
static Vector *new_cg_point(const CGPoint &p);
|
||||
|
||||
// CGSize support
|
||||
CGSize cg_size() const;
|
||||
static Vector *new_cg_size(const CGSize &s);
|
||||
|
||||
// CGRect support
|
||||
CGRect cg_rect() const;
|
||||
static Vector *new_cg_rect(const CGRect &r);
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
// UIEdgeInsets support
|
||||
UIEdgeInsets ui_edge_insets() const;
|
||||
static Vector *new_ui_edge_insets(const UIEdgeInsets &i);
|
||||
#endif
|
||||
|
||||
// CGAffineTransform support
|
||||
CGAffineTransform cg_affine_transform() const;
|
||||
static Vector *new_cg_affine_transform(const CGAffineTransform &t);
|
||||
|
||||
// CGColorRef support
|
||||
CGColorRef cg_color() const CF_RETURNS_RETAINED;
|
||||
static Vector *new_cg_color(CGColorRef color);
|
||||
|
||||
// operator overloads
|
||||
CGFloat &operator[](size_t i) const {
|
||||
NSCAssert(size() > i, @"unexpected vector size:%lu", (unsigned long)size());
|
||||
return _values[i];
|
||||
}
|
||||
|
||||
// Returns the mathematical length
|
||||
CGFloat norm() const;
|
||||
CGFloat squaredNorm() const;
|
||||
|
||||
// Round to nearest sub
|
||||
void subRound(CGFloat sub);
|
||||
|
||||
// Returns string description
|
||||
NSString * toString() const;
|
||||
|
||||
// Operator overloads
|
||||
template<typename U> Vector& operator= (const Vector4<U>& other) {
|
||||
size_t count = MIN(_count, other.size());
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
_values[i] = other[i];
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
Vector& operator= (const Vector& other);
|
||||
void swap(Vector &first, Vector &second);
|
||||
bool operator==(const Vector &other) const;
|
||||
bool operator!=(const Vector &other) const;
|
||||
};
|
||||
|
||||
/** Convenience typedefs */
|
||||
typedef std::shared_ptr<Vector> VectorRef;
|
||||
typedef std::shared_ptr<const Vector> VectorConstRef;
|
||||
|
||||
}
|
||||
#endif /* defined(__POP__FBVector__) */
|
||||
Generated
+301
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
All rights reserved.
|
||||
|
||||
This source code is licensed under the BSD-style license found in the
|
||||
LICENSE file in the root directory of this source tree. An additional grant
|
||||
of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
#import "POPVector.h"
|
||||
#import "POPCGUtils.h"
|
||||
|
||||
namespace POP
|
||||
{
|
||||
|
||||
Vector::Vector(const size_t count)
|
||||
{
|
||||
_count = count;
|
||||
_values = 0 != count ? (CGFloat *)calloc(count, sizeof(CGFloat)) : NULL;
|
||||
}
|
||||
|
||||
Vector::Vector(const Vector& other)
|
||||
{
|
||||
_count = other.size();
|
||||
_values = 0 != _count ? (CGFloat *)calloc(_count, sizeof(CGFloat)) : NULL;
|
||||
if (0 != _count) {
|
||||
memcpy(_values, other.data(), _count * sizeof(CGFloat));
|
||||
}
|
||||
}
|
||||
|
||||
Vector::~Vector()
|
||||
{
|
||||
if (NULL != _values) {
|
||||
free(_values);
|
||||
_values = NULL;
|
||||
}
|
||||
_count = 0;
|
||||
}
|
||||
|
||||
void Vector::swap(Vector &first, Vector &second)
|
||||
{
|
||||
using std::swap;
|
||||
swap(first._count, second._count);
|
||||
swap(first._values, second._values);
|
||||
}
|
||||
|
||||
Vector& Vector::operator=(const Vector& other)
|
||||
{
|
||||
Vector temp(other);
|
||||
swap(*this, temp);
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool Vector::operator==(const Vector &other) const {
|
||||
if (_count != other.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const CGFloat * const values = other.data();
|
||||
|
||||
for (NSUInteger idx = 0; idx < _count; idx++) {
|
||||
if (_values[idx] != values[idx]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Vector::operator!=(const Vector &other) const {
|
||||
if (_count == other.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const CGFloat * const values = other.data();
|
||||
|
||||
for (NSUInteger idx = 0; idx < _count; idx++) {
|
||||
if (_values[idx] != values[idx]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Vector *Vector::new_vector(NSUInteger count, const CGFloat *values)
|
||||
{
|
||||
if (0 == count) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Vector *v = new Vector(count);
|
||||
if (NULL != values) {
|
||||
memcpy(v->_values, values, count * sizeof(CGFloat));
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
Vector *Vector::new_vector(const Vector * const other)
|
||||
{
|
||||
if (NULL == other) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return Vector::new_vector(other->size(), other->data());
|
||||
}
|
||||
|
||||
Vector *Vector::new_vector(NSUInteger count, Vector4r vec)
|
||||
{
|
||||
if (0 == count) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Vector *v = new Vector(count);
|
||||
|
||||
NSCAssert(count <= 4, @"unexpected count %lu", (unsigned long)count);
|
||||
for (NSUInteger i = 0; i < MIN(count, (NSUInteger)4); i++) {
|
||||
v->_values[i] = vec[i];
|
||||
}
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
Vector4r Vector::vector4r() const
|
||||
{
|
||||
Vector4r v = Vector4r::Zero();
|
||||
for (size_t i = 0; i < _count; i++) {
|
||||
v(i) = _values[i];
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
Vector2r Vector::vector2r() const
|
||||
{
|
||||
Vector2r v = Vector2r::Zero();
|
||||
if (_count > 0) v(0) = _values[0];
|
||||
if (_count > 1) v(1) = _values[1];
|
||||
return v;
|
||||
}
|
||||
|
||||
Vector *Vector::new_cg_float(CGFloat f)
|
||||
{
|
||||
Vector *v = new Vector(1);
|
||||
v->_values[0] = f;
|
||||
return v;
|
||||
}
|
||||
|
||||
CGPoint Vector::cg_point () const
|
||||
{
|
||||
Vector2r v = vector2r();
|
||||
return CGPointMake(v(0), v(1));
|
||||
}
|
||||
|
||||
Vector *Vector::new_cg_point(const CGPoint &p)
|
||||
{
|
||||
Vector *v = new Vector(2);
|
||||
v->_values[0] = p.x;
|
||||
v->_values[1] = p.y;
|
||||
return v;
|
||||
}
|
||||
|
||||
CGSize Vector::cg_size () const
|
||||
{
|
||||
Vector2r v = vector2r();
|
||||
return CGSizeMake(v(0), v(1));
|
||||
}
|
||||
|
||||
Vector *Vector::new_cg_size(const CGSize &s)
|
||||
{
|
||||
Vector *v = new Vector(2);
|
||||
v->_values[0] = s.width;
|
||||
v->_values[1] = s.height;
|
||||
return v;
|
||||
}
|
||||
|
||||
CGRect Vector::cg_rect() const
|
||||
{
|
||||
return _count < 4 ? CGRectZero : CGRectMake(_values[0], _values[1], _values[2], _values[3]);
|
||||
}
|
||||
|
||||
Vector *Vector::new_cg_rect(const CGRect &r)
|
||||
{
|
||||
Vector *v = new Vector(4);
|
||||
v->_values[0] = r.origin.x;
|
||||
v->_values[1] = r.origin.y;
|
||||
v->_values[2] = r.size.width;
|
||||
v->_values[3] = r.size.height;
|
||||
return v;
|
||||
}
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
|
||||
UIEdgeInsets Vector::ui_edge_insets() const
|
||||
{
|
||||
return _count < 4 ? UIEdgeInsetsZero : UIEdgeInsetsMake(_values[0], _values[1], _values[2], _values[3]);
|
||||
}
|
||||
|
||||
Vector *Vector::new_ui_edge_insets(const UIEdgeInsets &i)
|
||||
{
|
||||
Vector *v = new Vector(4);
|
||||
v->_values[0] = i.top;
|
||||
v->_values[1] = i.left;
|
||||
v->_values[2] = i.bottom;
|
||||
v->_values[3] = i.right;
|
||||
return v;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
CGAffineTransform Vector::cg_affine_transform() const
|
||||
{
|
||||
if (_count < 6) {
|
||||
return CGAffineTransformIdentity;
|
||||
}
|
||||
|
||||
NSCAssert(size() >= 6, @"unexpected vector size:%lu", (unsigned long)size());
|
||||
CGAffineTransform t;
|
||||
t.a = _values[0];
|
||||
t.b = _values[1];
|
||||
t.c = _values[2];
|
||||
t.d = _values[3];
|
||||
t.tx = _values[4];
|
||||
t.ty = _values[5];
|
||||
return t;
|
||||
}
|
||||
|
||||
Vector *Vector::new_cg_affine_transform(const CGAffineTransform &t)
|
||||
{
|
||||
Vector *v = new Vector(6);
|
||||
v->_values[0] = t.a;
|
||||
v->_values[1] = t.b;
|
||||
v->_values[2] = t.c;
|
||||
v->_values[3] = t.d;
|
||||
v->_values[4] = t.tx;
|
||||
v->_values[5] = t.ty;
|
||||
return v;
|
||||
}
|
||||
|
||||
CGColorRef Vector::cg_color() const
|
||||
{
|
||||
if (_count < 4) {
|
||||
return NULL;
|
||||
}
|
||||
return POPCGColorRGBACreate(_values);
|
||||
}
|
||||
|
||||
Vector *Vector::new_cg_color(CGColorRef color)
|
||||
{
|
||||
CGFloat rgba[4];
|
||||
POPCGColorGetRGBAComponents(color, rgba);
|
||||
return new_vector(4, rgba);
|
||||
}
|
||||
|
||||
void Vector::subRound(CGFloat sub)
|
||||
{
|
||||
for (NSUInteger idx = 0; idx < _count; idx++) {
|
||||
_values[idx] = POPSubRound(_values[idx], sub);
|
||||
}
|
||||
}
|
||||
|
||||
CGFloat Vector::norm() const
|
||||
{
|
||||
return sqrtr(squaredNorm());
|
||||
}
|
||||
|
||||
CGFloat Vector::squaredNorm() const
|
||||
{
|
||||
CGFloat d = 0;
|
||||
for (NSUInteger idx = 0; idx < _count; idx++) {
|
||||
d += (_values[idx] * _values[idx]);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
NSString * Vector::toString() const
|
||||
{
|
||||
if (0 == _count)
|
||||
return @"()";
|
||||
|
||||
if (1 == _count)
|
||||
return [NSString stringWithFormat:@"%f", _values[0]];
|
||||
|
||||
if (2 == _count)
|
||||
return [NSString stringWithFormat:@"(%.3f, %.3f)", _values[0], _values[1]];
|
||||
|
||||
NSMutableString *s = [NSMutableString stringWithCapacity:10];
|
||||
|
||||
for (NSUInteger idx = 0; idx < _count; idx++) {
|
||||
if (0 == idx) {
|
||||
[s appendFormat:@"[%.3f", _values[idx]];
|
||||
} else if (idx == _count - 1) {
|
||||
[s appendFormat:@", %.3f]", _values[idx]];
|
||||
} else {
|
||||
[s appendFormat:@", %.3f", _values[idx]];
|
||||
}
|
||||
}
|
||||
|
||||
return s;
|
||||
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Copyright (C) 2007 Apple Inc. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
|
||||
* its contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
|
||||
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef FloatConversion_h
|
||||
#define FloatConversion_h
|
||||
|
||||
#include <CoreGraphics/CGBase.h>
|
||||
|
||||
namespace WebCore {
|
||||
|
||||
template<typename T>
|
||||
float narrowPrecisionToFloat(T);
|
||||
|
||||
template<>
|
||||
inline float narrowPrecisionToFloat(double number)
|
||||
{
|
||||
return static_cast<float>(number);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
CGFloat narrowPrecisionToCGFloat(T);
|
||||
|
||||
template<>
|
||||
inline CGFloat narrowPrecisionToCGFloat(double number)
|
||||
{
|
||||
return static_cast<CGFloat>(number);
|
||||
}
|
||||
|
||||
} // namespace WebCore
|
||||
|
||||
#endif // FloatConversion_h
|
||||
+1072
File diff suppressed because it is too large.
Load diff
+277
@@ -0,0 +1,277 @@
|
||||
/*
|
||||
* Copyright (C) 2005, 2006 Apple Computer, Inc. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef TransformationMatrix_h
|
||||
#define TransformationMatrix_h
|
||||
|
||||
#include <string.h> //for memcpy
|
||||
#include <CoreGraphics/CGAffineTransform.h>
|
||||
#include <QuartzCore/QuartzCore.h>
|
||||
|
||||
namespace WebCore {
|
||||
|
||||
class TransformationMatrix {
|
||||
public:
|
||||
|
||||
typedef double Matrix4[4][4];
|
||||
|
||||
TransformationMatrix() { makeIdentity(); }
|
||||
TransformationMatrix(const TransformationMatrix& t) { *this = t; }
|
||||
TransformationMatrix(double a, double b, double c, double d, double e, double f) { setMatrix(a, b, c, d, e, f); }
|
||||
TransformationMatrix(double m11, double m12, double m13, double m14,
|
||||
double m21, double m22, double m23, double m24,
|
||||
double m31, double m32, double m33, double m34,
|
||||
double m41, double m42, double m43, double m44)
|
||||
{
|
||||
setMatrix(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44);
|
||||
}
|
||||
|
||||
void setMatrix(double a, double b, double c, double d, double e, double f)
|
||||
{
|
||||
m_matrix[0][0] = a; m_matrix[0][1] = b; m_matrix[0][2] = 0; m_matrix[0][3] = 0;
|
||||
m_matrix[1][0] = c; m_matrix[1][1] = d; m_matrix[1][2] = 0; m_matrix[1][3] = 0;
|
||||
m_matrix[2][0] = 0; m_matrix[2][1] = 0; m_matrix[2][2] = 1; m_matrix[2][3] = 0;
|
||||
m_matrix[3][0] = e; m_matrix[3][1] = f; m_matrix[3][2] = 0; m_matrix[3][3] = 1;
|
||||
}
|
||||
|
||||
void setMatrix(double m11, double m12, double m13, double m14,
|
||||
double m21, double m22, double m23, double m24,
|
||||
double m31, double m32, double m33, double m34,
|
||||
double m41, double m42, double m43, double m44)
|
||||
{
|
||||
m_matrix[0][0] = m11; m_matrix[0][1] = m12; m_matrix[0][2] = m13; m_matrix[0][3] = m14;
|
||||
m_matrix[1][0] = m21; m_matrix[1][1] = m22; m_matrix[1][2] = m23; m_matrix[1][3] = m24;
|
||||
m_matrix[2][0] = m31; m_matrix[2][1] = m32; m_matrix[2][2] = m33; m_matrix[2][3] = m34;
|
||||
m_matrix[3][0] = m41; m_matrix[3][1] = m42; m_matrix[3][2] = m43; m_matrix[3][3] = m44;
|
||||
}
|
||||
|
||||
TransformationMatrix& operator =(const TransformationMatrix &t)
|
||||
{
|
||||
setMatrix(t.m_matrix);
|
||||
return *this;
|
||||
}
|
||||
|
||||
TransformationMatrix& makeIdentity()
|
||||
{
|
||||
setMatrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool isIdentity() const
|
||||
{
|
||||
return m_matrix[0][0] == 1 && m_matrix[0][1] == 0 && m_matrix[0][2] == 0 && m_matrix[0][3] == 0 &&
|
||||
m_matrix[1][0] == 0 && m_matrix[1][1] == 1 && m_matrix[1][2] == 0 && m_matrix[1][3] == 0 &&
|
||||
m_matrix[2][0] == 0 && m_matrix[2][1] == 0 && m_matrix[2][2] == 1 && m_matrix[2][3] == 0 &&
|
||||
m_matrix[3][0] == 0 && m_matrix[3][1] == 0 && m_matrix[3][2] == 0 && m_matrix[3][3] == 1;
|
||||
}
|
||||
|
||||
// This form preserves the double math from input to output
|
||||
void map(double x, double y, double& x2, double& y2) const { multVecMatrix(x, y, x2, y2); }
|
||||
|
||||
double m11() const { return m_matrix[0][0]; }
|
||||
void setM11(double f) { m_matrix[0][0] = f; }
|
||||
double m12() const { return m_matrix[0][1]; }
|
||||
void setM12(double f) { m_matrix[0][1] = f; }
|
||||
double m13() const { return m_matrix[0][2]; }
|
||||
void setM13(double f) { m_matrix[0][2] = f; }
|
||||
double m14() const { return m_matrix[0][3]; }
|
||||
void setM14(double f) { m_matrix[0][3] = f; }
|
||||
double m21() const { return m_matrix[1][0]; }
|
||||
void setM21(double f) { m_matrix[1][0] = f; }
|
||||
double m22() const { return m_matrix[1][1]; }
|
||||
void setM22(double f) { m_matrix[1][1] = f; }
|
||||
double m23() const { return m_matrix[1][2]; }
|
||||
void setM23(double f) { m_matrix[1][2] = f; }
|
||||
double m24() const { return m_matrix[1][3]; }
|
||||
void setM24(double f) { m_matrix[1][3] = f; }
|
||||
double m31() const { return m_matrix[2][0]; }
|
||||
void setM31(double f) { m_matrix[2][0] = f; }
|
||||
double m32() const { return m_matrix[2][1]; }
|
||||
void setM32(double f) { m_matrix[2][1] = f; }
|
||||
double m33() const { return m_matrix[2][2]; }
|
||||
void setM33(double f) { m_matrix[2][2] = f; }
|
||||
double m34() const { return m_matrix[2][3]; }
|
||||
void setM34(double f) { m_matrix[2][3] = f; }
|
||||
double m41() const { return m_matrix[3][0]; }
|
||||
void setM41(double f) { m_matrix[3][0] = f; }
|
||||
double m42() const { return m_matrix[3][1]; }
|
||||
void setM42(double f) { m_matrix[3][1] = f; }
|
||||
double m43() const { return m_matrix[3][2]; }
|
||||
void setM43(double f) { m_matrix[3][2] = f; }
|
||||
double m44() const { return m_matrix[3][3]; }
|
||||
void setM44(double f) { m_matrix[3][3] = f; }
|
||||
|
||||
double a() const { return m_matrix[0][0]; }
|
||||
void setA(double a) { m_matrix[0][0] = a; }
|
||||
|
||||
double b() const { return m_matrix[0][1]; }
|
||||
void setB(double b) { m_matrix[0][1] = b; }
|
||||
|
||||
double c() const { return m_matrix[1][0]; }
|
||||
void setC(double c) { m_matrix[1][0] = c; }
|
||||
|
||||
double d() const { return m_matrix[1][1]; }
|
||||
void setD(double d) { m_matrix[1][1] = d; }
|
||||
|
||||
double e() const { return m_matrix[3][0]; }
|
||||
void setE(double e) { m_matrix[3][0] = e; }
|
||||
|
||||
double f() const { return m_matrix[3][1]; }
|
||||
void setF(double f) { m_matrix[3][1] = f; }
|
||||
|
||||
// this = this * mat
|
||||
TransformationMatrix& multiply(const TransformationMatrix&);
|
||||
|
||||
TransformationMatrix& scale(double);
|
||||
TransformationMatrix& scaleNonUniform(double sx, double sy);
|
||||
TransformationMatrix& scale3d(double sx, double sy, double sz);
|
||||
|
||||
TransformationMatrix& rotate(double d) { return rotate3d(0, 0, d); }
|
||||
TransformationMatrix& rotateFromVector(double x, double y);
|
||||
TransformationMatrix& rotate3d(double rx, double ry, double rz);
|
||||
|
||||
// The vector (x,y,z) is normalized if it's not already. A vector of
|
||||
// (0,0,0) uses a vector of (0,0,1).
|
||||
TransformationMatrix& rotate3d(double x, double y, double z, double angle);
|
||||
|
||||
TransformationMatrix& translate(double tx, double ty);
|
||||
TransformationMatrix& translate3d(double tx, double ty, double tz);
|
||||
|
||||
// translation added with a post-multiply
|
||||
TransformationMatrix& translateRight(double tx, double ty);
|
||||
TransformationMatrix& translateRight3d(double tx, double ty, double tz);
|
||||
|
||||
TransformationMatrix& flipX();
|
||||
TransformationMatrix& flipY();
|
||||
TransformationMatrix& skew(double angleX, double angleY);
|
||||
TransformationMatrix& skewX(double angle) { return skew(angle, 0); }
|
||||
TransformationMatrix& skewY(double angle) { return skew(0, angle); }
|
||||
|
||||
TransformationMatrix& applyPerspective(double p);
|
||||
bool hasPerspective() const { return m_matrix[2][3] != 0.0f; }
|
||||
|
||||
bool isInvertible() const;
|
||||
|
||||
// This method returns the identity matrix if it is not invertible.
|
||||
// Use isInvertible() before calling this if you need to know.
|
||||
TransformationMatrix inverse() const;
|
||||
|
||||
// decompose the matrix into its component parts
|
||||
typedef struct {
|
||||
double scaleX, scaleY, scaleZ;
|
||||
double skewXY, skewXZ, skewYZ;
|
||||
double rotateX, rotateY, rotateZ;
|
||||
double quaternionX, quaternionY, quaternionZ, quaternionW;
|
||||
double translateX, translateY, translateZ;
|
||||
double perspectiveX, perspectiveY, perspectiveZ, perspectiveW;
|
||||
} DecomposedType;
|
||||
|
||||
bool decompose(DecomposedType& decomp) const;
|
||||
void recompose(const DecomposedType& decomp, bool useEulerAngle = false);
|
||||
|
||||
void blend(const TransformationMatrix& from, double progress);
|
||||
|
||||
bool isAffine() const
|
||||
{
|
||||
return (m13() == 0 && m14() == 0 && m23() == 0 && m24() == 0 &&
|
||||
m31() == 0 && m32() == 0 && m33() == 1 && m34() == 0 && m43() == 0 && m44() == 1);
|
||||
}
|
||||
|
||||
// Throw away the non-affine parts of the matrix (lossy!)
|
||||
void makeAffine();
|
||||
|
||||
bool operator==(const TransformationMatrix& m2) const
|
||||
{
|
||||
return (m_matrix[0][0] == m2.m_matrix[0][0] &&
|
||||
m_matrix[0][1] == m2.m_matrix[0][1] &&
|
||||
m_matrix[0][2] == m2.m_matrix[0][2] &&
|
||||
m_matrix[0][3] == m2.m_matrix[0][3] &&
|
||||
m_matrix[1][0] == m2.m_matrix[1][0] &&
|
||||
m_matrix[1][1] == m2.m_matrix[1][1] &&
|
||||
m_matrix[1][2] == m2.m_matrix[1][2] &&
|
||||
m_matrix[1][3] == m2.m_matrix[1][3] &&
|
||||
m_matrix[2][0] == m2.m_matrix[2][0] &&
|
||||
m_matrix[2][1] == m2.m_matrix[2][1] &&
|
||||
m_matrix[2][2] == m2.m_matrix[2][2] &&
|
||||
m_matrix[2][3] == m2.m_matrix[2][3] &&
|
||||
m_matrix[3][0] == m2.m_matrix[3][0] &&
|
||||
m_matrix[3][1] == m2.m_matrix[3][1] &&
|
||||
m_matrix[3][2] == m2.m_matrix[3][2] &&
|
||||
m_matrix[3][3] == m2.m_matrix[3][3]);
|
||||
}
|
||||
|
||||
bool operator!=(const TransformationMatrix& other) const { return !(*this == other); }
|
||||
|
||||
// *this = *this * t (i.e., a multRight)
|
||||
TransformationMatrix& operator*=(const TransformationMatrix& t)
|
||||
{
|
||||
return multiply(t);
|
||||
}
|
||||
|
||||
// result = *this * t (i.e., a multRight)
|
||||
TransformationMatrix operator*(const TransformationMatrix& t)
|
||||
{
|
||||
TransformationMatrix result = *this;
|
||||
result.multiply(t);
|
||||
return result;
|
||||
}
|
||||
|
||||
CATransform3D transform3d () const;
|
||||
CGAffineTransform affineTransform () const;
|
||||
|
||||
TransformationMatrix(const CATransform3D&);
|
||||
operator CATransform3D() const;
|
||||
|
||||
TransformationMatrix(const CGAffineTransform&);
|
||||
operator CGAffineTransform() const;
|
||||
|
||||
private:
|
||||
|
||||
// multiply passed 2D point by matrix (assume z=0)
|
||||
void multVecMatrix(double x, double y, double& dstX, double& dstY) const;
|
||||
|
||||
// multiply passed 3D point by matrix
|
||||
void multVecMatrix(double x, double y, double z, double& dstX, double& dstY, double& dstZ) const;
|
||||
|
||||
void setMatrix(const Matrix4 m)
|
||||
{
|
||||
if (m && m != m_matrix)
|
||||
memcpy(m_matrix, m, sizeof(Matrix4));
|
||||
}
|
||||
|
||||
bool isIdentityOrTranslation() const
|
||||
{
|
||||
return m_matrix[0][0] == 1 && m_matrix[0][1] == 0 && m_matrix[0][2] == 0 && m_matrix[0][3] == 0 &&
|
||||
m_matrix[1][0] == 0 && m_matrix[1][1] == 1 && m_matrix[1][2] == 0 && m_matrix[1][3] == 0 &&
|
||||
m_matrix[2][0] == 0 && m_matrix[2][1] == 0 && m_matrix[2][2] == 1 && m_matrix[2][3] == 0 &&
|
||||
m_matrix[3][3] == 1;
|
||||
}
|
||||
|
||||
Matrix4 m_matrix;
|
||||
};
|
||||
|
||||
} // namespace WebCore
|
||||
|
||||
#endif // TransformationMatrix_h
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef UnitBezier_h
|
||||
#define UnitBezier_h
|
||||
|
||||
#include <math.h>
|
||||
|
||||
namespace WebCore {
|
||||
|
||||
struct UnitBezier {
|
||||
UnitBezier(double p1x, double p1y, double p2x, double p2y)
|
||||
{
|
||||
// Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
|
||||
cx = 3.0 * p1x;
|
||||
bx = 3.0 * (p2x - p1x) - cx;
|
||||
ax = 1.0 - cx -bx;
|
||||
|
||||
cy = 3.0 * p1y;
|
||||
by = 3.0 * (p2y - p1y) - cy;
|
||||
ay = 1.0 - cy - by;
|
||||
}
|
||||
|
||||
double sampleCurveX(double t)
|
||||
{
|
||||
// `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
|
||||
return ((ax * t + bx) * t + cx) * t;
|
||||
}
|
||||
|
||||
double sampleCurveY(double t)
|
||||
{
|
||||
return ((ay * t + by) * t + cy) * t;
|
||||
}
|
||||
|
||||
double sampleCurveDerivativeX(double t)
|
||||
{
|
||||
return (3.0 * ax * t + 2.0 * bx) * t + cx;
|
||||
}
|
||||
|
||||
// Given an x value, find a parametric value it came from.
|
||||
double solveCurveX(double x, double epsilon)
|
||||
{
|
||||
double t0;
|
||||
double t1;
|
||||
double t2;
|
||||
double x2;
|
||||
double d2;
|
||||
int i;
|
||||
|
||||
// First try a few iterations of Newton's method -- normally very fast.
|
||||
for (t2 = x, i = 0; i < 8; i++) {
|
||||
x2 = sampleCurveX(t2) - x;
|
||||
if (fabs (x2) < epsilon)
|
||||
return t2;
|
||||
d2 = sampleCurveDerivativeX(t2);
|
||||
if (fabs(d2) < 1e-6)
|
||||
break;
|
||||
t2 = t2 - x2 / d2;
|
||||
}
|
||||
|
||||
// Fall back to the bisection method for reliability.
|
||||
t0 = 0.0;
|
||||
t1 = 1.0;
|
||||
t2 = x;
|
||||
|
||||
if (t2 < t0)
|
||||
return t0;
|
||||
if (t2 > t1)
|
||||
return t1;
|
||||
|
||||
while (t0 < t1) {
|
||||
x2 = sampleCurveX(t2);
|
||||
if (fabs(x2 - x) < epsilon)
|
||||
return t2;
|
||||
if (x > x2)
|
||||
t0 = t2;
|
||||
else
|
||||
t1 = t2;
|
||||
t2 = (t1 - t0) * .5 + t0;
|
||||
}
|
||||
|
||||
// Failure.
|
||||
return t2;
|
||||
}
|
||||
|
||||
double solve(double x, double epsilon)
|
||||
{
|
||||
return sampleCurveY(solveCurveX(x, epsilon));
|
||||
}
|
||||
|
||||
private:
|
||||
double ax;
|
||||
double bx;
|
||||
double cx;
|
||||
|
||||
double ay;
|
||||
double by;
|
||||
double cy;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
Reference in new issue
Block a user