[dali_2.3.23] Merge branch 'devel/master'
[platform/core/uifw/dali-demo.git] / examples / motion-blur / motion-blur-example.cpp
1 /*
2  * Copyright (c) 2022 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 "shared/view.h"
25
26 using namespace Dali;
27 using namespace Dali::Toolkit;
28
29 namespace // unnamed namespace
30 {
31 ////////////////////////////////////////////////////
32 //
33 // Demo setup parameters
34 //
35
36 const float        MOTION_BLUR_ACTOR_WIDTH  = 256; // actor size on screen
37 const float        MOTION_BLUR_ACTOR_HEIGHT = 256; // ""
38 const unsigned int MOTION_BLUR_NUM_SAMPLES  = 8;
39
40 const int   MOTION_BLUR_NUM_ACTOR_IMAGES = 5;
41 const char* MOTION_BLUR_ACTOR_IMAGE1(DEMO_IMAGE_DIR "image-with-border-1.jpg");
42 const char* MOTION_BLUR_ACTOR_IMAGE2(DEMO_IMAGE_DIR "image-with-border-2.jpg");
43 const char* MOTION_BLUR_ACTOR_IMAGE3(DEMO_IMAGE_DIR "image-with-border-3.jpg");
44 const char* MOTION_BLUR_ACTOR_IMAGE4(DEMO_IMAGE_DIR "image-with-border-4.jpg");
45 const char* MOTION_BLUR_ACTOR_IMAGE5(DEMO_IMAGE_DIR "image-with-border-1.jpg");
46
47 const char* MOTION_BLUR_ACTOR_IMAGES[] = {
48   MOTION_BLUR_ACTOR_IMAGE1,
49   MOTION_BLUR_ACTOR_IMAGE2,
50   MOTION_BLUR_ACTOR_IMAGE3,
51   MOTION_BLUR_ACTOR_IMAGE4,
52   MOTION_BLUR_ACTOR_IMAGE5,
53 };
54
55 const int NUM_ACTOR_ANIMATIONS  = 4;
56 const int NUM_CAMERA_ANIMATIONS = 2;
57
58 const char* BACKGROUND_IMAGE_PATH = DEMO_IMAGE_DIR "background-default.png";
59
60 const char* TOOLBAR_IMAGE(DEMO_IMAGE_DIR "top-bar.png");
61 const char* LAYOUT_IMAGE(DEMO_IMAGE_DIR "icon-change.png");
62 const char* LAYOUT_IMAGE_SELECTED(DEMO_IMAGE_DIR "icon-change-selected.png");
63 const char* APPLICATION_TITLE("Motion Blur");
64 const char* EFFECTS_OFF_ICON(DEMO_IMAGE_DIR "icon-effects-off.png");
65 const char* EFFECTS_OFF_ICON_SELECTED(DEMO_IMAGE_DIR "icon-effects-off-selected.png");
66 const char* EFFECTS_ON_ICON(DEMO_IMAGE_DIR "icon-effects-on.png");
67 const char* EFFECTS_ON_ICON_SELECTED(DEMO_IMAGE_DIR "icon-effects-on-selected.png");
68
69 const float UI_MARGIN = 4.0f; ///< Screen Margin for placement of UI buttons
70
71 const Vector3 BUTTON_SIZE_CONSTRAINT(0.24f, 0.09f, 1.0f);
72 const Vector3 BUTTON_TITLE_LABEL_TAP_HERE_SIZE_CONSTRAINT(0.55f, 0.06f, 1.0f);
73 const Vector3 BUTTON_TITLE_LABEL_INSTRUCTIONS_POPUP_SIZE_CONSTRAINT(1.0f, 1.0f, 1.0f);
74
75 // move this button down a bit so it is visible on target and not covered up by toolbar
76 const float BUTTON_TITLE_LABEL_Y_OFFSET = 0.05f;
77
78 const float ORIENTATION_DURATION = 0.5f; ///< Time to rotate to new orientation.
79
80 /**
81  * @brief Set an image to image view, scaled-down to no more than the dimensions passed in.
82  *
83  * Uses SHRINK_TO_FIT which ensures the resulting image is
84  * smaller than or equal to the specified dimensions while preserving its original aspect ratio.
85  */
86 void SetImageFittedInBox(ImageView& imageView, Property::Map& shaderEffect, const char* const imagePath, int maxWidth, int maxHeight)
87 {
88   Property::Map map;
89   map[Visual::Property::TYPE]     = Visual::IMAGE;
90   map[ImageVisual::Property::URL] = imagePath;
91   // Load the image nicely scaled-down to fit within the specified max width and height:
92   map[ImageVisual::Property::DESIRED_WIDTH]  = maxWidth;
93   map[ImageVisual::Property::DESIRED_HEIGHT] = maxHeight;
94   map[ImageVisual::Property::FITTING_MODE]   = FittingMode::SHRINK_TO_FIT;
95   map[ImageVisual::Property::SAMPLING_MODE]  = SamplingMode::BOX_THEN_LINEAR;
96   map.Merge(shaderEffect);
97
98   imageView.SetProperty(ImageView::Property::IMAGE, map);
99 }
100
101 } // unnamed namespace
102
103 //
104 class MotionBlurExampleApp : public ConnectionTracker
105 {
106 public:
107   /**
108      * DeviceOrientation describes the four different
109      * orientations the device can be in based on accelerometer reports.
110      */
111   enum DeviceOrientation
112   {
113     PORTRAIT          = 0,
114     LANDSCAPE         = 90,
115     PORTRAIT_INVERSE  = 180,
116     LANDSCAPE_INVERSE = 270
117   };
118
119   /**
120    * Constructor
121    * @param application class, stored as reference
122    */
123   MotionBlurExampleApp(Application& app)
124   : mApplication(app),
125     mActorEffectsEnabled(false),
126     mCurrentActorAnimation(0),
127     mCurrentImage(0),
128     mOrientation(PORTRAIT)
129   {
130     // Connect to the Application's Init signal
131     app.InitSignal().Connect(this, &MotionBlurExampleApp::OnInit);
132   }
133
134   ~MotionBlurExampleApp()
135   {
136     // Nothing to do here; everything gets deleted automatically
137   }
138
139   /**
140    * This method gets called once the main loop of application is up and running
141    */
142   void OnInit(Application& app)
143   {
144     // The Init signal is received once (only) during the Application lifetime
145     Window window = app.GetWindow();
146
147     window.KeyEventSignal().Connect(this, &MotionBlurExampleApp::OnKeyEvent);
148
149     // Creates a default view with a default tool bar.
150     // The view is added to the window.
151     mContentLayer = DemoHelper::CreateView(mApplication,
152                                            mView,
153                                            mToolBar,
154                                            BACKGROUND_IMAGE_PATH,
155                                            TOOLBAR_IMAGE,
156                                            APPLICATION_TITLE);
157
158     // Ensure the content layer is a square so the touch area works in all orientations
159     Vector2 windowSize = window.GetSize();
160     float   size       = std::max(windowSize.width, windowSize.height);
161     mContentLayer.SetProperty(Actor::Property::SIZE, Vector2(size, size));
162
163     //Add an effects icon on the right of the title
164     mActorEffectsButton = Toolkit::PushButton::New();
165     mActorEffectsButton.SetProperty(Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, EFFECTS_OFF_ICON);
166     mActorEffectsButton.SetProperty(Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, EFFECTS_OFF_ICON_SELECTED);
167     mActorEffectsButton.ClickedSignal().Connect(this, &MotionBlurExampleApp::OnEffectButtonClicked);
168     mToolBar.AddControl(mActorEffectsButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HORIZONTAL_CENTER, DemoHelper::DEFAULT_PLAY_PADDING);
169
170     // Creates a mode button.
171     // Create a effect toggle button. (right of toolbar)
172     Toolkit::PushButton layoutButton = Toolkit::PushButton::New();
173     layoutButton.SetProperty(Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, LAYOUT_IMAGE);
174     layoutButton.SetProperty(Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, LAYOUT_IMAGE_SELECTED);
175     layoutButton.ClickedSignal().Connect(this, &MotionBlurExampleApp::OnLayoutButtonClicked);
176     layoutButton.SetProperty(Actor::Property::LEAVE_REQUIRED, true);
177     mToolBar.AddControl(layoutButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HORIZONTAL_RIGHT, DemoHelper::DEFAULT_MODE_SWITCH_PADDING);
178
179     // Input
180     mTapGestureDetector = TapGestureDetector::New();
181     mTapGestureDetector.Attach(mContentLayer);
182     mTapGestureDetector.DetectedSignal().Connect(this, &MotionBlurExampleApp::OnTap);
183
184     Dali::Window winHandle = app.GetWindow();
185     winHandle.AddAvailableOrientation(Dali::WindowOrientation::PORTRAIT);
186     winHandle.AddAvailableOrientation(Dali::WindowOrientation::LANDSCAPE);
187     winHandle.AddAvailableOrientation(Dali::WindowOrientation::PORTRAIT_INVERSE);
188     winHandle.AddAvailableOrientation(Dali::WindowOrientation::LANDSCAPE_INVERSE);
189     winHandle.ResizeSignal().Connect(this, &MotionBlurExampleApp::OnWindowResized);
190
191     // set initial orientation
192     Rotate(PORTRAIT);
193
194     ///////////////////////////////////////////////////////
195     //
196     // Motion blurred actor
197     //
198
199     // Scale down actor to fit on very low resolution screens with space to interact:
200     mMotionBlurActorSize       = Size(std::min(windowSize.x * 0.3f, MOTION_BLUR_ACTOR_WIDTH), std::min(windowSize.y * 0.3f, MOTION_BLUR_ACTOR_HEIGHT));
201     mMotionBlurActorUpdateSize = Size(std::max(mMotionBlurActorSize.x, mMotionBlurActorSize.y), std::max(mMotionBlurActorSize.x, mMotionBlurActorSize.y));
202     mMotionBlurActorSize       = Size(std::min(mMotionBlurActorSize.x, mMotionBlurActorSize.y), std::min(mMotionBlurActorSize.x, mMotionBlurActorSize.y));
203
204     mMotionBlurActorUpdateSize = mMotionBlurActorSize * 1.25f;
205
206     mMotionBlurEffect    = CreateMotionBlurEffect();
207     mMotionBlurImageView = ImageView::New();
208     SetImageFittedInBox(mMotionBlurImageView, mMotionBlurEffect, MOTION_BLUR_ACTOR_IMAGE1, mMotionBlurActorSize.x, mMotionBlurActorSize.y);
209     mMotionBlurImageView.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
210     mMotionBlurImageView.SetProperty(Actor::Property::SIZE, mMotionBlurActorSize);
211     mMotionBlurImageView.SetProperty(Actor::Property::UPDATE_AREA_HINT, Vector4(0, 0, mMotionBlurActorUpdateSize.width, mMotionBlurActorUpdateSize.height));
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   //
224   // Device Orientation Support
225   //
226   //
227
228   void OnWindowResized(Window window, Window::WindowSize size)
229   {
230     Rotate(size.GetWidth() > size.GetHeight() ? LANDSCAPE : PORTRAIT);
231   }
232
233   void Rotate(DeviceOrientation orientation)
234   {
235     // Resize the root actor
236     const Vector2 targetSize = mApplication.GetWindow().GetSize();
237
238     if(mOrientation != orientation)
239     {
240       mOrientation = orientation;
241
242       // check if actor is on window
243       if(mView.GetParent())
244       {
245         // has parent so we expect it to be on window, start animation
246         mRotateAnimation = Animation::New(ORIENTATION_DURATION);
247         mRotateAnimation.AnimateTo(Property(mView, Actor::Property::SIZE_WIDTH), targetSize.width);
248         mRotateAnimation.AnimateTo(Property(mView, Actor::Property::SIZE_HEIGHT), targetSize.height);
249         mRotateAnimation.Play();
250       }
251       else
252       {
253         mView.SetProperty(Actor::Property::SIZE, targetSize);
254       }
255     }
256     else
257     {
258       // for first time just set size
259       mView.SetProperty(Actor::Property::SIZE, targetSize);
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 windowSize = mApplication.GetWindow().GetSize();
277     actor.ScreenToLocal(originOffsetX, originOffsetY, windowSize.width * 0.5f, windowSize.height * 0.5f);
278
279     // get dest point in local actor space
280     const Vector2& localPoint = tapGesture.GetLocalPoint();
281     destPos.x                 = localPoint.x - originOffsetX;
282     destPos.y                 = localPoint.y - originOffsetY;
283     destPos.z                 = 0.0f;
284
285     float tapMovementAnimDuration = 0.5f;
286     mActorTapMovementAnimation    = Animation::New(tapMovementAnimDuration);
287     if(mMotionBlurImageView)
288     {
289       mActorTapMovementAnimation.AnimateTo(Property(mMotionBlurImageView, Actor::Property::POSITION), destPos, AlphaFunction::EASE_IN_OUT_SINE, TimePeriod(tapMovementAnimDuration));
290     }
291     mActorTapMovementAnimation.SetEndAction(Animation::BAKE);
292     mActorTapMovementAnimation.Play();
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::Button::Property::UNSELECTED_BACKGROUND_VISUAL, EFFECTS_ON_ICON);
362       mActorEffectsButton.SetProperty(Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, EFFECTS_ON_ICON_SELECTED);
363     }
364     else
365     {
366       mActorEffectsEnabled = false;
367       mActorEffectsButton.SetProperty(Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, EFFECTS_OFF_ICON);
368       mActorEffectsButton.SetProperty(Toolkit::Button::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.GetState() == 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   void ChangeImage()
411   {
412     mCurrentImage++;
413     if(MOTION_BLUR_NUM_ACTOR_IMAGES == mCurrentImage)
414     {
415       mCurrentImage = 0;
416     }
417     SetImageFittedInBox(mMotionBlurImageView, mMotionBlurEffect, MOTION_BLUR_ACTOR_IMAGES[mCurrentImage], mMotionBlurActorSize.x, mMotionBlurActorSize.y);
418   }
419
420 private:
421   Application&     mApplication; ///< Application instance
422   Toolkit::Control mView;
423   Toolkit::ToolBar mToolBar;
424
425   Layer mContentLayer; ///< Content layer (contains actor for this blur demo)
426
427   PushButton mActorEffectsButton; ///< The actor effects toggling Button.
428
429   // Motion blur
430   Property::Map mMotionBlurEffect;
431   ImageView     mMotionBlurImageView;
432   Size          mMotionBlurActorSize;
433   Size          mMotionBlurActorUpdateSize;
434
435   // animate actor to position where user taps screen
436   Animation mActorTapMovementAnimation;
437
438   // show different animations to demonstrate blur effect working on an object only movement basis
439   bool      mActorEffectsEnabled;
440   Animation mActorAnimation;
441   int       mCurrentActorAnimation;
442
443   // offer a selection of images that user can cycle between
444   int mCurrentImage;
445
446   TapGestureDetector mTapGestureDetector;
447
448   DeviceOrientation mOrientation;     ///< Current Device orientation
449   Animation         mRotateAnimation; ///< Animation for rotating between landscape and portrait.
450 };
451
452 int DALI_EXPORT_API main(int argc, char** argv)
453 {
454   Application          app = Application::New(&argc, &argv, DEMO_THEME_PATH);
455   MotionBlurExampleApp test(app);
456   app.MainLoop();
457   return 0;
458 }