0cf34a086991ced9b92651ea1c1eef9fbff18903
[platform/core/uifw/dali-toolkit.git] / optional / dali-toolkit / internal / controls / magnifier / magnifier-impl.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 // CLASS HEADER
19 #include <dali-toolkit/internal/controls/magnifier/magnifier-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/actors/image-actor.h>
23 #include <dali/public-api/animation/constraints.h>
24 #include <dali/public-api/common/stage.h>
25 #include <dali/public-api/render-tasks/render-task-list.h>
26
27 using namespace Dali;
28
29 namespace // unnamed namespace
30 {
31
32 const char* DEFAULT_FRAME_IMAGE_PATH = DALI_IMAGE_DIR "magnifier-image-frame.png";
33
34 const float IMAGE_BORDER_INDENT = 14.0f;            ///< Indent of border in pixels.
35
36 /**
37  * ImageBorderSizeConstraint
38  */
39 struct ImageBorderSizeConstraint
40 {
41   ImageBorderSizeConstraint()
42   : mSizeOffset(Vector3(IMAGE_BORDER_INDENT - 1, IMAGE_BORDER_INDENT - 1, 0.0f) * 2.0f)
43   {
44   }
45
46   Vector3 operator()(const Vector3&    current,
47                      const PropertyInput& referenceSizeProperty)
48   {
49     const Vector3& referenceSize = referenceSizeProperty.GetVector3();
50
51     return referenceSize + mSizeOffset;
52   }
53
54   Vector3 mSizeOffset;                        ///< The amount to offset the size from referenceSize
55 };
56
57 struct CameraActorPositionConstraint
58 {
59   CameraActorPositionConstraint(const Vector2& stageSize, float defaultCameraDistance = 0.0f)
60   : mStageSize(stageSize),
61     mDefaultCameraDistance(defaultCameraDistance)
62   {
63   }
64
65   Vector3 operator()(const Vector3& current,
66                      const PropertyInput& sourcePositionProperty)
67   {
68     const Vector3& sourcePosition = sourcePositionProperty.GetVector3();
69
70     return Vector3( sourcePosition.x + mStageSize.x * 0.5f,
71                     sourcePosition.y + mStageSize.y * 0.5f,
72                     sourcePosition.z + mDefaultCameraDistance);
73   }
74
75   Vector2 mStageSize;
76   float mDefaultCameraDistance;
77
78 };
79
80 struct RenderTaskViewportPositionConstraint
81 {
82   RenderTaskViewportPositionConstraint(const Vector2& stageSize)
83   : mStageSize(stageSize)
84   {
85   }
86
87   Vector2 operator()(const Vector2& current,
88                      const PropertyInput& positionProperty,
89                      const PropertyInput& magnifierSizeProperty,
90                      const PropertyInput& magnifierScaleProperty)
91   {
92     Vector2 position(positionProperty.GetVector3()); // World position?
93
94     //position -= mStageSize * 0.5f;
95
96     // should be updated when:
97     // Magnifier's world position/size/scale/parentorigin/anchorpoint changes.
98     // or Magnifier camera's world position changes.
99     Vector3 size = magnifierSizeProperty.GetVector3() * magnifierScaleProperty.GetVector3();
100
101     // Reposition, and resize viewport to reflect the world bounds of this Magnifier actor.
102     position.x += (mStageSize.width - size.width) * 0.5f;
103     position.y += (mStageSize.height - size.height) * 0.5f;
104
105     return position;
106   }
107
108   Vector2 mStageSize;
109 };
110
111 struct RenderTaskViewportSizeConstraint
112 {
113   RenderTaskViewportSizeConstraint()
114   {
115   }
116
117   Vector2 operator()(const Vector2& current,
118                      const PropertyInput& magnifierSizeProperty,
119                      const PropertyInput& magnifierScaleProperty)
120   {
121     return Vector2(magnifierSizeProperty.GetVector3() * magnifierScaleProperty.GetVector3());
122   }
123 };
124
125 }
126
127 namespace Dali
128 {
129
130 namespace Toolkit
131 {
132
133 namespace Internal
134 {
135
136 ///////////////////////////////////////////////////////////////////////////////////////////////////
137 // Magnifier
138 ///////////////////////////////////////////////////////////////////////////////////////////////////
139
140 Dali::Toolkit::Magnifier Magnifier::New()
141 {
142   // Create the implementation
143   MagnifierPtr magnifier(new Magnifier());
144
145   // Pass ownership to CustomActor via derived handle
146   Dali::Toolkit::Magnifier handle(*magnifier);
147
148   // Second-phase init of the implementation
149   // This can only be done after the CustomActor connection has been made...
150   magnifier->Initialize();
151
152   return handle;
153 }
154
155 Magnifier::Magnifier()
156 : Control( REQUIRES_TOUCH_EVENTS ),
157   mPropertySourcePosition(Property::INVALID_INDEX),
158   mDefaultCameraDistance(1000.f),
159   mActorSize(Vector3::ZERO),
160   mMagnificationFactor(1.0f)
161 {
162 }
163
164 void Magnifier::SetSourceActor(Actor actor)
165 {
166   mTask.SetSourceActor( actor );
167 }
168
169 void Magnifier::SetSourcePosition(const Vector3& position)
170 {
171   Self().SetProperty(mPropertySourcePosition, position);
172 }
173
174 void Magnifier::Initialize()
175 {
176   Actor self = Self();
177   mPropertySourcePosition = self.RegisterProperty( Toolkit::Magnifier::SOURCE_POSITION_PROPERTY_NAME, Vector3::ZERO );
178   Vector2 stageSize(Stage::GetCurrent().GetSize());
179
180   Layer dummyLayer = Layer::New();
181   Stage().GetCurrent().Add(dummyLayer);
182   dummyLayer.SetParentOrigin(ParentOrigin::CENTER);
183
184   // NOTE:
185   // sourceActor is a dummy delegate actor that takes the source property position,
186   // and generates a WORLD_POSITION, which is 1 frame behind the source property.
187   // This way the constraints for determining the camera position (source) and those
188   // for determining viewport position use the same 1 frame old values.
189   // A simple i) CameraPos = f(B), ii) B = f(A) set of constraints wont suffice as
190   // although CameraPos will use B, which is A's previous value. The constraint will
191   // not realise that B is still dirty as far as constraint (i) is concerned.
192   // Perhaps this is a bug in the way the constraint system factors into what is dirty
193   // and what is not.
194   mSourceActor = Actor::New();
195   dummyLayer.Add(mSourceActor);
196   mSourceActor.SetParentOrigin(ParentOrigin::CENTER);
197   Constraint constraint = Constraint::New<Vector3>( Actor::POSITION,
198                                                     Source( self, mPropertySourcePosition ),
199                                                     EqualToConstraint() );
200   mSourceActor.ApplyConstraint(constraint);
201
202   // create the render task this will render content on top of everything
203   // based on camera source position.
204   InitializeRenderTask();
205
206   // set up some constraints to:
207   // i) reposition (dest) frame actor based on magnifier actor's world position (this is 1 frame delayed)
208   // ii) reposition and resize (dest) the render task's viewport based on magnifier actor's world position (1 frame delayed) & size.
209   // iii) reposition (source) camera actor based on magnifier source actor's world position (this is 1 frame delayed)
210
211   // Apply constraint to camera's position
212   // Position our camera at the same distance from its target as the default camera is.
213   // The camera position doesn't affect how we render, just what we render (due to near and far clip planes)
214   // NOTE: We can't interrogate the default camera's position as it is not known initially (takes 1 frame
215   // for value to update).
216   // But we can determine the initial position using the same formula:
217   // distance = stage.height * 0.5 / tan(FOV * 0.5)
218
219   RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
220   RenderTask renderTask = taskList.GetTask(0u);
221   float fov = renderTask.GetCameraActor().GetFieldOfView();
222   mDefaultCameraDistance = (stageSize.height * 0.5f) / tanf(fov * 0.5f);
223
224   // Use a 1 frame delayed source position to determine the camera actor's position.
225   // This is necessary as the viewport is determined by the Magnifier's Actor's World position (which is computed
226   // at the end of the update cycle i.e. after constraints have been applied.)
227   //Property::Index propertySourcePositionDelayed = mCameraActor.RegisterProperty("delayed-source-position", Vector3::ZERO);
228
229   constraint = Constraint::New<Vector3>( Actor::POSITION,
230                                                     Source( mSourceActor, Actor::WORLD_POSITION ),
231                                                     CameraActorPositionConstraint(stageSize, mDefaultCameraDistance) );
232   mCameraActor.ApplyConstraint(constraint);
233
234   // Apply constraint to render-task viewport position
235   constraint = Constraint::New<Vector2>( RenderTask::VIEWPORT_POSITION,
236                                          Source( self, Actor::WORLD_POSITION ),//mPropertySourcePosition ),
237                                          Source( self, Actor::SIZE ),
238                                          Source( self, Actor::WORLD_SCALE),
239                                          RenderTaskViewportPositionConstraint(stageSize) );
240   mTask.ApplyConstraint(constraint);
241
242   // Apply constraint to render-task viewport position
243   constraint = Constraint::New<Vector2>( RenderTask::VIEWPORT_SIZE,
244                                          Source( self, Actor::SIZE ),
245                                          Source( self, Actor::WORLD_SCALE),
246                                          RenderTaskViewportSizeConstraint() );
247   mTask.ApplyConstraint(constraint);
248 }
249
250 Magnifier::~Magnifier()
251 {
252
253 }
254
255 void Magnifier::InitializeRenderTask()
256 {
257   Stage stage = Stage::GetCurrent();
258
259   RenderTaskList taskList = stage.GetRenderTaskList();
260
261   mTask = taskList.CreateTask();
262   mTask.SetInputEnabled(false);
263   mTask.SetClearColor(Vector4(0.5f, 0.5f, 0.5f, 1.0f));
264   mTask.SetClearEnabled(true);
265
266   mCameraActor = CameraActor::New();
267   mCameraActor.SetType(Camera::FREE_LOOK);
268   mCameraActor.SetRotation(Quaternion(M_PI, Vector3::YAXIS)); // Look at stage
269
270   stage.Add(mCameraActor);
271   mTask.SetCameraActor( mCameraActor );
272
273   SetFrameVisibility(true);
274 }
275
276 bool Magnifier::GetFrameVisibility() const
277 {
278   return mFrameLayer;
279 }
280
281 void Magnifier::SetFrameVisibility(bool visible)
282 {
283   if(visible && !mFrameLayer)
284   {
285     Actor self(Self());
286
287     Layer mFrameLayer = Layer::New();
288     mFrameLayer.SetParentOrigin( ParentOrigin::CENTER );
289     Stage::GetCurrent().Add(mFrameLayer);
290
291     Image image = Image::New( DEFAULT_FRAME_IMAGE_PATH );
292     ImageActor frame = ImageActor::New( image );
293     frame.SetDrawMode(DrawMode::OVERLAY);
294     frame.SetStyle( ImageActor::STYLE_NINE_PATCH );
295
296     frame.SetNinePatchBorder( Vector4::ONE * IMAGE_BORDER_INDENT );
297     mFrameLayer.Add(frame);
298
299     // Apply position constraint to the frame
300     Constraint constraint = Constraint::New<Vector3>( Actor::POSITION,
301                                                       Source( self, Actor::WORLD_POSITION ),
302                                                       EqualToConstraint() );
303     frame.ApplyConstraint(constraint);
304
305     // Apply scale constraint to the frame
306     constraint = Constraint::New<Vector3>( Actor::SCALE,
307                                            Source( self, Actor::SCALE ),
308                                            EqualToConstraint() );
309     frame.ApplyConstraint(constraint);
310
311     Source(self, Actor::SCALE),
312
313     // Apply size constraint to the the frame
314     constraint = Constraint::New<Vector3>(Actor::SIZE,
315                                           Source(self, Actor::SIZE),
316                                           ImageBorderSizeConstraint());
317     frame.ApplyConstraint(constraint);
318   }
319   else if(!visible && mFrameLayer)
320   {
321     Stage::GetCurrent().Remove(mFrameLayer);
322     mFrameLayer.Reset();
323   }
324 }
325
326 void Magnifier::OnControlSizeSet(const Vector3& targetSize)
327 {
328   // TODO: Once Camera/CameraActor properties function as proper animatable properties
329   // this code can disappear.
330   // whenever the size of the magnifier changes, the field of view needs to change
331   // to compensate for the new size of the viewport. this cannot be done within
332   // a constraint yet as Camera/CameraActor properties are not animatable/constrainable.
333   mActorSize = targetSize;
334   Update();
335 }
336
337 float Magnifier::GetMagnificationFactor() const
338 {
339   return mMagnificationFactor;
340 }
341
342 void Magnifier::SetMagnificationFactor(float value)
343 {
344   mMagnificationFactor = value;
345   Update();
346 }
347
348 void Magnifier::Update()
349 {
350   // TODO: Make Camera settings (fieldofview/aspectratio) as animatable constraints.
351
352   // should be updated when:
353   // Magnifier's world size/scale changes.
354   Actor self(Self());
355   Vector3 worldSize = mActorSize * self.GetCurrentWorldScale();
356
357   // Adjust field of view to scale content
358
359   // size.height / 2
360   // |------/
361   // |d    /
362   // |i   /
363   // |s  /
364   // |t /
365   // |./
366   // |/ <--- fov/2 radians.
367   //
368   const float fov = atanf( 0.5f * worldSize.height / mDefaultCameraDistance / mMagnificationFactor) * 2.0f;
369   mCameraActor.SetFieldOfView( fov );
370
371   // Adjust aspect ratio to compensate for rectangular viewports.
372   mCameraActor.SetAspectRatio( worldSize.width / worldSize.height );
373 }
374
375 } // namespace Internal
376
377 } // namespace Toolkit
378
379 } // namespace Dali