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