75b537f1fdbd27ae7357a0ede780d02f6bf0b085
[platform/core/uifw/dali-toolkit.git] / optional / dali-toolkit / internal / controls / gaussian-blur-view / gaussian-blur-view-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 "gaussian-blur-view-impl.h"
20
21 // EXTERNAL INCLUDES
22 #include <sstream>
23 #include <iomanip>
24
25 // INTERNAL INCLUDES
26 #include <dali-toolkit/public-api/controls/gaussian-blur-view/gaussian-blur-view.h>
27
28 #include <dali/integration-api/debug.h>
29
30 // TODO:
31 // pixel format / size - set from JSON
32 // aspect ratio property needs to be able to be constrained also for cameras, not possible currently. Therefore changing aspect ratio of GaussianBlurView won't currently work
33 // default near clip value
34 // mChildrenRoot Add()/Remove() overloads - better solution
35 // Manager object - re-use render targets if there are multiple GaussianBlurViews created
36
37
38
39 /////////////////////////////////////////////////////////
40 // IMPLEMENTATION NOTES
41
42 // As the GaussianBlurView actor changes size, the amount of pixels we need to blur changes. Therefore we need some way of doing this. However:-
43 // OnSetSize() does not get called when GaussianBlurView object size is modified using a Constraint.
44 // OnSizeAnimation() only gets called once per AnimateTo/By() and if an Animation has N such calls then only the final one will end up being used. Therefore we can't use
45 // OnSizeAnimation() to alter render target sizes.
46 // To get around the above problems, we use fixed sized render targets, from the last SetSize() call (which calls OnSetSize()), then we adjust the internal cameras / actors
47 // to take account of the changed GaussianBlurView object size, projecting to the unchanged render target sizes. This is done relative to the fixed render target / actor sizes
48 // by using constraints relative to the GaussianBlurView actor size.
49
50
51 // 2 modes:
52 // 1st mode, this control has a tree of actors (use Add() to add children) that are rendered and blurred.
53 // mRenderChildrenTask renders children to FB mRenderTargetForRenderingChildren
54 // mHorizBlurTask renders mImageActorHorizBlur Actor showing FB mRenderTargetForRenderingChildren into FB mRenderTarget2
55 // mVertBlurTask renders mImageActorVertBlur Actor showing FB mRenderTarget2 into FB mRenderTarget1
56 // mCompositeTask renders mImageActorComposite Actor showing FB mRenderTarget1 into FB mRenderTargetForRenderingChildren
57 //
58 // 2nd mode, an image is blurred and rendered to a supplied target framebuffer
59 // mHorizBlurTask renders mImageActorHorizBlur Actor showing mUserInputImage into FB mRenderTarget2
60 // mVertBlurTask renders mImageActorVertBlur Actor showing mRenderTarget2 into FB mUserOutputRenderTarget
61 //
62 // Only this 2nd mode handles ActivateOnce
63
64 namespace Dali
65 {
66
67 namespace Toolkit
68 {
69
70 namespace Internal
71 {
72
73 namespace
74 {
75
76 using namespace Dali;
77
78 BaseHandle Create()
79 {
80   return Toolkit::GaussianBlurView::New();
81 }
82
83 TypeRegistration mType( typeid(Toolkit::GaussianBlurView), typeid(Toolkit::Control), Create );
84
85
86 const unsigned int GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES = 5;
87 const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH = 1.5f;
88 const Pixel::Format GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888;
89 const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH = 1.0f;                                       // default, fully blurred
90 const std::string GAUSSIAN_BLUR_VIEW_STRENGTH_PROPERTY_NAME("GaussianBlurStrengthPropertyName");
91 const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE = 0.5f;
92 const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE = 0.5f;
93
94 const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f;
95
96 const char* const GAUSSIAN_BLUR_FRAGMENT_SOURCE =
97     "uniform vec2 uSampleOffsets[NUM_SAMPLES];\n"
98     "uniform float uSampleWeights[NUM_SAMPLES];\n"
99
100     "void main()\n"
101     "{\n"
102     "   mediump vec4 col;\n"
103     "   col = texture2D(sTexture, vec2(vTexCoord.x, vTexCoord.y) + uSampleOffsets[0]) * uSampleWeights[0];     \n"
104     "   for (int i=1; i<NUM_SAMPLES; ++i)                                                                      \n"
105     "   {                                                                                                      \n"
106     "     col += texture2D(sTexture, vec2(vTexCoord.x, vTexCoord.y) + uSampleOffsets[i]) * uSampleWeights[i];  \n"
107     "   }                                                                                                      \n"
108     "   gl_FragColor = col;\n"
109     "}\n";
110
111 } // namespace
112
113
114 GaussianBlurView::GaussianBlurView()
115   : Control( CONTROL_BEHAVIOUR_NONE )
116   , mNumSamples(GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES)
117   , mBlurBellCurveWidth( 0.001f )
118   , mPixelFormat(GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT)
119   , mDownsampleWidthScale(GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE)
120   , mDownsampleHeightScale(GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE)
121   , mDownsampledWidth( 0.0f )
122   , mDownsampledHeight( 0.0f )
123   , mBlurUserImage( false )
124   , mRenderOnce( false )
125   , mBackgroundColor( Color::BLACK )
126   , mTargetSize(Vector2::ZERO)
127   , mLastSize(Vector2::ZERO)
128   , mChildrenRoot(Actor::New())
129   , mBlurStrengthPropertyIndex(Property::INVALID_INDEX)
130 {
131   SetBlurBellCurveWidth(GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH);
132 }
133
134 GaussianBlurView::GaussianBlurView( const unsigned int numSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat,
135                                     const float downsampleWidthScale, const float downsampleHeightScale,
136                                     bool blurUserImage)
137   : Control( CONTROL_BEHAVIOUR_NONE )
138   , mNumSamples(numSamples)
139   , mPixelFormat(renderTargetPixelFormat)
140   , mDownsampleWidthScale(downsampleWidthScale)
141   , mDownsampleHeightScale(downsampleHeightScale)
142   , mDownsampledWidth( 0.0f )
143   , mDownsampledHeight( 0.0f )
144   , mBlurUserImage( blurUserImage )
145   , mBackgroundColor( Color::BLACK )
146   , mTargetSize(Vector2::ZERO)
147   , mLastSize(Vector2::ZERO)
148   , mChildrenRoot(Actor::New())
149   , mBlurStrengthPropertyIndex(Property::INVALID_INDEX)
150 {
151   SetBlurBellCurveWidth(blurBellCurveWidth);
152 }
153
154 GaussianBlurView::~GaussianBlurView()
155 {
156 }
157
158
159 Toolkit::GaussianBlurView GaussianBlurView::New()
160 {
161   GaussianBlurView* impl = new GaussianBlurView();
162
163   Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView( *impl );
164
165   // Second-phase init of the implementation
166   // This can only be done after the CustomActor connection has been made...
167   impl->Initialize();
168
169   return handle;
170 }
171
172 Toolkit::GaussianBlurView GaussianBlurView::New(const unsigned int numSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat,
173                                                 const float downsampleWidthScale, const float downsampleHeightScale,
174                                                 bool blurUserImage)
175 {
176   GaussianBlurView* impl = new GaussianBlurView( numSamples, blurBellCurveWidth, renderTargetPixelFormat,
177                                                  downsampleWidthScale, downsampleHeightScale,
178                                                  blurUserImage);
179
180   Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView( *impl );
181
182   // Second-phase init of the implementation
183   // This can only be done after the CustomActor connection has been made...
184   impl->Initialize();
185
186   return handle;
187 }
188
189 /////////////////////////////////////////////////////////////
190 // for creating a subtree for all user added child actors, so that we can have them exclusive to the mRenderChildrenTask and our other actors exclusive to our other tasks
191 // TODO: overloading Actor::Add()/Remove() not nice since breaks polymorphism. Need another method to pass ownership of added child actors to our internal actor root.
192 void GaussianBlurView::Add(Actor child)
193 {
194   mChildrenRoot.Add(child);
195 }
196
197 void GaussianBlurView::Remove(Actor child)
198 {
199   mChildrenRoot.Remove(child);
200 }
201
202 void GaussianBlurView::SetUserImageAndOutputRenderTarget(Image inputImage, FrameBufferImage outputRenderTarget)
203 {
204   // can only do this if the GaussianBlurView object was created with this parameter set
205   DALI_ASSERT_ALWAYS(mBlurUserImage);
206
207   mUserInputImage = inputImage;
208   mImageActorHorizBlur.SetImage( mUserInputImage );
209
210   mUserOutputRenderTarget = outputRenderTarget;
211 }
212
213 FrameBufferImage GaussianBlurView::GetBlurredRenderTarget() const
214 {
215   if(!mUserOutputRenderTarget)
216   {
217     return mRenderTargetForRenderingChildren;
218   }
219
220   return mUserOutputRenderTarget;
221 }
222
223 void GaussianBlurView::SetBackgroundColor( const Vector4& color )
224 {
225   mBackgroundColor = color;
226 }
227
228 Vector4 GaussianBlurView::GetBackgroundColor() const
229 {
230   return mBackgroundColor;
231 }
232
233 ///////////////////////////////////////////////////////////
234 //
235 // Private methods
236 //
237
238 /**
239  * EqualToConstraintFloat
240  *
241  * f(current, property) = property
242  */
243 struct EqualToConstraintFloat
244 {
245   EqualToConstraintFloat(){}
246
247   float operator()(const float current, const PropertyInput& property) {return property.GetFloat();}
248 };
249
250 void GaussianBlurView::OnInitialize()
251 {
252   // root actor to parent all user added actors, needed to allow us to set that subtree as exclusive for our child render task
253   mChildrenRoot.SetParentOrigin(ParentOrigin::CENTER);
254   mChildrenRoot.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) ); // same size as GaussianBlurView object
255
256
257   //////////////////////////////////////////////////////
258   // Create shaders
259
260   // horiz
261   std::ostringstream horizFragmentShaderStringStream;
262   horizFragmentShaderStringStream << "#define NUM_SAMPLES " << mNumSamples << "\n";
263   horizFragmentShaderStringStream << GAUSSIAN_BLUR_FRAGMENT_SOURCE;
264   mHorizBlurShader = ShaderEffect::New( "", horizFragmentShaderStringStream.str() );
265   // vert
266   std::ostringstream vertFragmentShaderStringStream;
267   vertFragmentShaderStringStream << "#define NUM_SAMPLES " << mNumSamples << "\n";
268   vertFragmentShaderStringStream << GAUSSIAN_BLUR_FRAGMENT_SOURCE;
269   mVertBlurShader = ShaderEffect::New( "", vertFragmentShaderStringStream.str() );
270
271
272   //////////////////////////////////////////////////////
273   // Create actors
274
275   // Create an ImageActor for performing a horizontal blur on the texture
276   mImageActorHorizBlur = ImageActor::New();
277   mImageActorHorizBlur.SetParentOrigin(ParentOrigin::CENTER);
278   mImageActorHorizBlur.ScaleBy( Vector3(1.0f, -1.0f, 1.0f) ); // FIXME
279   mImageActorHorizBlur.SetShaderEffect( mHorizBlurShader );
280
281   // Create an ImageActor for performing a vertical blur on the texture
282   mImageActorVertBlur = ImageActor::New();
283   mImageActorVertBlur.SetParentOrigin(ParentOrigin::CENTER);
284   mImageActorVertBlur.ScaleBy( Vector3(1.0f, -1.0f, 1.0f) ); // FIXME
285   mImageActorVertBlur.SetShaderEffect( mVertBlurShader );
286
287   // Register a property that the user can control to fade the blur in / out via the GaussianBlurView object
288   mBlurStrengthPropertyIndex = Self().RegisterProperty(GAUSSIAN_BLUR_VIEW_STRENGTH_PROPERTY_NAME, GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH);
289
290   // Create an ImageActor for compositing the blur and the original child actors render
291   if(!mBlurUserImage)
292   {
293     mImageActorComposite = ImageActor::New();
294     mImageActorComposite.SetParentOrigin(ParentOrigin::CENTER);
295     mImageActorComposite.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) ); // same size as GaussianBlurView object
296     mImageActorComposite.ScaleBy( Vector3(1.0f, -1.0f, 1.0f) ); // FIXME
297     mImageActorComposite.SetOpacity(GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH); // ensure alpha is enabled for this object and set default value
298
299     Constraint blurStrengthConstraint = Constraint::New<float>( Actor::COLOR_ALPHA, ParentSource(mBlurStrengthPropertyIndex), EqualToConstraintFloat());
300     mImageActorComposite.ApplyConstraint(blurStrengthConstraint);
301
302     // Create an ImageActor for holding final result, i.e. the blurred image. This will get rendered to screen later, via default / user render task
303     mTargetActor = ImageActor::New();
304     mTargetActor.SetParentOrigin(ParentOrigin::CENTER);
305     mTargetActor.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) ); // same size as GaussianBlurView object
306     mTargetActor.ScaleBy( Vector3(1.0f, -1.0f, 1.0f) ); // FIXME
307
308
309     //////////////////////////////////////////////////////
310     // Create cameras for the renders corresponding to the view size
311     mRenderFullSizeCamera = CameraActor::New();
312     mRenderFullSizeCamera.SetParentOrigin(ParentOrigin::CENTER);
313
314
315     //////////////////////////////////////////////////////
316     // Connect to actor tree
317     Self().Add( mImageActorComposite );
318     Self().Add( mTargetActor );
319     Self().Add( mRenderFullSizeCamera );
320   }
321
322
323   //////////////////////////////////////////////////////
324   // Create camera for the renders corresponding to the (potentially downsampled) render targets' size
325   mRenderDownsampledCamera = CameraActor::New();
326   mRenderDownsampledCamera.SetParentOrigin(ParentOrigin::CENTER);
327
328
329   //////////////////////////////////////////////////////
330   // Connect to actor tree
331   Self().Add( mChildrenRoot );
332   Self().Add( mImageActorHorizBlur );
333   Self().Add( mImageActorVertBlur );
334   Self().Add( mRenderDownsampledCamera );
335 }
336
337
338 /**
339  * ZrelativeToYconstraint
340  *
341  * f(current, property, scale) = Vector3(current.x, current.y, property.y * scale)
342  */
343 struct ZrelativeToYconstraint
344 {
345   ZrelativeToYconstraint( float scale )
346     : mScale( scale )
347   {}
348
349   Vector3 operator()(const Vector3&    current,
350                      const PropertyInput& property)
351   {
352     Vector3 v;
353
354     v.x = current.x;
355     v.y = current.y;
356     v.z = property.GetVector3().y * mScale;
357
358     return v;
359   }
360
361   float mScale;
362 };
363
364 void GaussianBlurView::OnControlSizeSet(const Vector3& targetSize)
365 {
366   mTargetSize = Vector2(targetSize);
367
368   // if we are already on stage, need to update render target sizes now to reflect the new size of this actor
369   if(Self().OnStage())
370   {
371     AllocateResources();
372   }
373 }
374
375 void GaussianBlurView::AllocateResources()
376 {
377   // size of render targets etc is based on the size of this actor, ignoring z
378   if(mTargetSize != mLastSize)
379   {
380     mLastSize = mTargetSize;
381
382     // get size of downsampled render targets
383     mDownsampledWidth = mTargetSize.width * mDownsampleWidthScale;
384     mDownsampledHeight = mTargetSize.height * mDownsampleHeightScale;
385
386     // Create and place a camera for the renders corresponding to the (potentially downsampled) render targets' size
387     mRenderDownsampledCamera.SetFieldOfView(ARBITRARY_FIELD_OF_VIEW);
388     // TODO: how do we pick a reasonable value for near clip? Needs to relate to normal camera the user renders with, but we don't have a handle on it
389     mRenderDownsampledCamera.SetNearClippingPlane(1.0f);
390     mRenderDownsampledCamera.SetAspectRatio(mDownsampledWidth / mDownsampledHeight);
391     mRenderDownsampledCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor
392     // Point the camera back into the scene
393     mRenderDownsampledCamera.SetRotation(Quaternion(M_PI, Vector3::YAXIS));
394
395     mRenderDownsampledCamera.SetPosition(0.0f, 0.0f, ((mDownsampledHeight * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f)));
396
397     // setup for normal operation
398     if(!mBlurUserImage)
399     {
400       // Create and place a camera for the children render, corresponding to its render target size
401       mRenderFullSizeCamera.SetFieldOfView(ARBITRARY_FIELD_OF_VIEW);
402       // TODO: how do we pick a reasonable value for near clip? Needs to relate to normal camera the user renders with, but we don't have a handle on it
403       mRenderFullSizeCamera.SetNearClippingPlane(1.0f);
404       mRenderFullSizeCamera.SetAspectRatio(mTargetSize.width / mTargetSize.height);
405       mRenderFullSizeCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor
406       // Point the camera back into the scene
407       mRenderFullSizeCamera.SetRotation(Quaternion(M_PI, Vector3::YAXIS));
408
409       float cameraPosConstraintScale = 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f);
410       mRenderFullSizeCamera.SetPosition(0.0f, 0.0f, mTargetSize.height * cameraPosConstraintScale);
411
412       // Children render camera must move when GaussianBlurView object is resized. This is since we cannot change render target size - so we need to remap the child actors' rendering
413       // accordingly so they still exactly fill the render target. Note that this means the effective resolution of the child render changes as the GaussianBlurView object changes
414       // size, this is the trade off for not being able to modify render target size
415       // Change camera z position based on GaussianBlurView actor height
416       mRenderFullSizeCamera.RemoveConstraints();
417       mRenderFullSizeCamera.ApplyConstraint( Constraint::New<Vector3>( Actor::POSITION, ParentSource( Actor::SIZE ), ZrelativeToYconstraint(cameraPosConstraintScale) ) );
418
419       // create offscreen buffer of new size to render our child actors to
420       mRenderTargetForRenderingChildren = FrameBufferImage::New( mTargetSize.width, mTargetSize.height, mPixelFormat, Dali::Image::Unused );
421
422       // Set ImageActor for performing a horizontal blur on the texture
423       mImageActorHorizBlur.SetImage( mRenderTargetForRenderingChildren );
424
425       // Create offscreen buffer for vert blur pass
426       mRenderTarget1 = FrameBufferImage::New( mDownsampledWidth, mDownsampledHeight, mPixelFormat, Dali::Image::Unused );
427
428       // use the completed blur in the first buffer and composite with the original child actors render
429       mImageActorComposite.SetImage( mRenderTarget1 );
430
431       // set up target actor for rendering result, i.e. the blurred image
432       mTargetActor.SetImage(mRenderTargetForRenderingChildren);
433     }
434
435     // Create offscreen buffer for horiz blur pass
436     mRenderTarget2 = FrameBufferImage::New( mDownsampledWidth, mDownsampledHeight, mPixelFormat, Dali::Image::Unused );
437
438     // size needs to match render target
439     mImageActorHorizBlur.SetSize(mDownsampledWidth, mDownsampledHeight);
440
441     // size needs to match render target
442     mImageActorVertBlur.SetImage( mRenderTarget2 );
443     mImageActorVertBlur.SetSize(mDownsampledWidth, mDownsampledHeight);
444
445     // set gaussian blur up for new sized render targets
446     SetShaderConstants();
447   }
448 }
449
450 void GaussianBlurView::CreateRenderTasks()
451 {
452   RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
453
454   if(!mBlurUserImage)
455   {
456     // create render task to render our child actors to offscreen buffer
457     mRenderChildrenTask = taskList.CreateTask();
458     mRenderChildrenTask.SetSourceActor( mChildrenRoot );
459     mRenderChildrenTask.SetExclusive(true);
460     mRenderChildrenTask.SetInputEnabled( false );
461     mRenderChildrenTask.SetClearEnabled( true );
462     mRenderChildrenTask.SetClearColor( mBackgroundColor );
463
464     mRenderChildrenTask.SetCameraActor(mRenderFullSizeCamera);
465     mRenderChildrenTask.SetTargetFrameBuffer( mRenderTargetForRenderingChildren );
466   }
467
468   // perform a horizontal blur targeting the second buffer
469   mHorizBlurTask = taskList.CreateTask();
470   mHorizBlurTask.SetSourceActor( mImageActorHorizBlur );
471   mHorizBlurTask.SetExclusive(true);
472   mHorizBlurTask.SetInputEnabled( false );
473   mHorizBlurTask.SetClearEnabled( true );
474   mHorizBlurTask.SetClearColor( mBackgroundColor );
475   if( mRenderOnce && mBlurUserImage )
476   {
477     mHorizBlurTask.SetRefreshRate(RenderTask::REFRESH_ONCE);
478   }
479
480   // use the second buffer and perform a horizontal blur targeting the first buffer
481   mVertBlurTask = taskList.CreateTask();
482   mVertBlurTask.SetSourceActor( mImageActorVertBlur );
483   mVertBlurTask.SetExclusive(true);
484   mVertBlurTask.SetInputEnabled( false );
485   mVertBlurTask.SetClearEnabled( true );
486   mVertBlurTask.SetClearColor( mBackgroundColor );
487   if( mRenderOnce && mBlurUserImage )
488   {
489     mVertBlurTask.SetRefreshRate(RenderTask::REFRESH_ONCE);
490     mVertBlurTask.FinishedSignal().Connect( this, &GaussianBlurView::OnRenderTaskFinished );
491   }
492
493   // use the completed blur in the first buffer and composite with the original child actors render
494   if(!mBlurUserImage)
495   {
496     mCompositeTask = taskList.CreateTask();
497     mCompositeTask.SetSourceActor( mImageActorComposite );
498     mCompositeTask.SetExclusive(true);
499     mCompositeTask.SetInputEnabled( false );
500
501     mCompositeTask.SetCameraActor(mRenderFullSizeCamera);
502     mCompositeTask.SetTargetFrameBuffer( mRenderTargetForRenderingChildren );
503   }
504
505   mHorizBlurTask.SetCameraActor(mRenderDownsampledCamera);
506   mVertBlurTask.SetCameraActor(mRenderDownsampledCamera);
507
508   mHorizBlurTask.SetTargetFrameBuffer( mRenderTarget2 );
509   if(mUserOutputRenderTarget)
510   {
511     mVertBlurTask.SetTargetFrameBuffer( mUserOutputRenderTarget );
512   }
513   else
514   {
515     mVertBlurTask.SetTargetFrameBuffer( mRenderTarget1 );
516   }
517 }
518
519 void GaussianBlurView::RemoveRenderTasks()
520 {
521   RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
522
523   taskList.RemoveTask(mRenderChildrenTask);
524   taskList.RemoveTask(mHorizBlurTask);
525   taskList.RemoveTask(mVertBlurTask);
526   taskList.RemoveTask(mCompositeTask);
527 }
528
529 void GaussianBlurView::OnStageDisconnection()
530 {
531   // TODO: can't call this here, since SetImage() calls fails similarly to above
532   // Need to fix the stage connection so this callback can be used arbitrarily. At that point we  can simplify the API by removing the need for Activate() / Deactivate()
533   //Deactivate();
534 }
535
536 void GaussianBlurView::OnControlStageConnection()
537 {
538   // TODO: can't call this here, since SetImage() calls fail to connect images to stage, since parent chain not fully on stage yet
539   // Need to fix the stage connection so this callback can be used arbitrarily. At that point we  can simplify the API by removing the need for Activate() / Deactivate()
540   //Activate();
541 }
542
543 void GaussianBlurView::Activate()
544 {
545   // make sure resources are allocated and start the render tasks processing
546   AllocateResources();
547   CreateRenderTasks();
548 }
549
550 void GaussianBlurView::ActivateOnce()
551 {
552   DALI_ASSERT_ALWAYS(mBlurUserImage); // Only works with blurring image mode.
553   mRenderOnce = true;
554   Activate();
555 }
556
557 void GaussianBlurView::Deactivate()
558 {
559   // stop render tasks processing
560   // Note: render target resources are automatically freed since we set the Image::Unused flag
561   RemoveRenderTasks();
562   mRenderOnce = false;
563 }
564
565 void GaussianBlurView::SetBlurBellCurveWidth(float blurBellCurveWidth)
566 {
567   // a value of zero leads to undefined Gaussian weights, do not allow user to do this
568   mBlurBellCurveWidth = std::max( blurBellCurveWidth, 0.001f );
569 }
570
571 float GaussianBlurView::CalcGaussianWeight(float x)
572 {
573   return (1.0f / sqrt(2.0f * Math::PI * mBlurBellCurveWidth)) * exp(-(x * x) / (2.0f * mBlurBellCurveWidth * mBlurBellCurveWidth));
574 }
575
576 void GaussianBlurView::SetShaderConstants()
577 {
578   Vector2 *uvOffsets;
579   float ofs;
580   float *weights;
581   float w, totalWeights;
582   unsigned int i;
583
584   uvOffsets = new Vector2[mNumSamples + 1];
585   weights = new float[mNumSamples + 1];
586
587   totalWeights = weights[0] = CalcGaussianWeight(0);
588   uvOffsets[0].x = 0.0f;
589   uvOffsets[0].y = 0.0f;
590
591   for(i=0; i<mNumSamples >> 1; i++)
592   {
593     w = CalcGaussianWeight((float)(i + 1));
594     weights[(i << 1) + 1] = w;
595     weights[(i << 1) + 2] = w;
596     totalWeights += w * 2.0f;
597
598     // offset texture lookup to between texels, that way the bilinear filter in the texture hardware will average two samples with one lookup
599     ofs = ((float)(i << 1)) + 1.5f;
600
601     // get offsets from units of pixels into uv coordinates in [0..1]
602     float ofsX = ofs / mDownsampledWidth;
603     float ofsY = ofs / mDownsampledHeight;
604     uvOffsets[(i << 1) + 1].x = ofsX;
605     uvOffsets[(i << 1) + 1].y = ofsY;
606
607     uvOffsets[(i << 1) + 2].x = -ofsX;
608     uvOffsets[(i << 1) + 2].y = -ofsY;
609   }
610
611   for(i=0; i<mNumSamples; i++)
612   {
613     weights[i] /= totalWeights;
614   }
615
616   // set shader constants
617   Vector2 xAxis(1.0f, 0.0f);
618   Vector2 yAxis(0.0f, 1.0f);
619   for (i = 0; i < mNumSamples; ++i )
620   {
621     mHorizBlurShader.SetUniform( GetSampleOffsetsPropertyName( i ), uvOffsets[ i ] * xAxis );
622     mHorizBlurShader.SetUniform( GetSampleWeightsPropertyName( i ), weights[ i ] );
623
624     mVertBlurShader.SetUniform( GetSampleOffsetsPropertyName( i ), uvOffsets[ i ] * yAxis );
625     mVertBlurShader.SetUniform( GetSampleWeightsPropertyName( i ), weights[ i ] );
626   }
627
628   delete[] uvOffsets;
629   delete[] weights;
630 }
631
632 std::string GaussianBlurView::GetSampleOffsetsPropertyName( unsigned int index ) const
633 {
634   DALI_ASSERT_ALWAYS( index < mNumSamples );
635
636   std::ostringstream oss;
637   oss << "uSampleOffsets[" << index << "]";
638   return oss.str();
639 }
640
641 std::string GaussianBlurView::GetSampleWeightsPropertyName( unsigned int index ) const
642 {
643   DALI_ASSERT_ALWAYS( index < mNumSamples );
644
645   std::ostringstream oss;
646   oss << "uSampleWeights[" << index << "]";
647   return oss.str();
648 }
649
650 Dali::Toolkit::GaussianBlurView::GaussianBlurViewSignal& GaussianBlurView::FinishedSignal()
651 {
652   return mFinishedSignal;
653 }
654
655 void GaussianBlurView::OnRenderTaskFinished(Dali::RenderTask& renderTask)
656 {
657   Toolkit::GaussianBlurView handle( GetOwner() );
658   mFinishedSignal.Emit( handle );
659 }
660
661 } // namespace Internal
662 } // namespace Toolkit
663 } // namespace Dali