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