Merge "Size negotiation patch 1: Remove SetPreferred size" into tizen
[platform/core/uifw/dali-demo.git] / examples / dissolve-effect / dissolve-effect-example.cpp
1 /*
2  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // EXTERNAL INCLUDES
19 #include <math.h>
20
21 // INTERNAL INCLUDES
22 #include "shared/view.h"
23
24 #include <dali/dali.h>
25 #include <dali-toolkit/dali-toolkit.h>
26
27 using namespace Dali;
28
29 // LOCAL STUFF
30 namespace
31 {
32
33 const char * const TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
34 const char * const APPLICATION_TITLE_HIGHP( "Dissolve Effect(highp)" );
35 const char * const APPLICATION_TITLE_MEDIUMP( "Dissolve Effect(mediump)" );
36 const char * const EFFECT_HIGHP_IMAGE( DALI_IMAGE_DIR "icon-highp.png" );
37 const char * const EFFECT_MEDIUMP_IMAGE( DALI_IMAGE_DIR "icon-mediump.png" );
38 const char * const PLAY_ICON( DALI_IMAGE_DIR "icon-play.png" );
39 const char * const STOP_ICON( DALI_IMAGE_DIR "icon-stop.png" );
40
41 const char* IMAGES[] =
42 {
43   DALI_IMAGE_DIR "gallery-large-1.jpg",
44   DALI_IMAGE_DIR "gallery-large-2.jpg",
45   DALI_IMAGE_DIR "gallery-large-3.jpg",
46   DALI_IMAGE_DIR "gallery-large-4.jpg",
47   DALI_IMAGE_DIR "gallery-large-5.jpg",
48   DALI_IMAGE_DIR "gallery-large-6.jpg",
49   DALI_IMAGE_DIR "gallery-large-7.jpg",
50   DALI_IMAGE_DIR "gallery-large-8.jpg",
51   DALI_IMAGE_DIR "gallery-large-9.jpg",
52   DALI_IMAGE_DIR "gallery-large-10.jpg",
53   DALI_IMAGE_DIR "gallery-large-11.jpg",
54   DALI_IMAGE_DIR "gallery-large-12.jpg",
55   DALI_IMAGE_DIR "gallery-large-13.jpg",
56   DALI_IMAGE_DIR "gallery-large-14.jpg",
57   DALI_IMAGE_DIR "gallery-large-15.jpg",
58   DALI_IMAGE_DIR "gallery-large-16.jpg",
59   DALI_IMAGE_DIR "gallery-large-17.jpg",
60   DALI_IMAGE_DIR "gallery-large-18.jpg",
61   DALI_IMAGE_DIR "gallery-large-19.jpg",
62   DALI_IMAGE_DIR "gallery-large-20.jpg",
63   DALI_IMAGE_DIR "gallery-large-21.jpg",
64 };
65
66 const int NUM_IMAGES( sizeof(IMAGES) / sizeof(IMAGES[0]) );
67
68 // The duration of the current image staying on screen when slideshow is on
69 const int VIEWINGTIME = 2000; // 2 seconds
70
71 const float TRANSITION_DURATION = 2.5f; //2.5 second
72
73 const float INITIAL_DEPTH = -10.0f;
74
75 /**
76  * @brief Load an image, scaled-down to no more than the stage dimensions.
77  *
78  * Uses image scaling mode ImageAttributes::ScaleToFill to resize the image at
79  * load time to cover the entire stage with pixels with no borders,
80  * and filter mode ImageAttributes::BoxThenLinear to sample the image with
81  * maximum quality.
82  */
83 ResourceImage LoadStageFillingImage( const char * const imagePath )
84 {
85   Size stageSize = Stage::GetCurrent().GetSize();
86   ImageAttributes attributes;
87   attributes.SetSize( stageSize.x, stageSize.y );
88   attributes.SetFilterMode( ImageAttributes::BoxThenLinear );
89   attributes.SetScalingMode( ImageAttributes::ScaleToFill );
90   return ResourceImage::New( imagePath, attributes );
91 }
92
93 } // namespace
94
95 class DissolveEffectApp : public ConnectionTracker
96 {
97 public:
98
99   /**
100    * Constructor
101    * @param application class, stored as reference
102    */
103   DissolveEffectApp( Application& application );
104
105   ~DissolveEffectApp();
106
107 private:
108
109   /**
110    * This method gets called once the main loop of application is up and running
111    */
112   void OnInit( Application& application );
113   /**
114    * PanGesture callback. This method gets called when the pan gesture is detected.
115    * @param[in] actor The actor receiving the pan gesture.
116    * @param[in] gesture The detected pan gesture.
117    */
118   void OnPanGesture( Actor actor, const PanGesture& gesture );
119
120   /**
121    * Set up the animations for transition
122    * @param[in] position The point ( locates within rectange {(0,0),(0,1),(1,0),(1,1)} ) passing through the central line of the dissolve effect
123    * @param[in] displacement The direction of the central line of the dissolve effect
124    */
125   void StartTransition(Vector2 position, Vector2 displacement);
126   /**
127    * Callback function of effect-switch button
128    * Change the precision of the effect shader when the effect button is clicked
129    * @param[in] button The handle of the clicked button
130    */
131   bool OnEffectButtonClicked( Toolkit::Button button );
132   /**
133    * Callback function of slideshow button
134    * Start or stop the automatical image display when the slideshow button is clicked
135    * @param[in] button The handle of the clicked button
136    */
137   bool OnSildeshowButtonClicked( Toolkit::Button button );
138   /**
139    * Callback function of cube transition completed signal
140    * @param[in] effect The cube effect used for the transition
141    * @param[in] imageActor The target imageActor of the completed transition
142    */
143   void OnTransitionCompleted(Animation& source);
144   /**
145    * Callback function of timer tick
146    * The timer is used to count the image display duration after cube transition in slideshow,
147    */
148   bool OnTimerTick();
149
150   /**
151    * Main key event handler
152    */
153   void OnKeyEvent(const KeyEvent& event);
154
155 private:
156   Application&                    mApplication;
157   Toolkit::View                   mView;
158   Toolkit::ToolBar                mToolBar;
159   Layer                           mContent;
160   Toolkit::TextView               mTitleActor;
161   Actor                           mParent;
162
163   ImageActor                      mCurrentImage;
164   ImageActor                      mNextImage;
165   unsigned int                    mIndex;
166
167   Toolkit::DissolveEffect         mCurrentImageEffect;
168   Toolkit::DissolveEffect         mNextImageEffect;
169   bool                            mUseHighPrecision;
170   Animation                       mAnimation;
171
172   PanGestureDetector              mPanGestureDetector;
173   bool                            mIsTransiting;
174
175   bool                            mSlideshow;
176   Timer                           mViewTimer;
177   bool                            mTimerReady;
178   unsigned int                    mCentralLineIndex;
179
180   Image                           mIconPlay;
181   Image                           mIconStop;
182   Toolkit::PushButton             mPlayStopButton;
183
184   Image                           mIconHighP;
185   Image                           mIconMediumP;
186   Toolkit::PushButton             mEffectChangeButton;
187 };
188
189 DissolveEffectApp::DissolveEffectApp( Application& application )
190 : mApplication( application ),
191   mIndex( 0 ),
192   mUseHighPrecision(true),
193   mIsTransiting( false ),
194   mSlideshow( false ),
195   mTimerReady( false ),
196   mCentralLineIndex( 0 )
197 {
198   mApplication.InitSignal().Connect( this, &DissolveEffectApp::OnInit );
199 }
200
201 DissolveEffectApp::~DissolveEffectApp()
202 {
203   //Nothing to do
204 }
205
206 void DissolveEffectApp::OnInit( Application& application )
207 {
208   Stage::GetCurrent().KeyEventSignal().Connect(this, &DissolveEffectApp::OnKeyEvent);
209
210   // Creates a default view with a default tool bar, the view is added to the stage.
211   mContent = DemoHelper::CreateView( application, mView,mToolBar, "", TOOLBAR_IMAGE, "" );
212
213   // Add an effect-changing button on the right of the tool bar.
214   mIconHighP = ResourceImage::New( EFFECT_HIGHP_IMAGE );
215   mIconMediumP = ResourceImage::New( EFFECT_MEDIUMP_IMAGE );
216   mEffectChangeButton = Toolkit::PushButton::New();
217   mEffectChangeButton.SetBackgroundImage(mIconHighP);
218   mEffectChangeButton.ClickedSignal().Connect( this, &DissolveEffectApp::OnEffectButtonClicked );
219   mToolBar.AddControl( mEffectChangeButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalRight, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
220
221   // Add title to the tool bar.
222   mTitleActor = Toolkit::TextView::New();
223   mTitleActor.SetText( APPLICATION_TITLE_HIGHP );
224   mTitleActor.SetStyleToCurrentText(DemoHelper::GetDefaultTextStyle());
225   mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Toolkit::Alignment::HorizontalCenter );
226
227   // Add an slide-show button on the right of the title
228   mIconPlay = ResourceImage::New( PLAY_ICON );
229   mIconStop = ResourceImage::New( STOP_ICON );
230   mPlayStopButton = Toolkit::PushButton::New();
231   mPlayStopButton.SetBackgroundImage( mIconPlay );
232   mPlayStopButton.ClickedSignal().Connect( this, &DissolveEffectApp::OnSildeshowButtonClicked );
233   mToolBar.AddControl( mPlayStopButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalCenter, DemoHelper::DEFAULT_PLAY_PADDING );
234
235   // use pan gesture to detect the cursor or finger movement
236   mPanGestureDetector = PanGestureDetector::New();
237   mPanGestureDetector.DetectedSignal().Connect( this, &DissolveEffectApp::OnPanGesture );
238
239   // create the dissolve effect object
240   mCurrentImageEffect = Toolkit::DissolveEffect::New(mUseHighPrecision);
241   mNextImageEffect = Toolkit::DissolveEffect::New(mUseHighPrecision);
242
243   mViewTimer = Timer::New( VIEWINGTIME );
244   mViewTimer.TickSignal().Connect( this, &DissolveEffectApp::OnTimerTick );
245   mTimerReady = true;
246
247   // Set size to stage size to avoid seeing a black border on transition
248   mParent = Actor::New();
249   mParent.SetSize( Stage::GetCurrent().GetSize() );
250   mParent.SetPositionInheritanceMode( USE_PARENT_POSITION );
251   mContent.Add( mParent );
252
253   // show the first image
254   mCurrentImage = ImageActor::New( LoadStageFillingImage( IMAGES[mIndex] ) );
255   mCurrentImage.SetRelayoutEnabled( false );
256   mCurrentImage.SetPositionInheritanceMode(USE_PARENT_POSITION_PLUS_LOCAL_POSITION);
257   mCurrentImage.SetResizePolicy( FILL_TO_PARENT, ALL_DIMENSIONS );
258   mCurrentImage.SetSizeScalePolicy( FIT_WITH_ASPECT_RATIO );
259   mParent.Add( mCurrentImage );
260
261   mPanGestureDetector.Attach( mCurrentImage );
262 }
263
264 // signal handler, called when the pan gesture is detected
265 void DissolveEffectApp::OnPanGesture( Actor actor, const PanGesture& gesture )
266 {
267   // does not response when the animation has not finished
268   if( mIsTransiting || mSlideshow )
269   {
270     return;
271   }
272
273   if( gesture.state == Gesture::Continuing )
274   {
275     if( gesture.displacement.x < 0)
276     {
277       mIndex = (mIndex + 1)%NUM_IMAGES;
278     }
279     else
280     {
281       mIndex = (mIndex + NUM_IMAGES -1)%NUM_IMAGES;
282     }
283
284     Image image = LoadStageFillingImage( IMAGES[ mIndex ] );
285     mNextImage = ImageActor::New( image );
286     mNextImage.SetRelayoutEnabled( false );
287     mNextImage.SetPositionInheritanceMode(USE_PARENT_POSITION_PLUS_LOCAL_POSITION);
288     mNextImage.SetResizePolicy( FILL_TO_PARENT, ALL_DIMENSIONS );
289     mNextImage.SetSizeScalePolicy( FIT_WITH_ASPECT_RATIO );
290     mNextImage.SetZ(INITIAL_DEPTH);
291     mParent.Add( mNextImage );
292     Vector2 size = Vector2( mCurrentImage.GetCurrentSize() );
293     StartTransition( gesture.position / size, gesture.displacement * Vector2(1.0, size.x/size.y));
294   }
295 }
296
297 void DissolveEffectApp::StartTransition(Vector2 position, Vector2 displacement)
298 {
299   mAnimation = Animation::New(TRANSITION_DURATION);
300
301   mCurrentImageEffect.SetCentralLine(position,displacement);
302   mCurrentImageEffect.SetDistortion(0.0f);
303   mCurrentImage.SetShaderEffect(mCurrentImageEffect);
304   mAnimation.AnimateTo( Property(mCurrentImageEffect, mCurrentImageEffect.GetDistortionPropertyName()), 1.0f, AlphaFunctions::Linear );
305
306   mNextImage.SetOpacity(0.0f);
307   mAnimation.AnimateTo( Property( mNextImage, Actor::Property::COLOR_ALPHA ), 1.0f, AlphaFunctions::Linear );
308
309   if(mUseHighPrecision)
310   {
311     mNextImageEffect.SetCentralLine(position,-displacement);
312     mNextImageEffect.SetDistortion(1.0f);
313     mNextImage.SetShaderEffect(mNextImageEffect);
314     mAnimation.AnimateTo( Property(mNextImageEffect, mNextImageEffect.GetDistortionPropertyName()), 0.0f, AlphaFunctions::Linear );
315   }
316   else
317   {
318     mAnimation.AnimateTo( Property( mNextImage, Actor::Property::POSITION ), Vector3( 0.0f, 0.0f, 0.0f ), AlphaFunctions::Linear );
319   }
320
321   mAnimation.FinishedSignal().Connect( this, &DissolveEffectApp::OnTransitionCompleted );
322   mAnimation.Play();
323   mIsTransiting = true;
324 }
325
326 void DissolveEffectApp::OnKeyEvent(const KeyEvent& event)
327 {
328   if(event.state == KeyEvent::Down)
329   {
330     if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
331     {
332       mApplication.Quit();
333     }
334   }
335 }
336
337 bool DissolveEffectApp::OnEffectButtonClicked( Toolkit::Button button )
338 {
339   mUseHighPrecision = !mUseHighPrecision;
340   mCurrentImageEffect = Toolkit::DissolveEffect::New(mUseHighPrecision);
341   if(mUseHighPrecision)
342   {
343     mTitleActor.SetText( APPLICATION_TITLE_HIGHP );
344     mEffectChangeButton.SetBackgroundImage(mIconHighP);
345   }
346   else
347   {
348     mTitleActor.SetText( APPLICATION_TITLE_MEDIUMP );
349     mEffectChangeButton.SetBackgroundImage(mIconMediumP);
350   }
351   mTitleActor.SetStyleToCurrentText(DemoHelper::GetDefaultTextStyle());
352
353   return true;
354 }
355
356 bool DissolveEffectApp::OnSildeshowButtonClicked( Toolkit::Button button )
357 {
358   mSlideshow = !mSlideshow;
359   if( mSlideshow )
360   {
361     mPlayStopButton.SetBackgroundImage( mIconStop );
362     mPanGestureDetector.Detach( mParent );
363     mViewTimer.Start();
364     mTimerReady = false;
365   }
366   else
367   {
368     mPlayStopButton.SetBackgroundImage( mIconPlay );
369     mTimerReady = true;
370     mPanGestureDetector.Attach( mParent );
371   }
372   return true;
373 }
374
375 void DissolveEffectApp::OnTransitionCompleted( Animation& source )
376 {
377   mCurrentImage.RemoveShaderEffect();
378   mNextImage.RemoveShaderEffect();
379   mParent.Remove( mCurrentImage );
380   mPanGestureDetector.Detach( mCurrentImage );
381   mCurrentImage = mNextImage;
382   mPanGestureDetector.Attach( mCurrentImage );
383   mIsTransiting = false;
384
385   if( mSlideshow)
386   {
387     mViewTimer.Start();
388     mTimerReady = false;
389   }
390 }
391
392 bool DissolveEffectApp::OnTimerTick()
393 {
394   mTimerReady = true;
395   if(mSlideshow)
396   {
397     mIndex = (mIndex + 1)%NUM_IMAGES;
398     Image image = LoadStageFillingImage( IMAGES[ mIndex ] );
399     mNextImage = ImageActor::New( image );
400     mNextImage.SetPositionInheritanceMode(USE_PARENT_POSITION_PLUS_LOCAL_POSITION);
401     mNextImage.SetResizePolicy( FILL_TO_PARENT, ALL_DIMENSIONS );
402     mNextImage.SetSizeScalePolicy( FIT_WITH_ASPECT_RATIO );
403     mNextImage.SetZ(INITIAL_DEPTH);
404     mParent.Add( mNextImage );
405     switch( mCentralLineIndex%4 )
406     {
407       case 0:
408       {
409         StartTransition(Vector2(1.0f,0.5f), Vector2(-1.0f, 0.0f));
410         break;
411       }
412       case 1:
413       {
414         StartTransition(Vector2(0.5f,0.0f), Vector2(0.0f, 1.0f));
415         break;
416       }
417       case 2:
418       {
419         StartTransition(Vector2(0.0f,0.5f), Vector2(1.0f, 0.0f));
420         break;
421       }
422       default:
423       {
424         StartTransition(Vector2(0.5f,1.0f), Vector2(0.0f, -1.0f));
425         break;
426       }
427
428     }
429     mCentralLineIndex++;
430   }
431   return false;   //return false to stop the timer
432 }
433
434 // Entry point for Linux & Tizen applications
435 int main( int argc, char **argv )
436 {
437   Application application = Application::New( &argc, &argv );
438   DissolveEffectApp test( application );
439   application.MainLoop();
440
441   return 0;
442 }