[dali_1.1.37] Merge branch 'devel/master'
[platform/core/uifw/dali-demo.git] / examples / blocks / blocks-example.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 #include <sstream>
19 #include <iostream>
20 #include <string>
21 #include <map>
22 #include <algorithm>
23
24 #include <dali/dali.h>
25 #include <dali-toolkit/dali-toolkit.h>
26 #include "shared/view.h"
27
28 using namespace Dali;
29 using namespace Dali::Toolkit;
30 using namespace DemoHelper;
31
32 namespace
33 {
34 const char* BACKGROUND_IMAGE( DEMO_IMAGE_DIR "background-blocks.jpg" );
35 const char* TOOLBAR_IMAGE( DEMO_IMAGE_DIR "top-bar.png" );
36 const char* APPLICATION_TITLE( "DALi Blocks" );
37 const char* BALL_IMAGE = DEMO_IMAGE_DIR "blocks-ball.png";
38 const char* PADDLE_IMAGE = DEMO_IMAGE_DIR "blocks-paddle.png";
39 const char* PADDLE_HANDLE_IMAGE = DEMO_IMAGE_DIR "blocks-paddle-handle.png";
40
41 const char* BRICK_IMAGE_PATH[] =    { DEMO_IMAGE_DIR "blocks-brick-1.png",
42                                       DEMO_IMAGE_DIR "blocks-brick-2.png",
43                                       DEMO_IMAGE_DIR "blocks-brick-3.png",
44                                       DEMO_IMAGE_DIR "blocks-brick-4.png" };
45
46 const int TOTAL_BRICKS(4);                                                  ///< Total bricks in game.
47 const Vector3 ICON_SIZE(100.0f, 100.0f, 0.0f);
48
49 const float SCREEN_MARGIN = 10.0f;                                          ///< Margin indentation around screen
50 const Vector3 MENU_BUTTON_SIZE = Vector3(0.15f, 0.05f, 1.0f);               ///< Standard Menu Buttons.
51
52 const float MAX_ANIMATION_DURATION = 60.0f;                                 ///< 60 seconds animations. Long enough for ball to hit an obstacle.
53 const float BALL_VELOCITY = 300.0f;                                         ///< Ball velocity in pixels/second.
54 const float MAX_VELOCITY = 500.0f;                                          ///< Max. velocity in pixels/second.
55 const Vector3 PADDLE_COLLISION_MARGIN(0.0f, 0.0f, 0.0f);                    ///< Collision margin for ball-paddle detection.
56 const Vector3 BRICK_COLLISION_MARGIN(0.0f, 0.0f, 0.0f);                     ///< Collision margin for ball-brick detection.
57 const Vector3 INITIAL_BALL_DIRECTION(1.0f, 1.0f, 0.0f);                     ///< Initial ball direction.
58
59 const std::string WOBBLE_PROPERTY_NAME("wobbleProperty");                  ///< Wobble property name.
60 const std::string COLLISION_PROPERTY_NAME("collisionProperty");            ///< Collision property name.
61
62 const Vector2 BRICK_SIZE(0.1f, 0.05f );                                     ///< Brick size relative to width of stage.
63 const Vector2 BALL_SIZE( 0.05f, 0.05f );                                    ///< Ball size relative to width of stage.
64 const Vector2 PADDLE_SIZE( 0.2f, 0.05f );                                   ///< Paddle size relative to width of stage.
65 const Vector2 PADDLE_HANDLE_SIZE( 0.3f, 0.3f );                             ///< Paddle handle size relative to width of stage.
66 const Vector2 BALL_START_POSITION(0.5f, 0.8f);                              ///< Ball start position relative to stage size.
67 const Vector2 PADDLE_START_POSITION(0.5f, 0.9f);                            ///< Paddler start position relative to stage size.
68 const Vector2 PADDLE_HIT_MARGIN( 0.1, 0.15f );                              ///< Extra hit Area for Paddle when touching.
69
70 const int TOTAL_LIVES(3);                                                   ///< Total lives in game before it's game over!
71 const int TOTAL_LEVELS(3);                                                  ///< 3 Levels total, then repeats.
72
73 // constraints ////////////////////////////////////////////////////////////////
74
75 /**
76  * CollisionCircleRectangleConstraint generates a collision vector
77  * between two actors a (circle) and b (rectangle)
78  */
79 struct CollisionCircleRectangleConstraint
80 {
81   /**
82    * Collision Constraint constructor
83    * The adjust (optional) parameter can be used to add a margin
84    * to the actors. A +ve size will result in larger collisions,
85    * while a -ve size will result in tighter collisions.
86    *
87    * @param[in] adjustPosition (optional) Adjusts the position offset of detection
88    * @param[in] adjustSize (optional) Adjusts the rectangular size of detection
89    */
90   CollisionCircleRectangleConstraint(Vector3 adjustPosition = Vector3::ZERO,
91                                      Vector3 adjustSize = Vector3::ZERO)
92   : mAdjustPosition(adjustPosition),
93     mAdjustSize(adjustSize)
94   {
95   }
96
97   /**
98    * Generates collision vector indicating whether Actor's A and B
99    * have overlapped eachother, and the relative position of Actor B to A.
100    *
101    * @param[in,out] current The current collision-property
102    * @param[in] inputs Contains:
103    *                    Actor A's Position property.
104    *                    Actor B's Position property.
105    *                    Actor A's Size property.
106    *                    Actor B's Size property.
107    * @return The collision vector is returned.
108    */
109   void operator()( Vector3& current, const PropertyInputContainer& inputs )
110   {
111     const Vector3& a = inputs[0]->GetVector3();
112     const Vector3 b = inputs[1]->GetVector3() + mAdjustPosition;
113     const Vector3& sizeA = inputs[2]->GetVector3();
114     const Vector3& sizeB = inputs[3]->GetVector3();
115     const Vector3 sizeA2 = sizeA * 0.5f; // circle radius
116     const Vector3 sizeB2 = (sizeB + mAdjustSize) * 0.5f; // rectangle half rectangle.
117
118     // get collision relative to a (rectangle).
119     Vector3 delta = a - b;
120
121     // reduce rectangle to 0.
122     if (delta.x > sizeB2.x)
123     {
124       delta.x -= sizeB2.x;
125     }
126     else if (delta.x < -sizeB2.x)
127     {
128       delta.x += sizeB2.x;
129     }
130     else
131     {
132       delta.x = 0;
133     }
134
135     if (delta.y > sizeB2.y)
136     {
137       delta.y -= sizeB2.y;
138     }
139     else if (delta.y < -sizeB2.y)
140     {
141       delta.y += sizeB2.y;
142     }
143     else
144     {
145       delta.y = 0;
146     }
147
148     // now calculate collision vector vs origin. (assume A is a circle, not ellipse)
149     if(delta.Length() < sizeA2.x)
150     {
151       delta.Normalize();
152       current = delta;
153     }
154     else
155     {
156       current = Vector3::ZERO;
157     }
158   }
159
160   const Vector3 mAdjustPosition;            ///< Position Adjustment value
161   const Vector3 mAdjustSize;                ///< Size Adjustment value
162 };
163
164 /**
165  * WobbleConstraint generates a decaying sinusoidial rotation.
166  * The result when applied to an Actor, is the Actor rotating left/right
167  * initially a large amount (deviation degrees, when wobble property is 0.0f)
168  * then eventually coming to a stop (once wobble property reaches 1.0f)
169  */
170 struct WobbleConstraint
171 {
172   /**
173    * Wobble Constraint constructor
174    * Generates a sinusoidial rotation that starts with
175    * high amplitude (deviation), and then decays to zero over input 0.0f to 1.0f
176    *
177    * @param[in] deviation The max. deviation of wobble effect in degrees.
178    */
179   WobbleConstraint( Degree deviation )
180   : mDeviation( deviation )
181   {
182
183   }
184
185   /**
186    * @param[in,out] current The current rotation property
187    * @param[in] inputs Contains the wobble property (value from 0.0f to 1.0f)
188    * @return The rotation (quaternion) is generated.
189    */
190   void operator()( Quaternion& current, const PropertyInputContainer& inputs )
191   {
192     const float& wobble = inputs[0]->GetFloat();
193
194     float f = sinf(wobble * 10.0f) * (1.0f-wobble);
195
196     current = Quaternion(mDeviation * f, Vector3::ZAXIS);
197   }
198
199   Radian mDeviation;           ///< Deviation factor in radians.
200 };
201
202 } // unnamed namespace
203
204 /**
205  * This example shows how to use PropertyNotifications
206  */
207 class ExampleController : public ConnectionTracker
208 {
209 public:
210
211   /**
212    * Constructor
213    * @param application Application class, stored as reference
214    */
215   ExampleController( Application& application )
216   : mApplication( application ),
217     mView()
218   {
219     // Connect to the Application's Init and orientation changed signal
220     mApplication.InitSignal().Connect(this, &ExampleController::Create);
221   }
222
223   /**
224    * This method gets called once the main loop of application is up and running
225    * @param[in] application Reference to the application instance
226    */
227   void Create(Application& application)
228   {
229     Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleController::OnKeyEvent);
230
231     // Creates a default view with a default tool bar.
232     // The view is added to the stage.
233     Toolkit::ToolBar toolBar;
234     mContentLayer = DemoHelper::CreateView( application,
235                                             mView,
236                                             toolBar,
237                                             BACKGROUND_IMAGE,
238                                             TOOLBAR_IMAGE,
239                                             APPLICATION_TITLE );
240
241     // Add an extra space on the right to center the title text.
242     toolBar.AddControl( Actor::New(), DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalRight );
243
244     // Create the content layer, which is where game actors appear.
245     AddContentLayer();
246   }
247
248 private:
249
250   /**
251    * Adds a new layer to the stage, containing game actors.
252    */
253   void AddContentLayer()
254   {
255     Stage stage = Stage::GetCurrent();
256     const Vector3 stageSize(stage.GetSize());
257
258     // Ball setup
259     mBallStartPosition = stageSize * Vector3( BALL_START_POSITION );
260     mBall = CreateImage(BALL_IMAGE);
261     mBall.SetPosition( mBallStartPosition );
262     mBall.SetSize( BALL_SIZE * stageSize.width );
263     mContentLayer.Add(mBall);
264     mBallVelocity = Vector3::ZERO;
265
266     // Paddle setup
267     mPaddleHitMargin = Vector2(stageSize) * PADDLE_HIT_MARGIN;
268     mPaddle = Actor::New();
269     mPaddleHandle = CreateImage(PADDLE_HANDLE_IMAGE);
270     mPaddleImage = CreateImage(PADDLE_IMAGE);
271     mPaddle.Add( mPaddleHandle );
272     mPaddle.Add( mPaddleImage );
273     mPaddleHandle.SetParentOrigin( ParentOrigin::TOP_CENTER );
274     mPaddleHandle.SetAnchorPoint( AnchorPoint::TOP_CENTER );
275     mPaddleHandle.SetPosition( 0.0f, stageSize.width * 0.0125f );
276     mPaddleImage.SetParentOrigin( ParentOrigin::TOP_CENTER );
277     mPaddleImage.SetAnchorPoint( AnchorPoint::TOP_CENTER );
278     mPaddle.SetParentOrigin( ParentOrigin::TOP_LEFT );
279     mPaddle.SetAnchorPoint( AnchorPoint::CENTER );
280     mPaddleFullSize = PADDLE_SIZE * stageSize.width;
281     mPaddle.SetSize( mPaddleFullSize + mPaddleHitMargin );
282     mPaddleHandle.SetSize( PADDLE_HANDLE_SIZE * stageSize.width );
283     mPaddleImage.SetSize( mPaddleFullSize );
284
285     mWobbleProperty = mPaddle.RegisterProperty(WOBBLE_PROPERTY_NAME, 0.0f);
286     Constraint wobbleConstraint = Constraint::New<Quaternion>( mPaddle, Actor::Property::ORIENTATION, WobbleConstraint(Degree( 10.0f )));
287     wobbleConstraint.AddSource( LocalSource(mWobbleProperty) );
288     wobbleConstraint.Apply();
289
290     mPaddle.SetPosition( stageSize * Vector3( PADDLE_START_POSITION ) );
291     mContentLayer.Add(mPaddle);
292     mPaddle.TouchSignal().Connect(this, &ExampleController::OnTouchPaddle);
293     mContentLayer.TouchSignal().Connect(this, &ExampleController::OnTouchLayer);
294
295     const float margin(BALL_SIZE.width * stageSize.width * 0.5f);
296
297     // Set up notifications for ball's collisions against walls.
298     PropertyNotification leftNotification = mBall.AddPropertyNotification( Actor::Property::POSITION_X, LessThanCondition(margin) );
299     leftNotification.NotifySignal().Connect( this, &ExampleController::OnHitLeftWall );
300
301     PropertyNotification rightNotification = mBall.AddPropertyNotification( Actor::Property::POSITION_X, GreaterThanCondition(stageSize.width - margin) );
302     rightNotification.NotifySignal().Connect( this, &ExampleController::OnHitRightWall );
303
304     PropertyNotification topNotification = mBall.AddPropertyNotification( Actor::Property::POSITION_Y, LessThanCondition(margin) );
305     topNotification.NotifySignal().Connect( this, &ExampleController::OnHitTopWall );
306
307     PropertyNotification bottomNotification = mBall.AddPropertyNotification( Actor::Property::POSITION_Y, GreaterThanCondition(stageSize.height + margin) );
308     bottomNotification.NotifySignal().Connect( this, &ExampleController::OnHitBottomWall );
309
310     // Set up notification for ball colliding against paddle.
311     Actor delegate = Actor::New();
312     stage.Add(delegate);
313     Property::Index property = delegate.RegisterProperty(COLLISION_PROPERTY_NAME, Vector3::ZERO);
314     Constraint constraint = Constraint::New<Vector3>( delegate, property, CollisionCircleRectangleConstraint( -Vector3(0.0f, mPaddleHitMargin.height * 0.575f, 0.0f),-Vector3(mPaddleHitMargin) ) );
315     constraint.AddSource( Source(mBall, Actor::Property::POSITION) );
316     constraint.AddSource( Source(mPaddle, Actor::Property::POSITION) );
317     constraint.AddSource( Source(mBall, Actor::Property::SIZE) );
318     constraint.AddSource( Source(mPaddle, Actor::Property::SIZE) );
319     constraint.Apply();
320
321     PropertyNotification paddleNotification = delegate.AddPropertyNotification( property, GreaterThanCondition(0.0f) );
322     paddleNotification.NotifySignal().Connect( this, &ExampleController::OnHitPaddle );
323
324     RestartGame();
325   }
326
327   /**
328    * Restarts Game
329    * Resets Lives count and other stats, and loads level
330    */
331   void RestartGame()
332   {
333     mLives = TOTAL_LIVES;
334     mLevel = 0;
335     mBall.SetPosition( mBallStartPosition );
336     mBallVelocity = Vector3::ZERO;
337     mPaddle.SetSize( mPaddleFullSize + mPaddleHitMargin );
338     mPaddleImage.SetSize( mPaddleFullSize );
339
340     LoadLevel(mLevel);
341   }
342
343   /**
344    * Loads level
345    * All existing level content is removed, and new bricks
346    * are added.
347    * @param[in] level Level index to load.
348    */
349   void LoadLevel(int level)
350   {
351     if(mLevelContainer && mLevelContainer.GetParent() == mContentLayer)
352     {
353       mContentLayer.Remove( mLevelContainer );
354     }
355
356     mLevelContainer = Actor::New();
357     mLevelContainer.SetAnchorPoint( AnchorPoint::CENTER );
358     mLevelContainer.SetParentOrigin( ParentOrigin::CENTER );
359     mLevelContainer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
360
361     mContentLayer.Add( mLevelContainer );
362
363     mBrickCount = 0;
364
365     switch(level%TOTAL_LEVELS)
366     {
367       case 0:
368       {
369         GenerateLevel0();
370         break;
371       }
372       case 1:
373       {
374         GenerateLevel1();
375         break;
376       }
377       case 2:
378       {
379         GenerateLevel2();
380         break;
381       }
382       default:
383       {
384         break;
385       }
386     } // end switch
387   }
388
389   /**
390    * Generates level 0
391    */
392   void GenerateLevel0()
393   {
394     Vector2 stageSize(Stage::GetCurrent().GetSize());
395     const Vector2 brickSize(BRICK_SIZE * stageSize.width);
396
397     const int columns = (0.85f * stageSize.width) / brickSize.width; // 85 percent of the width of the screen covered with bricks.
398     const int rows = (0.3f * stageSize.height) / brickSize.height;   // 30 percent of the height of the screen covered with bricks.
399     const Vector2 offset( (stageSize.x - (columns * brickSize.width)) * 0.5f,
400                            stageSize.y * 0.125f );
401
402     for(int j = 0; j < rows; j++)
403     {
404       for(int i = 0; i < columns; i++)
405       {
406         Actor brick = CreateBrick(Vector2(i * brickSize.width + offset.x, j * brickSize.height + offset.y) + (brickSize * 0.5f), j % TOTAL_BRICKS );
407         mLevelContainer.Add(brick);
408         mBrickCount++;
409       }
410     }
411   }
412
413   /**
414    * Generates level 1
415    */
416   void GenerateLevel1()
417   {
418     Vector2 stageSize(Stage::GetCurrent().GetSize());
419     const Vector2 brickSize(BRICK_SIZE * stageSize.width);
420
421     const int columns = (0.85f * stageSize.width) / brickSize.width; // 85 percent of the width of the screen covered with bricks.
422     const int rows = (0.3f * stageSize.height) / brickSize.height;   // 30 percent of the height of the screen covered with bricks.
423     const Vector2 offset( (stageSize.x - (columns * brickSize.width)) * 0.5f,
424                            stageSize.y * 0.125f );
425
426     for(int j = 0; j < rows; j++)
427     {
428       for(int i = 0; i < columns; i++)
429       {
430         int i2 = columns - i - 1;
431         int j2 = rows - j - 1;
432         int brickIndex = std::min( std::min(i, j), std::min(i2, j2) ) % TOTAL_BRICKS;
433
434         Actor brick = CreateBrick(Vector2(i * brickSize.width + offset.x, j * brickSize.height + offset.y) + (brickSize * 0.5f), brickIndex );
435
436         mLevelContainer.Add(brick);
437         mBrickCount++;
438       }
439     }
440   }
441
442   /**
443    * Generates level 2
444    */
445   void GenerateLevel2()
446   {
447     Vector2 stageSize(Stage::GetCurrent().GetSize());
448     const Vector2 brickSize(BRICK_SIZE * stageSize.width);
449
450     const int columns = (0.85f * stageSize.width) / brickSize.width; // 85 percent of the width of the screen covered with bricks.
451     const int rows = (0.3f * stageSize.height) / brickSize.height;   // 30 percent of the height of the screen covered with bricks.
452     const Vector2 offset( (stageSize.x - (columns * brickSize.width)) * 0.5f,
453                            stageSize.y * 0.125f );
454
455     // lays down bricks in a spiral formation starting at i,j = (0,0) top left corner
456     // travelling right di,dj = (1,0) initially
457     int i = 0;
458     int j = 0;
459     int di = 1;
460     int dj = 0;
461
462     // contracting boundaries
463     int left = 0;
464     int right = columns - 1;
465     int top = 2;
466     int bottom = rows - 1;
467
468     // length of current line. we stop laying down bricks when the length is 1 brick or less.
469     int length = 0;
470     while(true)
471     {
472       Actor brick = CreateBrick(Vector2(i * brickSize.width + offset.x, j * brickSize.height + offset.y) + (brickSize * 0.5f), 0 );
473       mLevelContainer.Add(brick);
474       i+=di;
475       j+=dj;
476       bool turn(false);
477       if((i==right) && (di==1))
478       {
479         right -= 2;
480         turn = true;
481       }
482       if((j==bottom) && (dj==1))
483       {
484         bottom -= 2;
485         turn = true;
486       }
487       if((i==left) && (di==-1))
488       {
489         left += 2;
490         turn = true;
491       }
492       if((j==top) && (dj==-1))
493       {
494         top += 2;
495         turn = true;
496       }
497       if(turn)
498       {
499         // turn 90 degrees clockwise.
500         std::swap(di, dj);
501         di = -di;
502         if (length<=1)
503         {
504           break;
505         }
506         length = 0;
507       }
508       length++;
509       mBrickCount++;
510     }
511   }
512
513
514   /**
515    * Creates a brick at a specified position on the stage
516    * @param[in] position the position for the brick
517    * @param[in] type the type of brick
518    * @return The Brick Actor is returned.
519    */
520   Actor CreateBrick( const Vector2& position, int type )
521   {
522     Vector2 stageSize(Stage::GetCurrent().GetSize());
523     const Vector2 brickSize(BRICK_SIZE * Vector2(stageSize.x, stageSize.x));
524
525     Image img = ResourceImage::New( BRICK_IMAGE_PATH[type], Dali::ImageDimensions( 128, 64 ), Dali::FittingMode::SCALE_TO_FILL, Dali::SamplingMode::BOX_THEN_LINEAR );
526     ImageView brick = ImageView::New(img);
527     brick.SetParentOrigin(ParentOrigin::TOP_LEFT);
528     brick.SetAnchorPoint(AnchorPoint::CENTER);
529     brick.SetSize( brickSize );
530     brick.SetPosition( Vector3( position ) );
531
532     // Add a constraint on the brick between it and the ball generating a collision-property
533     Property::Index property = brick.RegisterProperty(COLLISION_PROPERTY_NAME, Vector3::ZERO);
534     Constraint constraint = Constraint::New<Vector3>( brick, property, CollisionCircleRectangleConstraint(BRICK_COLLISION_MARGIN) );
535     constraint.AddSource( Source(mBall, Actor::Property::POSITION) );
536     constraint.AddSource( Source(brick, Actor::Property::POSITION) );
537     constraint.AddSource( Source(mBall, Actor::Property::SIZE) );
538     constraint.AddSource( Source(brick, Actor::Property::SIZE) );
539     constraint.Apply();
540
541     // Now add a notification on this collision-property
542
543     PropertyNotification brickNotification = brick.AddPropertyNotification( property, GreaterThanCondition(0.0f) );
544     brickNotification.NotifySignal().Connect( this, &ExampleController::OnHitBrick );
545
546     return brick;
547   }
548
549   /**
550    * Creates an Image (Helper)
551    *
552    * @param[in] filename the path of the image.
553    */
554   ImageView CreateImage(const std::string& filename)
555   {
556     ImageView actor = ImageView::New(filename);
557     actor.SetParentOrigin(ParentOrigin::TOP_LEFT);
558     actor.SetAnchorPoint(AnchorPoint::CENTER);
559     return actor;
560   }
561
562   /**
563    * Continue animation (based on current velocity)
564    */
565   void ContinueAnimation()
566   {
567     if(mBallAnimation)
568     {
569       mBallAnimation.Clear();
570     }
571
572     mBallAnimation = Animation::New(MAX_ANIMATION_DURATION);
573     mBallAnimation.AnimateBy( Property( mBall, Actor::Property::POSITION ), mBallVelocity * MAX_ANIMATION_DURATION);
574     mBallAnimation.Play();
575   }
576
577   /**
578    * Signal invoked whenever user touches the Paddle.
579    * @param[in] actor The actor touched
580    * @param[in] event The touch event
581    */
582   bool OnTouchPaddle(Actor actor, const TouchData& event)
583   {
584     if(event.GetPointCount()>0)
585     {
586       if( event.GetState( 0 ) == PointState::DOWN ) // Commence dragging
587       {
588         // Get point where user touched paddle (relative to paddle's center)
589         Vector2 screenPoint = event.GetScreenPosition( 0 );
590         mRelativeDragPoint = screenPoint;
591         mRelativeDragPoint -= actor.GetCurrentPosition();
592
593         mDragActor = actor;
594         mDragAnimation = Animation::New(0.25f);
595         mDragAnimation.AnimateTo( Property(mDragActor, Actor::Property::SCALE), Vector3(1.1f, 1.1f, 1.0f), AlphaFunction::EASE_OUT);
596         mDragAnimation.AnimateTo( Property(mPaddleHandle, Actor::Property::COLOR), Vector4(1.0f, 1.0f, 1.0f, 0.0f), AlphaFunction::EASE_OUT);
597         mDragAnimation.Play();
598       }
599     }
600     return false;
601   }
602
603   /**
604    * Signal invoked whenever user touches anywhere on the screen.
605    * @param[in] actor The actor touched
606    * @param[in] event The touch event
607    */
608   bool OnTouchLayer(Actor actor, const TouchData& event)
609   {
610     if(event.GetPointCount()>0)
611     {
612       if(mDragActor)
613       {
614         Vector3 position( event.GetScreenPosition( 0 ) );
615         mPaddle.SetPosition( position - mRelativeDragPoint );
616
617         if( event.GetState( 0 ) == PointState::UP ) // Stop dragging
618         {
619           mDragAnimation = Animation::New(0.25f);
620           mDragAnimation.AnimateTo( Property(mDragActor, Actor::Property::SCALE), Vector3(1.0f, 1.0f, 1.0f), AlphaFunction::EASE_IN);
621           mDragAnimation.AnimateTo( Property(mPaddleHandle, Actor::Property::COLOR), Vector4(1.0f, 1.0f, 1.0f, 1.0f), AlphaFunction::EASE_OUT);
622           mDragAnimation.Play();
623           mDragActor.Reset();
624         }
625       }
626     }
627     return false;
628   }
629
630   /**
631    * Notification: Ball hit left wall
632    * @param source The notification
633    */
634   void OnHitLeftWall(PropertyNotification& source)
635   {
636     mBallVelocity.x = fabsf(mBallVelocity.x);
637     ContinueAnimation();
638   }
639
640   /**
641    * Notification: Ball hit right wall
642    * @param source The notification
643    */
644   void OnHitRightWall(PropertyNotification& source)
645   {
646     mBallVelocity.x = -fabsf(mBallVelocity.x);
647     ContinueAnimation();
648   }
649
650   /**
651    * Notification: Ball hit top wall
652    * @param source The notification
653    */
654   void OnHitTopWall(PropertyNotification& source)
655   {
656     mBallVelocity.y = fabsf(mBallVelocity.y);
657     ContinueAnimation();
658   }
659
660   /**
661    * Notification: Ball hit bottom wall
662    * @param source The notification
663    */
664   void OnHitBottomWall(PropertyNotification& source)
665   {
666     if(mBallAnimation)
667     {
668       mBallAnimation.Clear();
669     }
670
671     if(mLives>0)
672     {
673       mLives--;
674       const float f(static_cast<float>(mLives) / TOTAL_LIVES);
675       mBallVelocity = Vector3::ZERO;
676
677       Animation shrink = Animation::New(0.5f);
678       shrink.AnimateTo( Property(mPaddle, Actor::Property::SIZE_WIDTH), mPaddleFullSize.x * f + mPaddleHitMargin.x);
679       shrink.AnimateTo( Property(mPaddleImage, Actor::Property::SIZE_WIDTH), mPaddleFullSize.x * f );
680
681       shrink.FinishedSignal().Connect( this, &ExampleController::OnPaddleShrunk );
682       shrink.Play();
683     }
684   }
685
686   /**
687    * Paddle Shrink Animation complete.
688    * @param[in] source The animation responsible for shrinking the paddle.
689    */
690   void OnPaddleShrunk( Animation &source )
691   {
692     // Reposition Ball in start position, and make ball appear.
693     mBall.SetPosition( mBallStartPosition );
694     mBall.SetColor( Vector4(1.0f, 1.0f, 1.0f, 0.1f) );
695     Animation appear = Animation::New(0.5f);
696     appear.AnimateTo( Property(mBall, Actor::Property::COLOR), Vector4(1.0f, 1.0f, 1.0f, 1.0f) );
697     appear.Play();
698
699     if(!mLives)
700     {
701       RestartGame();
702     }
703   }
704
705   /**
706    * Notification: Ball hit paddle
707    * @param source The notification
708    */
709   void OnHitPaddle(PropertyNotification& source)
710   {
711     Actor delegate = Actor::DownCast(source.GetTarget());
712     Vector3 collisionVector = delegate.GetProperty<Vector3>(source.GetTargetProperty());
713     Vector3 ballRelativePosition(mBall.GetCurrentPosition() - mPaddle.GetCurrentPosition());
714     ballRelativePosition.Normalize();
715
716     collisionVector.x += ballRelativePosition.x * 0.5f;
717
718     if(mBallVelocity.LengthSquared() < Math::MACHINE_EPSILON_1)
719     {
720       mBallVelocity += collisionVector * BALL_VELOCITY;
721     }
722     else
723     {
724       const float normalVelocity = fabsf(mBallVelocity.Dot(collisionVector));
725       mBallVelocity += collisionVector * normalVelocity * 2.0f;
726       const float currentSpeed = mBallVelocity.Length();
727       const float limitedSpeed = std::min( currentSpeed, MAX_VELOCITY );
728       mBallVelocity = mBallVelocity * limitedSpeed / currentSpeed;
729     }
730
731     ContinueAnimation();
732
733     // wobble paddle
734     mWobbleAnimation = Animation::New(0.5f);
735     mWobbleAnimation.AnimateTo( Property( mPaddle, mWobbleProperty ), 1.0f );
736     mWobbleAnimation.Play();
737     mPaddle.SetProperty(mWobbleProperty, 0.0f);
738   }
739
740   /**
741    * Notification: Ball hit brick
742    * @param source The notification
743    */
744   void OnHitBrick(PropertyNotification& source)
745   {
746     Actor brick = Actor::DownCast(source.GetTarget());
747     Vector3 collisionVector = brick.GetProperty<Vector3>(source.GetTargetProperty());
748
749     const float normalVelocity = fabsf(mBallVelocity.Dot(collisionVector));
750     mBallVelocity += collisionVector * normalVelocity * 2.0f;
751     const float currentSpeed = mBallVelocity.Length();
752     const float limitedSpeed = std::min( currentSpeed, MAX_VELOCITY );
753     mBallVelocity = mBallVelocity * limitedSpeed / currentSpeed;
754
755     ContinueAnimation();
756
757     // remove collision-constraint and notification.
758     brick.RemovePropertyNotification(source);
759     brick.RemoveConstraints();
760
761     // fade brick (destroy)
762     Animation destroyAnimation = Animation::New(0.5f);
763     destroyAnimation.AnimateTo( Property( brick, Actor::Property::COLOR_ALPHA ), 0.0f, AlphaFunction::EASE_IN );
764     destroyAnimation.Play();
765     destroyAnimation.FinishedSignal().Connect( this, &ExampleController::OnBrickDestroyed );
766     mDestroyAnimationMap[destroyAnimation] = brick;
767   }
768
769   /**
770    * Brick Destruction Animation complete.
771    * @param[in] source The animation responsible for destroying the brick
772    */
773   void OnBrickDestroyed( Animation& source )
774   {
775     // Remove brick from stage, it's constraint and property notification should also remove themselves.
776     Actor brick = mDestroyAnimationMap[source];
777     mDestroyAnimationMap.erase(source);
778     brick.GetParent().Remove(brick);
779     mBrickCount--;
780
781     if(!mBrickCount)
782     {
783       mLevel++;
784       LoadLevel(mLevel);
785     }
786   }
787
788   /**
789    * Main key event handler
790    */
791   void OnKeyEvent(const KeyEvent& event)
792   {
793     if(event.state == KeyEvent::Down)
794     {
795       if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
796       {
797         mApplication.Quit();
798       }
799     }
800   }
801
802 private:
803
804   Application& mApplication;                            ///< Application instance
805   Toolkit::Control mView;                               ///< The View instance.
806   Layer mContentLayer;                                  ///< The content layer (contains game actors)
807   ImageView mBall;                                      ///< The Moving ball image.
808   Vector3 mBallStartPosition;                           ///< Ball Start position
809   Vector3 mBallVelocity;                                ///< Ball's current direction.
810   Animation mBallAnimation;                             ///< Ball's animation
811   Actor mPaddle;                                        ///< The paddle including hit area.
812   ImageView mPaddleImage;                               ///< The paddle's image.
813   ImageView mPaddleHandle;                              ///< The paddle's handle (where the user touches)
814   Vector2 mPaddleHitMargin;                             ///< The paddle hit margin.
815   Animation mWobbleAnimation;                           ///< Paddle's animation when hit (wobbles)
816   Property::Index mWobbleProperty;                      ///< The wobble property (generated from animation)
817   Actor mLevelContainer;                                ///< The level container (contains bricks)
818
819   // actor - dragging functionality
820
821   Animation mDragAnimation;                             ///< Animation for dragging. (grows - affects ACTOR::SCALE)
822   Actor mDragActor;                                     ///< The actor which is being dragged (if any)
823   Vector3 mRelativeDragPoint;                           ///< The point the user touched, relative to the actor.
824   std::map<Animation, Actor> mDestroyAnimationMap;      ///< Keep track of which actors are to be destroyed.
825   Vector2 mPaddleFullSize;                              ///< Initial 100% size of the paddle.
826   int mLevel;                                           ///< Current level
827   int mLives;                                           ///< Total lives.
828   int mBrickCount;                                      ///< Total bricks on screen.
829 };
830
831 void RunTest(Application& app)
832 {
833   ExampleController test(app);
834
835   app.MainLoop();
836 }
837
838 int DALI_EXPORT_API main(int argc, char **argv)
839 {
840   Application app = Application::New(&argc, &argv, DEMO_THEME_PATH);
841
842   RunTest(app);
843
844   return 0;
845 }