2 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali-toolkit/internal/controls/page-turn-view/page-turn-view-impl.h>
22 #include <cstring> // for strcmp
23 #include <dali/public-api/animation/animation.h>
24 #include <dali/public-api/animation/constraint.h>
25 #include <dali/public-api/images/resource-image.h>
26 #include <dali/public-api/object/type-registry.h>
27 #include <dali/public-api/object/type-registry-helper.h>
28 #include <dali/devel-api/images/texture-set-image.h>
29 #include <dali/integration-api/debug.h>
32 #include <dali-toolkit/public-api/visuals/visual-properties.h>
33 #include <dali-toolkit/internal/controls/page-turn-view/page-turn-effect.h>
34 #include <dali-toolkit/internal/controls/page-turn-view/page-turn-book-spine-effect.h>
35 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
36 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
40 namespace //Unnamed namespace
42 // broken image is loaded if there is no valid image provided for the page
43 const char * const BROKEN_IMAGE_URL( DALI_IMAGE_DIR "broken.png");
45 // properties set on shader, these properties have the constant value in regardless of the page status
46 const char * const PROPERTY_SPINE_SHADOW ( "uSpineShadowParameter" ); // uniform for both spine and turn effect
48 // properties set on actor, the value of these properties varies depending on the page status
49 // properties used in turn effect
50 const char * const PROPERTY_TURN_DIRECTION( "uIsTurningBack" ); // uniform
51 const char * const PROPERTY_COMMON_PARAMETERS( "uCommonParameters" ); //uniform
53 const char * const PROPERTY_PAN_DISPLACEMENT( "panDisplacement" );// property used to constrain the uniforms
54 const char * const PROPERTY_PAN_CENTER( "panCenter" );// property used to constrain the uniforms
56 // default grid density for page turn effect, 20 pixels by 20 pixels
57 const float DEFAULT_GRID_DENSITY(20.0f);
59 // to bent the page, the minimal horizontal pan start position is pageSize.x * MINIMUM_START_POSITION_RATIO
60 const float MINIMUM_START_POSITION_RATIO(0.6f);
62 // the maximum vertical displacement of pan gesture, if exceed, will reduce it: pageSize.y * MAXIMUM_VERTICAL_MOVEMENT_RATIO
63 const float MAXIMUM_VERTICAL_MOVEMENT_RATIO(0.15f);
65 // when the x component of pan position reaches pageSize.x * PAGE_TURN_OVER_THRESHOLD_RATIO, page starts to turn over
66 const float PAGE_TURN_OVER_THRESHOLD_RATIO(0.5f);
68 // duration of animation, shorter for faster speed
69 const float PAGE_SLIDE_BACK_ANIMATION_DURATION(1.0f);
70 const float PAGE_TURN_OVER_ANIMATION_DURATION(1.2f);
72 // the major&minor radius (in pixels) to form an ellipse shape
73 // the top-left quarter of this ellipse is used to calculate spine normal for simulating shadow
74 const Vector2 DEFAULT_SPINE_SHADOW_PARAMETER(50.0f, 20.0f);
76 // constants for shadow casting
77 const float POINT_LIGHT_HEIGHT_RATIO(2.f);
78 const Vector4 DEFAULT_SHADOW_COLOR = Vector4(0.2f, 0.2f, 0.2f, 0.5f);
80 // constraints ////////////////////////////////////////////////////////////////
82 * Original Center Constraint
84 * This constraint adjusts the original center property of the page turn shader effect
85 * based on the X-direction displacement of the pan gesture
87 struct OriginalCenterConstraint
89 OriginalCenterConstraint(const Vector2& originalCenter, const Vector2& offset)
90 : mOldCenter( originalCenter )
92 mNewCenter = originalCenter + offset;
93 mDistance = offset.Length() * 0.5f;
94 mDirection = offset / mDistance;
97 void operator()( Vector2& current, const PropertyInputContainer& inputs )
99 float displacement = inputs[0]->GetFloat();
101 if( displacement < mDistance )
103 current = mOldCenter + mDirection * displacement;
107 current = mNewCenter + Vector2(0.25f*(displacement-mDistance), 0.f);
118 * Rotation Constraint
120 * This constraint adjusts the rotation property of the page actor
121 * based on the X-direction displacement of the pan gesture
123 struct RotationConstraint
125 RotationConstraint( float distance, float pageWidth, bool isTurnBack )
126 : mDistance( distance*0.5f )
128 mStep = 1.f / pageWidth;
129 mSign = isTurnBack ? -1.0f : 1.0f;
130 mConst = isTurnBack ? -1.0f : 0.f;
131 mRotation = isTurnBack ? Quaternion( Radian( -Math::PI ), Vector3::YAXIS ) : Quaternion( Radian(0.f), Vector3::YAXIS );
134 void operator()( Quaternion& current, const PropertyInputContainer& inputs )
136 float displacement = inputs[0]->GetFloat();
137 if( displacement < mDistance)
143 float coef = std::max(-1.0f, mStep*(mDistance-displacement));
144 float angle = Math::PI * ( mConst + mSign * coef );
145 current = Quaternion( Radian( angle ), Vector3::YAXIS );
153 Quaternion mRotation;
157 * Current Center Constraint
159 * This constraint adjusts the current center property of the page turn shader effect
160 * based on the pan position and the original center position
162 struct CurrentCenterConstraint
164 CurrentCenterConstraint( float pageWidth )
165 : mPageWidth( pageWidth )
167 mThres = pageWidth * PAGE_TURN_OVER_THRESHOLD_RATIO * 0.5f;
170 void operator()( Vector2& current, const PropertyInputContainer& inputs )
172 const Vector2& centerPosition = inputs[0]->GetVector2();
173 if( centerPosition.x > 0.f )
175 current.x = mThres+centerPosition.x * 0.5f;
176 current.y = centerPosition.y;
180 const Vector2& centerOrigin = inputs[1]->GetVector2();
181 Vector2 direction = centerOrigin - Vector2(mThres, centerPosition.y);
182 float coef = 1.f+(centerPosition.x*2.f / mPageWidth);
183 // when coef <= 0, the page is flat, slow down the last moment of the page stretch by 10 times to avoid a small bounce
186 coef = (coef+0.225f)/10.0f;
188 current = centerOrigin - direction * coef;
196 struct ShadowBlurStrengthConstraint
198 ShadowBlurStrengthConstraint( float thres )
202 void operator()( float& blurStrength, const PropertyInputContainer& inputs )
204 float displacement = inputs[2]->GetFloat();
205 if( EqualsZero(displacement))
207 const Vector2& cur = inputs[0]->GetVector2();
208 const Vector2& ori = inputs[1]->GetVector2();
209 blurStrength = 5.f*(ori-cur).Length() / mThres;
213 blurStrength = 1.f - (displacement-2.f*mThres)/mThres;
216 blurStrength = blurStrength > 1.f ? 1.f : ( blurStrength < 0.f ? 0.f : blurStrength );
222 } //unnamed namespace
238 // empty handle as we cannot create PageTurnView(but type registered for page turn signal)
242 // Setup properties, signals and actions using the type-registry.
243 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::PageTurnView, Toolkit::Control, Create );
245 DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "pageSize", VECTOR2, PAGE_SIZE )
246 DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "currentPageId", INTEGER, CURRENT_PAGE_ID )
247 DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "spineShadow", VECTOR2, SPINE_SHADOW )
249 DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pageTurnStarted", SIGNAL_PAGE_TURN_STARTED )
250 DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pageTurnFinished", SIGNAL_PAGE_TURN_FINISHED )
251 DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pagePanStarted", SIGNAL_PAGE_PAN_STARTED )
252 DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pagePanFinished", SIGNAL_PAGE_PAN_FINISHED )
254 DALI_TYPE_REGISTRATION_END()
258 // these several constants are also used in the derived classes
259 const char * const PageTurnView::PROPERTY_TEXTURE_WIDTH( "uTextureWidth" ); // uniform name
260 const char * const PageTurnView::PROPERTY_ORIGINAL_CENTER( "originalCenter" ); // property used to constrain the uniform
261 const char * const PageTurnView::PROPERTY_CURRENT_CENTER( "currentCenter" );// property used to constrain the uniform
262 const int PageTurnView::MAXIMUM_TURNING_NUM = 4;
263 const int PageTurnView::NUMBER_OF_CACHED_PAGES_EACH_SIDE = MAXIMUM_TURNING_NUM + 1;
264 const int PageTurnView::NUMBER_OF_CACHED_PAGES = NUMBER_OF_CACHED_PAGES_EACH_SIDE*2;
265 const float PageTurnView::STATIC_PAGE_INTERVAL_DISTANCE = 1.0f;
267 PageTurnView::Page::Page()
268 : isTurnBack( false )
270 actor = Actor::New();
271 actor.SetAnchorPoint( AnchorPoint::CENTER_LEFT );
272 actor.SetParentOrigin( ParentOrigin::CENTER_LEFT );
273 actor.SetVisible( false );
275 propertyPanDisplacement = actor.RegisterProperty( PROPERTY_PAN_DISPLACEMENT, 0.f );
276 propertyPanCenter = actor.RegisterProperty(PROPERTY_PAN_CENTER, Vector2::ZERO);
278 propertyOriginalCenter = actor.RegisterProperty(PROPERTY_ORIGINAL_CENTER, Vector2::ZERO);
279 propertyCurrentCenter = actor.RegisterProperty(PROPERTY_CURRENT_CENTER, Vector2::ZERO);
280 Matrix zeroMatrix(true);
281 actor.RegisterProperty(PROPERTY_COMMON_PARAMETERS, zeroMatrix);
282 propertyTurnDirection = actor.RegisterProperty(PROPERTY_TURN_DIRECTION, -1.f);
285 void PageTurnView::Page::SetImage( Image image )
289 textureSet = TextureSet::New();
292 TextureSetImage( textureSet, 0u, image );
295 void PageTurnView::Page::UseEffect(Shader newShader)
300 renderer.SetShader( shader );
304 void PageTurnView::Page::UseEffect(Shader newShader, Geometry geometry)
306 UseEffect( newShader );
310 renderer = Renderer::New( geometry, shader );
314 textureSet = TextureSet::New();
317 renderer.SetTextures( textureSet );
318 renderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
319 actor.AddRenderer( renderer );
323 void PageTurnView::Page::ChangeTurnDirection()
325 isTurnBack = !isTurnBack;
326 actor.SetProperty( propertyTurnDirection, isTurnBack ? 1.f : -1.f );
329 void PageTurnView::Page::SetPanDisplacement(float value)
331 actor.SetProperty( propertyPanDisplacement, value );
334 void PageTurnView::Page::SetPanCenter( const Vector2& value )
336 actor.SetProperty( propertyPanCenter, value );
339 void PageTurnView::Page::SetOriginalCenter( const Vector2& value )
341 actor.SetProperty( propertyOriginalCenter, value );
344 void PageTurnView::Page::SetCurrentCenter( const Vector2& value )
346 actor.SetProperty( propertyCurrentCenter, value );
349 PageTurnView::PageTurnView( PageFactory& pageFactory, const Vector2& pageSize )
350 : Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
351 mPageFactory( &pageFactory ),
352 mPageSize( pageSize ),
353 mSpineShadowParameter( DEFAULT_SPINE_SHADOW_PARAMETER ),
354 mDistanceUpCorner( 0.f ),
355 mDistanceBottomCorner( 0.f ),
356 mPanDisplacement( 0.f ),
357 mTotalPageCount( 0 ),
358 mCurrentPageIndex( 0 ),
359 mTurningPageIndex( 0 ),
362 mAnimatingCount( 0 ),
363 mConstraints( false ),
365 mPageUpdated( true ),
366 mPageTurnStartedSignal(),
367 mPageTurnFinishedSignal(),
368 mPagePanStartedSignal(),
369 mPagePanFinishedSignal()
373 PageTurnView::~PageTurnView()
377 void PageTurnView::OnInitialize()
379 // create the book spine effect for static pages
380 Property::Map spineEffectMap = CreatePageTurnBookSpineEffect();
381 mSpineEffectShader = CreateShader( spineEffectMap );
382 mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
383 // create the turn effect for turning pages
384 Property::Map turnEffectMap = CreatePageTurnEffect();
385 mTurnEffectShader = CreateShader( turnEffectMap );
386 mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
388 // create the grid geometry for pages
389 uint16_t width = static_cast<uint16_t>(mPageSize.width / DEFAULT_GRID_DENSITY + 0.5f);
390 uint16_t height = static_cast<uint16_t>(mPageSize.height / DEFAULT_GRID_DENSITY + 0.5f);
391 mGeometry = VisualFactoryCache::CreateGridGeometry( Uint16Pair( width, height ) );
393 mPages.reserve( NUMBER_OF_CACHED_PAGES );
394 for( int i = 0; i < NUMBER_OF_CACHED_PAGES; i++ )
396 mPages.push_back( Page() );
397 mPages[i].actor.SetSize( mPageSize );
398 Self().Add( mPages[i].actor );
401 // create the layer for turning images
402 mTurningPageLayer = Layer::New();
403 mTurningPageLayer.SetAnchorPoint( AnchorPoint::CENTER_LEFT );
404 mTurningPageLayer.SetBehavior(Layer::LAYER_3D);
405 mTurningPageLayer.Raise();
407 // Set control size and the parent origin of page layers
408 OnPageTurnViewInitialize();
410 Self().Add(mTurningPageLayer);
412 mTotalPageCount = static_cast<int>( mPageFactory->GetNumberOfPages() );
413 // add pages to the scene, and set depth for the stacked pages
414 for( int i = 0; i < NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++ )
417 mPages[i].actor.SetZ( -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
419 mPages[0].actor.SetVisible(true);
421 // enable the pan gesture which is attached to the control
422 EnableGestureDetection(Gesture::Type(Gesture::Pan));
425 Shader PageTurnView::CreateShader( const Property::Map& shaderMap )
428 Property::Value* shaderValue = shaderMap.Find( Toolkit::Visual::Property::SHADER, CUSTOM_SHADER );
429 Property::Map shaderSource;
430 if( shaderValue && shaderValue->Get( shaderSource ) )
432 std::string vertexShader;
433 Property::Value* vertexShaderValue = shaderSource.Find( Toolkit::Visual::Shader::Property::VERTEX_SHADER, CUSTOM_VERTEX_SHADER );
434 if( !vertexShaderValue || !vertexShaderValue->Get( vertexShader ) )
436 DALI_LOG_ERROR("PageTurnView::CreateShader failed: vertex shader source is not available.\n");
438 std::string fragmentShader;
439 Property::Value* fragmentShaderValue = shaderSource.Find( Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, CUSTOM_FRAGMENT_SHADER );
440 if( !fragmentShaderValue || !fragmentShaderValue->Get( fragmentShader ) )
442 DALI_LOG_ERROR("PageTurnView::CreateShader failed: fragment shader source is not available.\n");
444 shader = Shader::New( vertexShader, fragmentShader );
448 DALI_LOG_ERROR("PageTurnView::CreateShader failed: shader source is not available.\n");
454 void PageTurnView::SetupShadowView()
456 mShadowView = Toolkit::ShadowView::New( 0.25f, 0.25f );
457 Vector3 origin = mTurningPageLayer.GetCurrentParentOrigin();
458 mShadowView.SetParentOrigin( origin );
459 mShadowView.SetAnchorPoint( origin );
460 mShadowView.SetPointLightFieldOfView( Math::PI / 2.0f);
461 mShadowView.SetShadowColor(DEFAULT_SHADOW_COLOR);
463 mShadowPlaneBackground = Actor::New();
464 mShadowPlaneBackground.SetParentOrigin( ParentOrigin::CENTER );
465 mShadowPlaneBackground.SetSize( mControlSize );
466 Self().Add( mShadowPlaneBackground );
467 mShadowView.SetShadowPlaneBackground( mShadowPlaneBackground );
469 mPointLight = Actor::New();
470 mPointLight.SetAnchorPoint( origin );
471 mPointLight.SetParentOrigin( origin );
472 mPointLight.SetPosition( 0.f, 0.f, mPageSize.width*POINT_LIGHT_HEIGHT_RATIO );
473 Self().Add( mPointLight );
474 mShadowView.SetPointLight( mPointLight );
476 mTurningPageLayer.Add( mShadowView );
477 mShadowView.Activate();
480 void PageTurnView::OnStageConnection( int depth )
482 Control::OnStageConnection( depth );
487 void PageTurnView::OnStageDisconnection()
491 mShadowView.RemoveConstraints();
492 mPointLight.Unparent();
493 mShadowPlaneBackground.Unparent();
494 mShadowView.Unparent();
497 // make sure the status of the control is updated correctly when the pan gesture is interrupted
500 Control::OnStageDisconnection();
503 void PageTurnView::SetPageSize( const Vector2& pageSize )
505 mPageSize = pageSize;
509 mPointLight.SetPosition( 0.f, 0.f, mPageSize.width*POINT_LIGHT_HEIGHT_RATIO );
512 for( size_t i=0; i<mPages.size(); i++ )
514 mPages[i].actor.SetSize( mPageSize );
517 OnPageTurnViewInitialize();
519 if( mShadowPlaneBackground )
521 mShadowPlaneBackground.SetSize( mControlSize );
525 Vector2 PageTurnView::GetPageSize()
530 void PageTurnView::SetSpineShadowParameter( const Vector2& spineShadowParameter )
532 mSpineShadowParameter = spineShadowParameter;
534 // set spine shadow parameter to all the shader effects
535 mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
536 mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
539 Vector2 PageTurnView::GetSpineShadowParameter()
541 return mSpineShadowParameter;
544 void PageTurnView::GoToPage( unsigned int pageId )
546 int pageIdx = Clamp( static_cast<int>(pageId), 0, mTotalPageCount-1);
548 if( mCurrentPageIndex == pageIdx )
553 // if any animation ongoing, stop it.
556 // record the new current page index
557 mCurrentPageIndex = pageIdx;
560 // add the current page and the pages right before and after it
561 for( int i = pageIdx - NUMBER_OF_CACHED_PAGES_EACH_SIDE; i < pageIdx + NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++ )
566 mPages[pageId%NUMBER_OF_CACHED_PAGES].actor.SetVisible(true);
569 mPages[(pageId-1)%NUMBER_OF_CACHED_PAGES].actor.SetVisible(true);
571 // set ordered depth to the stacked pages
575 unsigned int PageTurnView::GetCurrentPage()
577 DALI_ASSERT_ALWAYS( mCurrentPageIndex >= 0 );
578 return static_cast< unsigned int >( mCurrentPageIndex );
581 void PageTurnView::AddPage( int pageIndex )
583 if(pageIndex > -1 && pageIndex < mTotalPageCount) // whether the page is available from the page factory
585 int index = pageIndex % NUMBER_OF_CACHED_PAGES;
588 newPageImage = mPageFactory->NewPage( pageIndex );
590 if( !newPageImage ) // load the broken image
592 newPageImage = ResourceImage::New( BROKEN_IMAGE_URL );
595 bool isLeftSide = ( pageIndex < mCurrentPageIndex );
596 if( mPages[index].isTurnBack != isLeftSide )
598 mPages[index].ChangeTurnDirection();
601 float degree = isLeftSide ? 180.f :0.f;
602 mPages[index].actor.SetOrientation( Degree( degree ), Vector3::YAXIS );
603 mPages[index].actor.SetVisible( false );
604 mPages[index].UseEffect( mSpineEffectShader, mGeometry );
605 mPages[index].SetImage( newPageImage );
607 // For Portrait, nothing to do
608 // For Landscape, set the parent origin to CENTER
609 OnAddPage( mPages[index].actor, isLeftSide );
613 void PageTurnView::RemovePage( int pageIndex )
615 if( pageIndex > -1 && pageIndex < mTotalPageCount)
617 int index = pageIndex % NUMBER_OF_CACHED_PAGES;
618 mPages[index].actor.SetVisible(false);
622 void PageTurnView::OnPan( const PanGesture& gesture )
624 // the pan gesture is attached to control itself instead of each page
625 switch( gesture.state )
627 case Gesture::Started:
629 // check whether the undergoing turning page number already reaches the maximum allowed
630 if( mPageUpdated && mAnimatingCount< MAXIMUM_TURNING_NUM && mSlidingCount < 1 )
632 SetPanActor( gesture.position ); // determine which page actor is panned
633 if( mTurningPageIndex != -1 && mPages[mTurningPageIndex % NUMBER_OF_CACHED_PAGES].actor.GetParent() != Self()) // if the page is added to turning layer,it is undergoing an animation currently
635 mTurningPageIndex = -1;
637 PanStarted( SetPanPosition( gesture.position ) ); // pass in the pan position in the local page coordinate
641 mTurningPageIndex = -1;
645 case Gesture::Continuing:
647 PanContinuing( SetPanPosition( gesture.position ) ); // pass in the pan position in the local page coordinate
650 case Gesture::Finished:
651 case Gesture::Cancelled:
653 PanFinished( SetPanPosition( gesture.position ), gesture.GetSpeed() );
657 case Gesture::Possible:
665 void PageTurnView::PanStarted( const Vector2& gesturePosition )
667 mPressDownPosition = gesturePosition;
669 if( mTurningPageIndex == -1 )
674 mIndex = mTurningPageIndex % NUMBER_OF_CACHED_PAGES;
676 mOriginalCenter = gesturePosition;
678 mPageUpdated = false;
680 // Guard against destruction during signal emission
681 Toolkit::PageTurnView handle( GetOwner() );
682 mPagePanStartedSignal.Emit( handle );
685 void PageTurnView::PanContinuing( const Vector2& gesturePosition )
687 if( mTurningPageIndex == -1 )
692 // Guard against destruction during signal emission
693 Toolkit::PageTurnView handle( GetOwner() );
697 // when the touch down position is near the spine
698 // or when the panning goes outwards or some other position which would tear the paper in real situation
699 // we change the start position into the current panning position and update the shader parameters
700 if( mOriginalCenter.x < mPageSize.width*MINIMUM_START_POSITION_RATIO
701 || gesturePosition.x > mOriginalCenter.x-1.0f
702 || ( ( gesturePosition.x/mOriginalCenter.x > gesturePosition.y/mOriginalCenter.y ) &&
703 ( gesturePosition.x/mOriginalCenter.x > (gesturePosition.y-mPageSize.height )/(mOriginalCenter.y-mPageSize.height ) ) ) )
705 mOriginalCenter = gesturePosition;
709 mDistanceUpCorner = mOriginalCenter.Length();
710 mDistanceBottomCorner = ( mOriginalCenter - Vector2( 0.0f, mPageSize.height ) ).Length();
711 mShadowView.Add( mPages[mIndex].actor );
712 mPages[mIndex].UseEffect( mTurnEffectShader );
713 mPages[mIndex].SetOriginalCenter( mOriginalCenter );
714 mCurrentCenter = mOriginalCenter;
715 mPages[mIndex].SetCurrentCenter( mCurrentCenter );
716 mPanDisplacement = 0.f;
717 mConstraints = false;
721 mPageTurnStartedSignal.Emit( handle, static_cast<unsigned int>(mTurningPageIndex), !mPages[mIndex].isTurnBack );
722 int id = mTurningPageIndex + (mPages[mIndex].isTurnBack ? -1 : 1);
723 if( id >=0 && id < mTotalPageCount )
725 mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetVisible(true);
728 mShadowView.RemoveConstraints();
730 mPages[mIndex].SetPanDisplacement( 0.f );
732 Constraint shadowBlurStrengthConstraint = Constraint::New<float>( mShadowView, mShadowView.GetBlurStrengthPropertyIndex(), ShadowBlurStrengthConstraint( mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO ) );
733 shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter) );
734 shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter) );
735 shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement) );
736 shadowBlurStrengthConstraint.Apply();
741 Vector2 currentCenter = gesturePosition;
743 // Test whether the new current center would tear the paper from the top pine in real situation
744 // we do not forbid this totally, which would restrict the panning gesture too much
745 // instead, set it to the nearest allowable position
746 float distanceUpCorner = currentCenter.Length();
747 float distanceBottomCorner = ( currentCenter-Vector2( 0.0f, mPageSize.height ) ).Length();
748 if( distanceUpCorner > mDistanceUpCorner )
750 currentCenter = currentCenter*mDistanceUpCorner/distanceUpCorner;
752 // would tear the paper from the bottom spine in real situation
753 if( distanceBottomCorner > mDistanceBottomCorner )
755 currentCenter = ( ( currentCenter - Vector2( 0.0f, mPageSize.height ) )*mDistanceBottomCorner/distanceBottomCorner + Vector2(0.0f,mPageSize.height ) );
757 // If direction has a very high y component, reduce it.
758 Vector2 curveDirection = currentCenter - mOriginalCenter;
759 if( fabs( curveDirection.y ) > fabs( curveDirection.x ) )
761 currentCenter.y = mOriginalCenter.y + ( currentCenter.y - mOriginalCenter.y ) * fabs( curveDirection.x/curveDirection.y );
763 // If the vertical distance is high, reduce it
764 float yShift = currentCenter.y - mOriginalCenter.y;
765 if( fabs( yShift ) > mPageSize.height * MAXIMUM_VERTICAL_MOVEMENT_RATIO )
767 currentCenter.y = mOriginalCenter.y + yShift*mPageSize.height*MAXIMUM_VERTICAL_MOVEMENT_RATIO/fabs(yShift );
770 // use contraints to control the page shape and rotation when the pan position is near the spine
771 if( currentCenter.x <= mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO && mOriginalCenter.x > mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO )
773 // set the property values used by the constraints
774 mPanDisplacement = mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO - currentCenter.x;
775 mPages[mIndex].SetPanDisplacement( mPanDisplacement );
776 mPages[mIndex].SetPanCenter( currentCenter );
778 // set up the OriginalCenterConstraint and CurrentCebterConstraint to the PageTurnEdffect
779 // also set up the RotationConstraint to the page actor
783 // the corner position need to be a little far away from the page edge to ensure the whole page is lift up
784 if( currentCenter.y >= mOriginalCenter.y )
786 corner = Vector2( 1.1f*mPageSize.width, 0.f );
790 corner = mPageSize*1.1f;
793 Vector2 offset( currentCenter-mOriginalCenter );
794 float k = - ( (mOriginalCenter.x-corner.x)*offset.x + (mOriginalCenter.y-corner.y)*offset.y )
795 /( offset.x*offset.x + offset.y*offset.y );
799 Constraint originalCenterConstraint = Constraint::New<Vector2>( mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter, OriginalCenterConstraint( mOriginalCenter, offset ));
800 originalCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement ) );
801 originalCenterConstraint.Apply();
803 Constraint currentCenterConstraint = Constraint::New<Vector2>( mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter, CurrentCenterConstraint(mPageSize.width));
804 currentCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanCenter ) );
805 currentCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter ) );
806 currentCenterConstraint.Apply();
808 PageTurnApplyInternalConstraint( mPages[mIndex].actor, mPageSize.height );
810 float distance = offset.Length();
811 Constraint rotationConstraint = Constraint::New<Quaternion>( mPages[mIndex].actor, Actor::Property::ORIENTATION, RotationConstraint(distance, mPageSize.width, mPages[mIndex].isTurnBack));
812 rotationConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement ) );
813 rotationConstraint.Apply();
820 if(mConstraints) // remove the constraint is the pan position move back to far away from the spine
822 mPages[mIndex].actor.RemoveConstraints();
823 mPages[mIndex].SetOriginalCenter(mOriginalCenter );
824 mConstraints = false;
825 mPanDisplacement = 0.f;
828 mPages[mIndex].SetCurrentCenter( currentCenter );
829 mCurrentCenter = currentCenter;
830 PageTurnApplyInternalConstraint(mPages[mIndex].actor, mPageSize.height );
835 void PageTurnView::PanFinished( const Vector2& gesturePosition, float gestureSpeed )
837 // Guard against destruction during signal emission
838 Toolkit::PageTurnView handle( GetOwner() );
840 if( mTurningPageIndex == -1 )
842 if( mAnimatingCount< MAXIMUM_TURNING_NUM && mSlidingCount < 1)
844 OnPossibleOutwardsFlick( gesturePosition, gestureSpeed );
850 mPagePanFinishedSignal.Emit( handle );
854 if(mConstraints) // if with constraints, the pan finished position is near spine, set up an animation to turn the page over
856 // update the pages here instead of in the TurnedOver callback function
857 // as new page is allowed to respond to the pan gesture before other pages finishing animation
858 if(mPages[mIndex].isTurnBack)
861 RemovePage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE );
862 AddPage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE );
867 RemovePage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE-1 );
868 AddPage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE-1 );
872 // set up an animation to turn the page over
873 float width = mPageSize.width*(1.f+PAGE_TURN_OVER_THRESHOLD_RATIO);
874 Animation animation = Animation::New( std::max(0.1f,PAGE_TURN_OVER_ANIMATION_DURATION * (1.0f - mPanDisplacement / width)) );
875 animation.AnimateTo( Property(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement),
876 width,AlphaFunction::EASE_OUT_SINE);
877 animation.AnimateTo( Property(mPages[mIndex].actor, mPages[mIndex].propertyPanCenter),
878 Vector2(-mPageSize.width*1.1f, 0.5f*mPageSize.height), AlphaFunction::EASE_OUT_SINE);
879 mAnimationPageIdPair[animation] = mTurningPageIndex;
881 animation.FinishedSignal().Connect( this, &PageTurnView::TurnedOver );
883 else // the pan finished position is far away from the spine, set up an animation to slide the page back instead of turning over
885 Animation animation= Animation::New( PAGE_SLIDE_BACK_ANIMATION_DURATION * (mOriginalCenter.x - mCurrentCenter.x) / mPageSize.width / PAGE_TURN_OVER_THRESHOLD_RATIO );
886 animation.AnimateTo( Property( mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter ),
887 mOriginalCenter, AlphaFunction::LINEAR );
888 mAnimationPageIdPair[animation] = mTurningPageIndex;
891 animation.FinishedSignal().Connect( this, &PageTurnView::SliddenBack );
893 mPageTurnStartedSignal.Emit( handle, static_cast<unsigned int>(mTurningPageIndex), mPages[mIndex].isTurnBack );
898 // In portrait view, an outwards flick should turn the previous page back
899 // In landscape view, nothing to do
900 OnPossibleOutwardsFlick( gesturePosition, gestureSpeed );
905 void PageTurnView::TurnedOver( Animation& animation )
907 int pageId = mAnimationPageIdPair[animation];
908 int index = pageId%NUMBER_OF_CACHED_PAGES;
910 mPages[index].ChangeTurnDirection();
911 mPages[index].actor.RemoveConstraints();
912 Self().Add(mPages[index].actor);
914 mAnimationPageIdPair.erase( animation );
916 float degree = mPages[index].isTurnBack ? 180.f : 0.f;
917 mPages[index].actor.SetOrientation( Degree(degree), Vector3::YAXIS );
918 mPages[index].UseEffect( mSpineEffectShader );
920 int id = pageId + (mPages[index].isTurnBack ? -1 : 1);
921 if( id >=0 && id < mTotalPageCount )
923 mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetVisible(false);
926 OnTurnedOver( mPages[index].actor, mPages[index].isTurnBack );
928 // Guard against destruction during signal emission
929 Toolkit::PageTurnView handle( GetOwner() );
930 mPageTurnFinishedSignal.Emit( handle, static_cast<unsigned int>(pageId), mPages[index].isTurnBack );
933 void PageTurnView::SliddenBack( Animation& animation )
935 int pageId = mAnimationPageIdPair[animation];
936 int index = pageId%NUMBER_OF_CACHED_PAGES;
937 Self().Add(mPages[index].actor);
940 mAnimationPageIdPair.erase( animation );
942 mPages[index].UseEffect( mSpineEffectShader );
944 int id = pageId + (mPages[index].isTurnBack ? -1 : 1);
945 if( id >=0 && id < mTotalPageCount )
947 mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetVisible(false);
950 // Guard against destruction during signal emission
951 Toolkit::PageTurnView handle( GetOwner() );
952 mPageTurnFinishedSignal.Emit( handle, static_cast<unsigned int>(pageId), mPages[index].isTurnBack );
955 void PageTurnView::OrganizePageDepth()
957 for( int i=0; i<NUMBER_OF_CACHED_PAGES_EACH_SIDE;i++ )
959 if(mCurrentPageIndex+i < mTotalPageCount)
961 mPages[( mCurrentPageIndex+i )%NUMBER_OF_CACHED_PAGES].actor.SetZ( -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
963 if( mCurrentPageIndex >= i + 1 )
965 mPages[( mCurrentPageIndex-i-1 )%NUMBER_OF_CACHED_PAGES].actor.SetZ( -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
970 void PageTurnView::StopTurning()
977 int index = mTurningPageIndex % NUMBER_OF_CACHED_PAGES;
978 Self().Add( mPages[ index ].actor );
979 mPages[ index ].actor.RemoveConstraints();
980 mPages[ index ].UseEffect( mSpineEffectShader );
981 float degree = mTurningPageIndex==mCurrentPageIndex ? 0.f :180.f;
982 mPages[index].actor.SetOrientation( Degree(degree), Vector3::YAXIS );
986 if( !mAnimationPageIdPair.empty() )
988 for (std::map<Animation,int>::iterator it=mAnimationPageIdPair.begin(); it!=mAnimationPageIdPair.end(); ++it)
990 static_cast<Animation>(it->first).SetCurrentProgress( 1.f );
995 Toolkit::PageTurnView::PageTurnSignal& PageTurnView::PageTurnStartedSignal()
997 return mPageTurnStartedSignal;
1000 Toolkit::PageTurnView::PageTurnSignal& PageTurnView::PageTurnFinishedSignal()
1002 return mPageTurnFinishedSignal;
1005 Toolkit::PageTurnView::PagePanSignal& PageTurnView::PagePanStartedSignal()
1007 return mPagePanStartedSignal;
1010 Toolkit::PageTurnView::PagePanSignal& PageTurnView::PagePanFinishedSignal()
1012 return mPagePanFinishedSignal;
1015 bool PageTurnView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1017 Dali::BaseHandle handle( object );
1019 bool connected( true );
1020 Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( handle );
1022 if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_TURN_STARTED ) )
1024 pageTurnView.PageTurnStartedSignal().Connect( tracker, functor );
1026 else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_TURN_FINISHED ) )
1028 pageTurnView.PageTurnFinishedSignal().Connect( tracker, functor );
1030 else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_PAN_STARTED ) )
1032 pageTurnView.PagePanStartedSignal().Connect( tracker, functor );
1034 else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_PAN_FINISHED ) )
1036 pageTurnView.PagePanFinishedSignal().Connect( tracker, functor );
1040 // signalName does not match any signal
1047 void PageTurnView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
1049 Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( Dali::BaseHandle( object ) );
1053 PageTurnView& pageTurnViewImpl( GetImplementation( pageTurnView ) );
1057 case Toolkit::PageTurnView::Property::PAGE_SIZE:
1059 pageTurnViewImpl.SetPageSize( value.Get<Vector2>() );
1062 case Toolkit::PageTurnView::Property::CURRENT_PAGE_ID:
1064 pageTurnViewImpl.GoToPage( value.Get<int>() );
1067 case Toolkit::PageTurnView::Property::SPINE_SHADOW:
1069 pageTurnViewImpl.SetSpineShadowParameter( value.Get<Vector2>() );
1076 Property::Value PageTurnView::GetProperty( BaseObject* object, Property::Index index )
1078 Property::Value value;
1080 Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( Dali::BaseHandle( object ) );
1084 PageTurnView& pageTurnViewImpl( GetImplementation( pageTurnView ) );
1088 case Toolkit::PageTurnView::Property::PAGE_SIZE:
1090 value = pageTurnViewImpl.GetPageSize();
1093 case Toolkit::PageTurnView::Property::CURRENT_PAGE_ID:
1095 value = static_cast<int>( pageTurnViewImpl.GetCurrentPage() );
1098 case Toolkit::PageTurnView::Property::SPINE_SHADOW:
1100 value = pageTurnViewImpl.GetSpineShadowParameter();
1108 } // namespace Internal
1110 } // namespace Toolkit