ccc056ce8da32da5edb41de91814ed4c9b8c49be
[platform/core/uifw/dali-demo.git] / examples / motion-blur / motion-blur-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 #include <sstream>
19 #include <iomanip>
20
21 #include "shared/view.h"
22 #include <dali/dali.h>
23 #include <dali-toolkit/dali-toolkit.h>
24
25 using namespace Dali;
26 using namespace Dali::Toolkit;
27
28
29
30 namespace // unnamed namespace
31 {
32
33 ////////////////////////////////////////////////////
34 //
35 // Demo setup parameters
36 //
37
38 //#define MULTIPLE_MOTION_BLURRED_ACTORS
39 #ifndef MULTIPLE_MOTION_BLURRED_ACTORS
40
41 const float MOTION_BLUR_ACTOR_WIDTH = 256;                                          // actor size on screen
42 const float MOTION_BLUR_ACTOR_HEIGHT = 256;                                         // ""
43
44 #else //#ifndef MULTIPLE_MOTION_BLURRED_ACTORS
45
46 const float MOTION_BLUR_ACTOR_WIDTH = 150;                                          // actor size on screen
47 const float MOTION_BLUR_ACTOR_HEIGHT = 112;                                         // ""
48
49 #endif //#ifndef MULTIPLE_MOTION_BLURRED_ACTORS
50
51
52 const unsigned int MOTION_BLUR_NUM_SAMPLES = 8;
53
54 const int MOTION_BLUR_NUM_ACTOR_IMAGES = 5;
55 const char* MOTION_BLUR_ACTOR_IMAGE1( DALI_IMAGE_DIR "image-with-border-1.jpg" );
56 const char* MOTION_BLUR_ACTOR_IMAGE2( DALI_IMAGE_DIR "image-with-border-2.jpg" );
57 const char* MOTION_BLUR_ACTOR_IMAGE3( DALI_IMAGE_DIR "image-with-border-3.jpg" );
58 const char* MOTION_BLUR_ACTOR_IMAGE4( DALI_IMAGE_DIR "image-with-border-4.jpg" );
59 const char* MOTION_BLUR_ACTOR_IMAGE5( DALI_IMAGE_DIR "image-with-border-1.jpg" );
60
61 const char* MOTION_BLUR_ACTOR_IMAGES[] = {
62   MOTION_BLUR_ACTOR_IMAGE1,
63   MOTION_BLUR_ACTOR_IMAGE2,
64   MOTION_BLUR_ACTOR_IMAGE3,
65   MOTION_BLUR_ACTOR_IMAGE4,
66   MOTION_BLUR_ACTOR_IMAGE5,
67 };
68
69 const int NUM_ACTOR_ANIMATIONS = 4;
70 const int NUM_CAMERA_ANIMATIONS = 2;
71
72
73 const char* BACKGROUND_IMAGE_PATH = DALI_IMAGE_DIR "background-default.png";
74
75 const char* TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
76 const char* LAYOUT_IMAGE( DALI_IMAGE_DIR "icon-change.png" );
77 const char* APPLICATION_TITLE( "Motion Blur" );
78 const char* EFFECTS_OFF_ICON( DALI_IMAGE_DIR "icon-effects-off.png" );
79 const char* EFFECTS_ON_ICON( DALI_IMAGE_DIR "icon-effects-on.png" );
80
81 const float UI_MARGIN = 4.0f;                              ///< Screen Margin for placement of UI buttons
82
83 const Vector3 BUTTON_SIZE_CONSTRAINT( 0.24f, 0.09f, 1.0f );
84 const Vector3 BUTTON_TITLE_LABEL_TAP_HERE_SIZE_CONSTRAINT( 0.55f, 0.06f, 1.0f );
85 const Vector3 BUTTON_TITLE_LABEL_INSTRUCTIONS_POPUP_SIZE_CONSTRAINT( 1.0f, 1.0f, 1.0f );
86
87 // move this button down a bit so it is visible on target and not covered up by toolbar
88 const float BUTTON_TITLE_LABEL_Y_OFFSET = 0.05f;
89
90 const float ORIENTATION_DURATION = 0.5f;                  ///< Time to rotate to new orientation.
91
92 /**
93  * @brief Load an image, scaled-down to no more than the dimensions passed in.
94  *
95  * Uses SHRINK_TO_FIT which ensures the resulting image is
96  * smaller than or equal to the specified dimensions while preserving its
97  * original aspect ratio.
98  */
99 ResourceImage LoadImageFittedInBox( const char * const imagePath, uint32_t maxWidth, uint32_t maxHeight )
100 {
101   // Load the image nicely scaled-down to fit within the specified max width and height:
102   return ResourceImage::New( imagePath, ImageDimensions( maxWidth, maxHeight ), FittingMode::SHRINK_TO_FIT, Dali::SamplingMode::BOX_THEN_LINEAR );
103 }
104
105 } // unnamed namespace
106
107
108 //
109 class MotionBlurExampleApp : public ConnectionTracker
110 {
111 public:
112
113   /**
114      * DeviceOrientation describes the four different
115      * orientations the device can be in based on accelerometer reports.
116      */
117   enum DeviceOrientation
118   {
119     PORTRAIT = 0,
120     LANDSCAPE = 90,
121     PORTRAIT_INVERSE = 180,
122     LANDSCAPE_INVERSE = 270
123   };
124
125   /**
126    * Constructor
127    * @param application class, stored as reference
128    */
129   MotionBlurExampleApp(Application &app)
130   : mApplication(app),
131     mActorEffectsEnabled(false),
132     mCurrentActorAnimation(0),
133     mCurrentImage(0)
134   {
135     // Connect to the Application's Init signal
136     app.InitSignal().Connect(this, &MotionBlurExampleApp::OnInit);
137   }
138
139   ~MotionBlurExampleApp()
140   {
141     // Nothing to do here; everything gets deleted automatically
142   }
143
144   /**
145    * This method gets called once the main loop of application is up and running
146    */
147   void OnInit(Application& app)
148   {
149     // The Init signal is received once (only) during the Application lifetime
150
151     Stage::GetCurrent().KeyEventSignal().Connect(this, &MotionBlurExampleApp::OnKeyEvent);
152
153
154     // Creates a default view with a default tool bar.
155     // The view is added to the stage.
156     mContentLayer = DemoHelper::CreateView( mApplication,
157                                             mView,
158                                             mToolBar,
159                                             BACKGROUND_IMAGE_PATH,
160                                             TOOLBAR_IMAGE,
161                                             APPLICATION_TITLE );
162
163     //Add an effects icon on the right of the title
164     mIconEffectsOff = ResourceImage::New( EFFECTS_OFF_ICON );
165     mIconEffectsOn = ResourceImage::New( EFFECTS_ON_ICON );
166     mActorEffectsButton = Toolkit::PushButton::New();
167     mActorEffectsButton.SetBackgroundImage( mIconEffectsOff );
168     mActorEffectsButton.ClickedSignal().Connect( this, &MotionBlurExampleApp::OnEffectButtonClicked );
169     mToolBar.AddControl( mActorEffectsButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalCenter, DemoHelper::DEFAULT_PLAY_PADDING );
170
171     // Creates a mode button.
172     // Create a effect toggle button. (right of toolbar)
173     Image imageLayout = ResourceImage::New( LAYOUT_IMAGE );
174     Toolkit::PushButton layoutButton = Toolkit::PushButton::New();
175     layoutButton.SetBackgroundImage(imageLayout);
176     layoutButton.ClickedSignal().Connect( this, &MotionBlurExampleApp::OnLayoutButtonClicked);
177     layoutButton.SetLeaveRequired( true );
178     mToolBar.AddControl( layoutButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalRight, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
179
180     // Input
181     mTapGestureDetector = TapGestureDetector::New();
182     mTapGestureDetector.Attach( mContentLayer );
183     mTapGestureDetector.DetectedSignal().Connect( this, &MotionBlurExampleApp::OnTap );
184
185     Dali::Window winHandle = app.GetWindow();
186     winHandle.AddAvailableOrientation( Dali::Window::PORTRAIT );
187     winHandle.AddAvailableOrientation( Dali::Window::LANDSCAPE );
188     winHandle.AddAvailableOrientation( Dali::Window::PORTRAIT_INVERSE  );
189     winHandle.AddAvailableOrientation( Dali::Window::LANDSCAPE_INVERSE );
190
191     // set initial orientation
192     winHandle.GetOrientation().ChangedSignal().Connect( this, &MotionBlurExampleApp::OnOrientationChanged );
193     unsigned int degrees = winHandle.GetOrientation().GetDegrees();
194     Rotate( static_cast< DeviceOrientation >( degrees ) );
195
196
197     ///////////////////////////////////////////////////////
198     //
199     // Motion blurred actor
200     //
201
202     // Scale down actor to fit on very low resolution screens with space to interact:
203     Size stageSize = Stage::GetCurrent().GetSize();
204     mMotionBlurActorSize = Size( std::min( stageSize.x * 0.3f, MOTION_BLUR_ACTOR_WIDTH ), std::min( stageSize.y * 0.3f, MOTION_BLUR_ACTOR_HEIGHT ) );
205     mMotionBlurActorSize = Size( std::min( mMotionBlurActorSize.x, mMotionBlurActorSize.y ), std::min( mMotionBlurActorSize.x, mMotionBlurActorSize.y ) );
206
207     Image image = LoadImageFittedInBox( MOTION_BLUR_ACTOR_IMAGE1, mMotionBlurActorSize.x, mMotionBlurActorSize.y );
208     mMotionBlurImageActor = ImageActor::New(image);
209     mMotionBlurImageActor.SetParentOrigin( ParentOrigin::CENTER );
210     mMotionBlurImageActor.SetSize(mMotionBlurActorSize.x, mMotionBlurActorSize.y);
211
212     mContentLayer.Add( mMotionBlurImageActor );
213
214     // Create shader used for doing motion blur
215     mMotionBlurEffect = MotionBlurEffect::Apply(mMotionBlurImageActor);
216
217
218 #ifdef MULTIPLE_MOTION_BLURRED_ACTORS
219
220     ///////////////////////////////////////////////////////
221     //
222     // Motion blurred actor 2
223     //
224
225     mMotionBlurImageActor2 = ImageActor::New(image);
226     mMotionBlurImageActor2.SetParentOrigin( ParentOrigin::CENTER );
227     mMotionBlurImageActor2.SetSize(mMotionBlurActorSize.x, mMotionBlurActorSize.y);
228     mMotionBlurImageActor2.SetPosition(mMotionBlurActorSize.x * 1.1f, 0.0f);
229     mMotionBlurImageActor.Add( mMotionBlurImageActor2 );
230
231     // Create shader used for doing motion blur
232     mMotionBlurEffect2 = MotionBlurEffect::New(MOTION_BLUR_NUM_SAMPLES);
233
234     // set actor shader to the blur one
235     mMotionBlurImageActor2.SetShaderEffect( mMotionBlurEffect2 );
236
237
238     ///////////////////////////////////////////////////////
239     //
240     // Motion blurred actor 3
241     //
242
243     mMotionBlurImageActor3 = ImageActor::New(image);
244     mMotionBlurImageActor3.SetParentOrigin( ParentOrigin::CENTER );
245     mMotionBlurImageActor3.SetSize(mMotionBlurActorSize.x, mMotionBlurActorSize.y);
246     mMotionBlurImageActor3.SetPosition(-mMotionBlurActorSize.x * 1.1f, 0.0f);
247     mMotionBlurImageActor.Add( mMotionBlurImageActor3 );
248
249     // Create shader used for doing motion blur
250     mMotionBlurEffect3 = MotionBlurEffect::New(MOTION_BLUR_NUM_SAMPLES);
251
252     // set actor shader to the blur one
253     mMotionBlurImageActor3.SetShaderEffect( mMotionBlurEffect3 );
254
255
256     ///////////////////////////////////////////////////////
257     //
258     // Motion blurred actor 4
259     //
260
261     mMotionBlurImageActor4 = ImageActor::New(image);
262     mMotionBlurImageActor4.SetParentOrigin( ParentOrigin::CENTER );
263     mMotionBlurImageActor4.SetSize(mMotionBlurActorSize.x, mMotionBlurActorSize.y);
264     mMotionBlurImageActor4.SetPosition(0.0f, mMotionBlurActorSize.y * 1.1f);
265     mMotionBlurImageActor.Add( mMotionBlurImageActor4 );
266
267     // Create shader used for doing motion blur
268     mMotionBlurEffect4 = MotionBlurEffect::New(MOTION_BLUR_NUM_SAMPLES);
269
270     // set actor shader to the blur one
271     mMotionBlurImageActor4.SetShaderEffect( mMotionBlurEffect4 );
272
273
274     ///////////////////////////////////////////////////////
275     //
276     // Motion blurred actor 5
277     //
278
279     mMotionBlurImageActor5 = ImageActor::New(image);
280     mMotionBlurImageActor5.SetParentOrigin( ParentOrigin::CENTER );
281     mMotionBlurImageActor5.SetSize(mMotionBlurActorSize.x, mMotionBlurActorSize.y);
282     mMotionBlurImageActor5.SetPosition(0.0f, -mMotionBlurActorSize.y * 1.1f);
283     mMotionBlurImageActor.Add( mMotionBlurImageActor5 );
284
285     // Create shader used for doing motion blur
286     mMotionBlurEffect5 = MotionBlurEffect::New(MOTION_BLUR_NUM_SAMPLES);
287
288     // set actor shader to the blur one
289     mMotionBlurImageActor5.SetShaderEffect( mMotionBlurEffect5 );
290 #endif //#ifdef MULTIPLE_MOTION_BLURRED_ACTORS
291   }
292
293   //////////////////////////////////////////////////////////////
294   //
295   // Device Orientation Support
296   //
297   //
298
299   void OnOrientationChanged( Orientation orientation )
300   {
301     unsigned int degrees = orientation.GetDegrees();
302     Rotate( static_cast< DeviceOrientation >( degrees ) );
303   }
304
305   void Rotate( DeviceOrientation orientation )
306   {
307     // Resize the root actor
308     Vector2 stageSize = Stage::GetCurrent().GetSize();
309     Vector2 targetSize = stageSize;
310     if( orientation == LANDSCAPE ||
311         orientation == LANDSCAPE_INVERSE )
312     {
313       targetSize = Vector2( stageSize.y, stageSize.x );
314     }
315
316     if( mOrientation != orientation )
317     {
318       mOrientation = orientation;
319
320       // check if actor is on stage
321       if( mView.GetParent() )
322       {
323         // has parent so we expect it to be on stage, start animation
324         mRotateAnimation = Animation::New( ORIENTATION_DURATION );
325         mRotateAnimation.AnimateTo( Property( mView, Actor::Property::ORIENTATION ), Quaternion( Radian( Degree( -orientation ) ), Vector3::ZAXIS ), AlphaFunction::EASE_OUT );
326         mRotateAnimation.AnimateTo( Property( mView, Actor::Property::SIZE_WIDTH ), targetSize.width );
327         mRotateAnimation.AnimateTo( Property( mView, Actor::Property::SIZE_HEIGHT ), targetSize.height );
328         mRotateAnimation.Play();
329       }
330       else
331       {
332         // set the rotation to match the orientation
333         mView.SetOrientation( Degree( -orientation ), Vector3::ZAXIS );
334         mView.SetSize( targetSize );
335       }
336     }
337     else
338     {
339       // for first time just set size
340       mView.SetSize( targetSize );
341     }
342   }
343
344
345   //////////////////////////////////////////////////////////////
346   //
347   // Actor Animation
348   //
349   //
350
351   // move to point on screen that was tapped
352   void OnTap( Actor actor, const TapGesture& tapGesture )
353   {
354     Vector3 destPos;
355     float originOffsetX, originOffsetY;
356
357     // rotate offset (from top left origin to centre) into actor space
358     Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
359     actor.ScreenToLocal(originOffsetX, originOffsetY, stageSize.width * 0.5f, stageSize.height * 0.5f);
360
361     // get dest point in local actor space
362     destPos.x = tapGesture.localPoint.x - originOffsetX;
363     destPos.y = tapGesture.localPoint.y - originOffsetY;
364     destPos.z = 0.0f;
365
366     float animDuration = 0.5f;
367     mActorTapMovementAnimation = Animation::New( animDuration );
368     if ( mMotionBlurImageActor )
369     {
370       mActorTapMovementAnimation.AnimateTo( Property(mMotionBlurImageActor, Actor::Property::POSITION), destPos, AlphaFunction::EASE_IN_OUT_SINE, TimePeriod(animDuration) );
371     }
372     mActorTapMovementAnimation.SetEndAction( Animation::Bake );
373     mActorTapMovementAnimation.Play();
374
375
376     // perform some spinning etc
377     if(mActorEffectsEnabled)
378     {
379       switch(mCurrentActorAnimation)
380       {
381         // spin around y
382         case 0:
383         {
384           float animDuration = 1.0f;
385           mActorAnimation = Animation::New(animDuration);
386           mActorAnimation.AnimateBy( Property( mMotionBlurImageActor, Actor::Property::ORIENTATION ), Quaternion( Radian( Degree(360.0f) ), Vector3::YAXIS ), AlphaFunction::EASE_IN_OUT );
387           mActorAnimation.SetEndAction( Animation::Bake );
388           mActorAnimation.Play();
389         }
390         break;
391
392         // spin around z
393         case 1:
394         {
395           float animDuration = 1.0f;
396           mActorAnimation = Animation::New(animDuration);
397           mActorAnimation.AnimateBy( Property( mMotionBlurImageActor, Actor::Property::ORIENTATION ), Quaternion( Radian( Degree(360.0f) ), Vector3::ZAXIS ), AlphaFunction::EASE_IN_OUT );
398           mActorAnimation.SetEndAction( Animation::Bake );
399           mActorAnimation.Play();
400         }
401         break;
402
403         // spin around y and z
404         case 2:
405         {
406           float animDuration = 1.0f;
407           mActorAnimation = Animation::New(animDuration);
408           mActorAnimation.AnimateBy( Property( mMotionBlurImageActor, Actor::Property::ORIENTATION ), Quaternion( Radian( Degree(360.0f) ), Vector3::YAXIS ), AlphaFunction::EASE_IN_OUT );
409           mActorAnimation.AnimateBy( Property( mMotionBlurImageActor, Actor::Property::ORIENTATION ), Quaternion( Radian( Degree(360.0f) ), Vector3::ZAXIS ), AlphaFunction::EASE_IN_OUT );
410           mActorAnimation.SetEndAction( Animation::Bake );
411           mActorAnimation.Play();
412         }
413         break;
414
415         // scale
416         case 3:
417         {
418           float animDuration = 1.0f;
419           mActorAnimation = Animation::New(animDuration);
420           mActorAnimation.AnimateBy( Property( mMotionBlurImageActor, Actor::Property::SCALE ), Vector3(2.0f, 2.0f, 2.0f), AlphaFunction::BOUNCE, TimePeriod( 0.0f, 1.0f ) );
421           mActorAnimation.SetEndAction( Animation::Bake );
422           mActorAnimation.Play();
423         }
424         break;
425
426         default:
427           break;
428       }
429
430       mCurrentActorAnimation++;
431       if(NUM_ACTOR_ANIMATIONS == mCurrentActorAnimation)
432       {
433         mCurrentActorAnimation = 0;
434       }
435     }
436   }
437
438   void ToggleActorEffects()
439   {
440     if(!mActorEffectsEnabled)
441     {
442       mActorEffectsEnabled = true;
443       mActorEffectsButton.SetBackgroundImage( mIconEffectsOn );
444     }
445     else
446     {
447       mActorEffectsEnabled = false;
448       mActorEffectsButton.SetBackgroundImage( mIconEffectsOff );
449     }
450   }
451
452   //////////////////////////////////////////////////////////////
453   //
454   // Input handlers
455   //
456   //
457
458   bool OnLayoutButtonClicked( Toolkit::Button button )
459   {
460     ChangeImage();
461     return true;
462   }
463
464   bool OnEffectButtonClicked( Toolkit::Button button )
465   {
466     ToggleActorEffects();
467     return true;
468   }
469
470   /**
471    * Main key event handler
472    */
473   void OnKeyEvent(const KeyEvent& event)
474   {
475     if(event.state == KeyEvent::Down)
476     {
477       if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
478       {
479         mApplication.Quit();
480       }
481     }
482   }
483
484   //////////////////////////////////////////////////////////////
485   //
486   // Misc
487   //
488   //
489
490
491   void ChangeImage()
492   {
493     mCurrentImage++;
494     if(MOTION_BLUR_NUM_ACTOR_IMAGES == mCurrentImage)
495     {
496       mCurrentImage = 0;
497     }
498
499     Image blurImage = LoadImageFittedInBox( MOTION_BLUR_ACTOR_IMAGES[mCurrentImage], mMotionBlurActorSize.x, mMotionBlurActorSize.y );
500     mMotionBlurImageActor.SetImage(blurImage);
501   }
502
503
504 private:
505   Application&               mApplication;            ///< Application instance
506   Toolkit::Control           mView;
507   Toolkit::ToolBar           mToolBar;
508   Image                      mIconEffectsOff;
509   Image                      mIconEffectsOn;
510
511   Layer                      mContentLayer;           ///< Content layer (contains actor for this blur demo)
512
513   PushButton                 mActorEffectsButton;     ///< The actor effects toggling Button.
514
515   // Motion blur
516   MotionBlurEffect mMotionBlurEffect;
517   ImageActor mMotionBlurImageActor;
518   Size mMotionBlurActorSize;
519
520 #ifdef MULTIPLE_MOTION_BLURRED_ACTORS
521   MotionBlurEffect mMotionBlurEffect2;
522   MotionBlurEffect mMotionBlurEffect3;
523   MotionBlurEffect mMotionBlurEffect4;
524   MotionBlurEffect mMotionBlurEffect5;
525
526   ImageActor mMotionBlurImageActor2;
527   ImageActor mMotionBlurImageActor3;
528   ImageActor mMotionBlurImageActor4;
529   ImageActor mMotionBlurImageActor5;
530 #endif //#ifdef MULTIPLE_MOTION_BLURRED_ACTORS
531
532   // animate actor to position where user taps screen
533   Animation mActorTapMovementAnimation;
534
535   // show different animations to demonstrate blur effect working on an object only movement basis
536   bool mActorEffectsEnabled;
537   Animation mActorAnimation;
538   int mCurrentActorAnimation;
539
540   // offer a selection of images that user can cycle between
541   int mCurrentImage;
542
543   TapGestureDetector mTapGestureDetector;
544
545   DeviceOrientation mOrientation;               ///< Current Device orientation
546   Animation mRotateAnimation;                   ///< Animation for rotating between landscape and portrait.
547
548   Popup mInstructionsPopup;                     ///< Info Popup
549 };
550
551 void RunTest(Application& app)
552 {
553   MotionBlurExampleApp test(app);
554
555   app.MainLoop();
556 }
557
558 // Entry point for Linux & Tizen applications
559 //
560 int main(int argc, char **argv)
561 {
562   Application app = Application::New(&argc, &argv);
563
564   RunTest(app);
565
566   return 0;
567 }