Merge "Clean up the code to build successfully on macOS" into devel/master
[platform/core/uifw/dali-core.git] / dali / internal / update / gestures / scene-graph-pan-gesture.h
index ad4e5e0..8386102 100644 (file)
@@ -1,8 +1,8 @@
-#ifndef __DALI_INTERNAL_SCENE_GRAPH_PAN_GESTURE_H__
-#define __DALI_INTERNAL_SCENE_GRAPH_PAN_GESTURE_H__
+#ifndef DALI_INTERNAL_SCENE_GRAPH_PAN_GESTURE_H
+#define DALI_INTERNAL_SCENE_GRAPH_PAN_GESTURE_H
 
 /*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  */
 
 // INTERNAL INCLUDES
+#include <dali/devel-api/threading/mutex.h>
 #include <dali/public-api/common/vector-wrapper.h>
-#include <dali/public-api/events/pan-gesture.h>
+#include <dali/internal/event/events/pan-gesture/pan-gesture-impl.h>
 #include <dali/internal/update/common/property-owner.h>
 #include <dali/internal/update/gestures/gesture-properties.h>
 
 namespace Dali
 {
 
-struct PanGesture;
+class PanGesture;
 
 namespace Internal
 {
@@ -47,13 +48,15 @@ public:
   enum PredictionMode
   {
     PREDICTION_NONE = 0,
-    PREDICTION_1
+    PREDICTION_1,
+    PREDICTION_2,
   };
 
   enum SmoothingMode
   {
-    SMOOTHING_NONE,           // no smoothing
-    SMOOTHING_LAST_VALUE,     // smooth between last value and latest value
+    SMOOTHING_NONE,           // No smoothing.
+    SMOOTHING_LAST_VALUE,     // Smooth between last value and latest value.
+    SMOOTHING_MULTI_TAP,      // Uses multitap smoothing, only available with Prediction mode 2.
   };
 
   static const PredictionMode DEFAULT_PREDICTION_MODE;
@@ -74,19 +77,12 @@ public:
      */
     struct Info
     {
-      Info()
-      {
-      }
+      Info() = default;
 
       /**
        * Copy constructor
        */
-      Info( const Info& rhs )
-      : velocity( rhs.velocity ),
-        displacement( rhs.displacement ),
-        position( rhs.position )
-      {
-      }
+      Info(const Info& rhs) = default;
 
       /**
        * Assignment operator
@@ -115,7 +111,7 @@ public:
      */
     PanInfo()
     : time( 0u ),
-      state( Gesture::Clear ),
+      state( GestureState::CLEAR ),
       read( true )
     {
     }
@@ -153,36 +149,36 @@ public:
      * Assignment operator
      * @param[in] gesture A Dali::Gesture
      */
-    PanInfo& operator=( const Dali::PanGesture& rhs )
+    PanInfo& operator=( const Internal::PanGesture& rhs )
     {
-      time = rhs.time;
-      state = rhs.state;
+      time = rhs.GetTime();
+      state = rhs.GetState();
 
-      local.velocity = rhs.velocity;
-      local.displacement = rhs.displacement;
-      local.position = rhs.position;
+      local.velocity = rhs.GetVelocity();
+      local.displacement = rhs.GetDisplacement();
+      local.position = rhs.GetPosition();
 
-      screen.velocity = rhs.screenVelocity;
-      screen.displacement = rhs.screenDisplacement;
-      screen.position = rhs.screenPosition;
+      screen.velocity = rhs.GetScreenVelocity();
+      screen.displacement = rhs.GetScreenDisplacement();
+      screen.position = rhs.GetScreenPosition();
 
       return *this;
     }
 
     // Data
     unsigned int time;
-    Gesture::State state;
+    GestureState state;
     Info local;
     Info screen;
     volatile bool read;
   };
 
-  typedef std::vector<PanInfo> PanInfoHistory;
-  typedef PanInfoHistory::iterator PanInfoHistoryIter;
-  typedef PanInfoHistory::const_iterator PanInfoHistoryConstIter;
+  using PanInfoHistory          = std::vector<PanInfo>;
+  using PanInfoHistoryIter      = PanInfoHistory::iterator;
+  using PanInfoHistoryConstIter = PanInfoHistory::const_iterator;
 
 private:
-  static const unsigned int PAN_GESTURE_HISTORY = 10u;
+  static const unsigned int PAN_GESTURE_HISTORY = 30u;
 
 public:
 
@@ -194,13 +190,13 @@ public:
   /**
    * Virtual destructor
    */
-  virtual ~PanGesture();
+  ~PanGesture() override;
 
   /**
    * Adds a PanGesture to the internal circular-buffer waiting to be handled by UpdateProperties.
    * @param[in]  gesture  The latest pan gesture.
    */
-  void AddGesture( const Dali::PanGesture& gesture );
+  void AddGesture( const Internal::PanGesture& gesture );
 
   /**
    * @brief Removes pan events from the history that are older than maxAge, leaving at least minEvents
@@ -215,21 +211,18 @@ public:
   /**
    * Uses elapsed time and time stamps
    */
-  void PredictiveAlgorithm1(int eventsThisFrame, PanInfo& gestureOut, PanInfoHistory& panHistory, unsigned int lastVSyncTime, unsigned int nextVSyncTime);
+  void PredictionMode1(int eventsThisFrame, PanInfo& gestureOut, PanInfoHistory& panHistory, unsigned int lastVSyncTime, unsigned int nextVSyncTime);
 
   /**
-   * Uses last two gestures
+   * Blends two points together.
+   * The blend value ranges are:
+   * 0.0f = use 100% of current value.
+   * 1.0f = use half-way average of current and last value.
    *
-   * @param[in]  justStarted Whether the pan has just started.
-   * @param[out] gestureOut Output gesture using average values from last two gestures
-   * @param[in]  lastVSyncTime The time to set on gestureOut.
-   */
-  void SmoothingAlgorithm1(bool justStarted, PanInfo& gestureOut, unsigned int lastVSyncTime);
-
-  /**
-   * Future smoothing method, implementation not complete
+   * @param[in,out] gesture     Pass in current gesture, outputs result of blend.
+   * @param[in]     lastGesture Pass in gesture to blend between.
    */
-  void SmoothingAlgorithm2(bool justStarted, PanInfo& gestureOut, unsigned int lastVSyncTime);
+  void BlendPoints( PanInfo& gesture, PanInfo& lastGesture, float blendValue );
 
   /**
    * Called by the update manager so that we can update the value of our properties.
@@ -329,6 +322,62 @@ public:
    */
   void SetSmoothingAmount(float amount);
 
+  /*
+   * @brief Sets whether to use actual times of the real gesture and frames or not.
+   *
+   * @param[in] value True = use actual times, False = use perfect values
+   */
+  void SetUseActualTimes( bool value );
+
+  /**
+   * @brief Sets the interpolation time range (ms) of past points to use (with weights) when interpolating.
+   *
+   * @param[in] value Time range in ms
+   */
+  void SetInterpolationTimeRange( int value );
+
+  /**
+   * @brief Sets whether to use scalar only prediction, which when enabled, ignores acceleration.
+   *
+   * @param[in] value True = use scalar prediction only
+   */
+  void SetScalarOnlyPredictionEnabled( bool value );
+
+  /**
+   * @brief Sets whether to use two point prediction. This combines two interpolated points to get more steady acceleration and velocity values.
+   *
+   * @param[in] value True = use two point prediction
+   */
+  void SetTwoPointPredictionEnabled( bool value );
+
+  /**
+   * @brief Sets the time in the past to interpolate the second point when using two point interpolation.
+   *
+   * @param[in] value Time in past in ms
+   */
+  void SetTwoPointInterpolatePastTime( int value );
+
+  /**
+   * @brief Sets the two point velocity bias. This is the ratio of first and second points to use for velocity.
+   *
+   * @param[in] value 0.0f = 100% first point. 1.0f = 100% of second point.
+   */
+  void SetTwoPointVelocityBias( float value );
+
+  /**
+   * @brief Sets the two point acceleration bias. This is the ratio of first and second points to use for acceleration.
+   *
+   * @param[in] value 0.0f = 100% first point. 1.0f = 100% of second point.
+   */
+  void SetTwoPointAccelerationBias( float value );
+
+  /**
+   * @brief Sets the range of time (ms) of points in the history to perform multitap smoothing with (if enabled).
+   *
+   * @param[in] value Time in past in ms
+   */
+  void SetMultitapSmoothingRange( int value );
+
   /**
    * Called to provide pan-gesture profiling information.
    */
@@ -350,6 +399,100 @@ private:
   // Undefined
   PanGesture(const PanGesture&);
 
+private:
+
+  // Struct to keep pairs of local and screen data together.
+  // TODO: This can encapsulate some functionality also.
+  using RelativeVectors = struct
+
+  {
+    Vector2 local;
+
+    Vector2 screen;
+  };
+
+  /**
+   * Houses new code to process input events and generate an output point.
+   *
+   * @param[in]  lastVSyncTime The time of the last render (in milliseconds)
+   * @param[in]  nextVSyncTime The estimated time of the next render (in milliseconds)
+   */
+  bool NewAlgorithm( unsigned int lastVSyncTime, unsigned int nextVSyncTime );
+
+  /**
+   * Gets the (absolute) time difference between two times.
+   * This is limited by minimumDelta, so it can be safe to use as a divisor.
+   * This function is wrapped so that the behviour can be overridden to return a "perfect" time difference (overrideDifference).
+   *
+   * @param[in]  timeA The first time to calculate from
+   * @param[in]  timeB The second time to calculate from
+   * @param[in]  minimumDelta The smallest amount the difference can become
+   * @param[in]  overrideDifference The time difference to return if using perfect times
+   */
+  inline float GetDivisibleTimeDifference( int timeA, int timeB, float minimumDelta, float overrideDifference );
+
+  /**
+   * This limits the change currentAcceleration can have over lastAcceleration by the specified changeLimit value.
+   *
+   * @param[in]  currentAcceleration The acceleration to modify
+   * @param[in]  lastAcceleration The acceleration to limit against
+   * @param[in]  changeLimit The maximum change (in either direction)
+   */
+  void LimitAccelerationChange( RelativeVectors& currentAcceleration, RelativeVectors& lastAcceleration, float changeLimit );
+
+  /**
+   * Reads all events received this frame into a linear buffer.
+   * A lock is held while this is done.
+   */
+  unsigned int ReadFrameEvents();
+
+  /**
+   * Converts between input rate and internal rate (typically 60Hz internally).
+   * Also writes to the pan history container.
+   * TODO: Does not need to return the gesture if it is in the history also, but currently it's used.
+   * (if rate conversion does not generate a point there are points still in history, but this can been done with a bool property).
+   *
+   * @param[out] rateConvertedGesture Result gesture for this frame is writen here.
+   * @param[in]  eventsThisFrame Number of events to convert
+   * @param[in]  currentFrameTime Time of the frame we will render to
+   * @param[in]  lastFrameTime Time of the last rendered frame
+   * @param[out] justStarted Set to true if we are now starting a new gesture
+   * @param[out] justFinished Set to true if we are now finishing a gesture
+   */
+  bool InputRateConversion( PanInfo& rateConvertedGesture, unsigned int eventsThisFrame,
+      unsigned int currentFrameTime, unsigned int lastFrameTime, bool& justStarted, bool& justFinished );
+
+  /**
+   * Generates an interpolated point at the specified point in time.
+   *
+   * @param[in]  history of points to use
+   * @param[in]  currentTime Time of the frame we will render to
+   * @param[in]  targetTime Time of the point to generate
+   * @param[in]  range Range of time (each side of target time) to use points from
+   * @param[out] outPoint Generated point
+   * @param[out] acceleration Generated acceleration
+   * @param[in]  outputTimeGranularity Time difference between output point (typically 60Hz)
+   * @param[in]  eraseUnused Set to true to clean up any history not used by the function
+   */
+  bool InterpolatePoint( PanInfoHistory& history, unsigned int currentTime, unsigned int targetTime, unsigned int range,
+      PanInfo& outPoint, RelativeVectors& acceleration, int outputTimeGranularity, bool eraseUnused );
+
+  /**
+   * Predicts a point in the future, based on the supplied point and acceleration.
+   * Other user configuration settings are considered.
+   *
+   * @param[in] startPoint Starting point to use. Position and velocity are taken from here.
+   * @param[in] accelerationToUse The acceleration to use.
+   * @param[out] predictedPoint Generated predicted point
+   * @param[in]  currentFrameTime Time of the frame we will render to
+   * @param[in]  previousFrameTime Time of the last rendered frame
+   * @param[in]  noPreviousData Set to true if we are just starting a gesture
+   */
+  void PredictionMode2( PanInfo& startPoint, RelativeVectors& accelerationToUse,
+      PanInfo& predictedPoint, unsigned int currentFrameTime, unsigned int previousFrameTime, bool noPreviousData );
+
+private:
+
   // Undefined
   PanGesture& operator=(const PanGesture&);
 
@@ -399,13 +542,28 @@ private:
   PanInfoHistory mPanHistory;
   PanInfoHistory mPredictionHistory;
   PanInfo mGestures[PAN_GESTURE_HISTORY];     ///< Circular buffer storing the 4 most recent gestures.
+  PanInfo mReadGestures[PAN_GESTURE_HISTORY]; ///< Linear buffer storing the most recent gestures (to reduce read lock time).
   PanInfo mLastGesture;                       ///< The last gesture. (last update frame).
   PanInfo mTargetGesture;                     ///< The most recent input gesture, if the current used gesture does not match.
   PanInfo mLastUnmodifiedGesture;             ///< The last gesture before any processing was done on it.
-  unsigned int mWritePosition;                ///< The next PanInfo buffer to write to. (starts at 0).
+  PanInfo mLastSecondInterpolatedPoint;       ///< Stores the last second interpolated point we generated.
+  PanInfo mLastFrameReadGesture;              ///< Stores the last gesture read.
+  PanInfo mLastPredictedPoint;                ///< Stores the last predicted point we generated.
+  RelativeVectors mLastAcceleration;          ///< Stores the acceleration value from the acceleration limiting last frame.
+  RelativeVectors mLastInterpolatedAcceleration;  ///< Stores the second interpolated point acceleration value from the last frame.
+  RelativeVectors mLastInitialAcceleration;   ///< Stores the initial acceleration value from the last frame.
+
+  volatile unsigned int mWritePosition;       ///< The next PanInfo buffer to write to. (starts at 0).
   unsigned int mReadPosition;                 ///< The next PanInfo buffer to read. (starts at 0).
   bool mNotAtTarget;                          ///< Keeps track of if the last gesture used was the most recent received.
-  bool mInGesture;                            ///< True if the gesture is currently being handled i.e. between Started <-> Finished/Cancelled.
+  bool mInGesture;                            ///< True if the gesture is currently being handled i.e. between STARTED <-> FINISHED/CANCELLED.
+  bool mPredictionAmountOverridden;
+  bool mSmoothingAmountOverridden;
+
+  PanGestureProfiling* mProfiling;            ///< NULL unless pan-gesture profiling information is required.
+  Dali::Mutex mMutex;                         ///< Mutex to lock access.
+
+  // Environment variables:
 
   PredictionMode mPredictionMode;             ///< The pan gesture prediction mode
   unsigned int mPredictionAmount;             ///< how far into future to predict in milliseconds
@@ -415,7 +573,14 @@ private:
   unsigned int mPredictionAmountAdjustment;   ///< the prediction amount to adjust in milliseconds when pan velocity changes
   SmoothingMode mSmoothingMode;               ///< The pan gesture prediction mode
   float         mSmoothingAmount;             ///< How much smoothing to apply [0.0f,1.0f]
-  PanGestureProfiling* mProfiling;            ///< NULL unless pan-gesture profiling information is required.
+  bool mUseActualTimes;                       ///< Disable to optionally override actual times if they make results worse.
+  int mInterpolationTimeRange;                ///< Time into past history (ms) to use points to interpolate the first point.
+  bool mScalarOnlyPredictionEnabled;          ///< If enabled, prediction is done using velocity alone (no integration or acceleration).
+  bool mTwoPointPredictionEnabled;            ///< If enabled, a second interpolated point is predicted and combined with the first to get more stable values.
+  int mTwoPointPastInterpolateTime;           ///< The target time in the past to generate the second interpolated point.
+  float mTwoPointVelocityBias;                ///< The ratio of first and second interpolated points to use for velocity. 0.0f = 100% of first point. 1.0f = 100% of second point.
+  float mTwoPointAccelerationBias;            ///< The ratio of first and second interpolated points to use for acceleration. 0.0f = 100% of first point. 1.0f = 100% of second point.
+  int mMultiTapSmoothingRange;                ///< The range in time (ms) of points in the history to smooth the final output against.
 };
 
 } // namespace SceneGraph
@@ -424,4 +589,4 @@ private:
 
 } // namespace Dali
 
-#endif // __DALI_INTERNAL_SCENE_GRAPH_PAN_GESTURE_H__
+#endif // DALI_INTERNAL_SCENE_GRAPH_PAN_GESTURE_H