[dali_1.1.40] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / super-blur-view / super-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 "super-blur-view-impl.h"
20
21 // EXTERNAL INCLUDES
22 #include <cmath>
23 #include <dali/public-api/animation/constraint.h>
24 #include <dali/public-api/common/stage.h>
25 #include <dali/public-api/object/type-registry.h>
26 #include <dali/public-api/object/property-map.h>
27 #include <dali/public-api/object/type-registry-helper.h>
28 #include <dali/devel-api/rendering/renderer.h>
29 #include <dali/devel-api/scripting/scripting.h>
30 #include <dali/integration-api/debug.h>
31
32 namespace //Unnamed namespace
33 {
34
35 using namespace Dali;
36
37 //Todo: make these properties instead of constants
38 const unsigned int GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES = 11;
39 const unsigned int GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION = 10;
40 const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH = 4.5f;
41 const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION = 5.f;
42 const Pixel::Format GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888;
43 const float GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE = 0.5f;
44 const float GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE = 0.5f;
45
46 const char* ALPHA_UNIFORM_NAME( "uAlpha" );
47 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
48   varying mediump vec2 vTexCoord;\n
49   uniform sampler2D sTexture;\n
50   uniform lowp vec4 uColor;\n
51   uniform lowp float uAlpha;\n
52   \n
53   void main()\n
54   {\n
55     gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
56     gl_FragColor.a *= uAlpha;
57   }\n
58 );
59
60 /**
61  * The constraint is used to blend the group of blurred images continuously with a unified blur strength property value which ranges from zero to one.
62  */
63 struct ActorOpacityConstraint
64 {
65   ActorOpacityConstraint(int totalImageNum, int currentImageIdx)
66   {
67     float rangeLength = 1.f / static_cast<float>( totalImageNum );
68     float index = static_cast<float>( currentImageIdx );
69     mRange = Vector2( index*rangeLength, (index+1.f)*rangeLength );
70   }
71
72   void operator()( float& current, const PropertyInputContainer& inputs )
73   {
74     float blurStrength = inputs[0]->GetFloat();
75     if(blurStrength < mRange.x)
76     {
77       current = 0.f;
78     }
79     else if(blurStrength > mRange.y)
80     {
81       current = 1.f;
82     }
83     else
84     {
85       current = ( blurStrength - mRange.x) / ( mRange.y - mRange.x );
86     }
87   }
88
89   Vector2 mRange;
90 };
91
92 } // namespace
93
94 namespace Dali
95 {
96
97 namespace Toolkit
98 {
99
100 namespace Internal
101 {
102
103 namespace
104 {
105
106 const unsigned int DEFAULT_BLUR_LEVEL(5u); ///< The default blur level when creating SuperBlurView from the type registry
107
108 BaseHandle Create()
109 {
110   return Toolkit::SuperBlurView::New( DEFAULT_BLUR_LEVEL );
111 }
112
113 // Setup properties, signals and actions using the type-registry.
114 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::SuperBlurView, Toolkit::Control, Create )
115
116 DALI_PROPERTY_REGISTRATION( Toolkit, SuperBlurView, "image", MAP, IMAGE )
117
118 DALI_TYPE_REGISTRATION_END()
119
120 } // unnamed namespace
121
122 SuperBlurView::SuperBlurView( unsigned int blurLevels )
123 : Control( ControlBehaviour( DISABLE_SIZE_NEGOTIATION ) ),
124   mTargetSize( Vector2::ZERO ),
125   mBlurStrengthPropertyIndex(Property::INVALID_INDEX),
126   mBlurLevels( blurLevels ),
127   mResourcesCleared( true )
128 {
129   DALI_ASSERT_ALWAYS( mBlurLevels > 0 && " Minimal blur level is one, otherwise no blur is needed" );
130   mGaussianBlurView.assign( blurLevels, Toolkit::GaussianBlurView() );
131   mBlurredImage.assign( blurLevels, FrameBufferImage() );
132   mRenderers.assign( blurLevels+1, Toolkit::ControlRenderer() );
133 }
134
135 SuperBlurView::~SuperBlurView()
136 {
137 }
138
139 Toolkit::SuperBlurView SuperBlurView::New( unsigned int blurLevels )
140 {
141   //Create the implementation
142   IntrusivePtr<SuperBlurView> superBlurView( new SuperBlurView( blurLevels ) );
143
144   //Pass ownership to CustomActor via derived handle
145   Toolkit::SuperBlurView handle( *superBlurView );
146
147   // Second-phase init of the implementation
148   // This can only be done after the CustomActor connection has been made...
149   superBlurView->Initialize();
150
151   return handle;
152 }
153
154 void SuperBlurView::OnInitialize()
155 {
156   mBlurStrengthPropertyIndex = Self().RegisterProperty( "blurStrength", 0.f );
157
158   Property::Map rendererMap;
159   rendererMap.Insert( "rendererType", "image");
160
161   Property::Map shaderMap;
162   std::stringstream verterShaderString;
163   shaderMap[ "fragmentShader" ] = FRAGMENT_SHADER;
164   rendererMap.Insert( "shader", shaderMap );
165
166   Toolkit::RendererFactory rendererFactory = Toolkit::RendererFactory::Get();
167   for(unsigned int i=0; i<=mBlurLevels; i++)
168   {
169     mRenderers[i] = rendererFactory.GetControlRenderer( rendererMap );
170     mRenderers[i].SetDepthIndex(i);
171   }
172 }
173
174 void SuperBlurView::SetImage(Image inputImage)
175 {
176   if( mTargetSize == Vector2::ZERO || mInputImage == inputImage)
177   {
178     return;
179   }
180
181   ClearBlurResource();
182
183   mInputImage = inputImage;
184   Actor self = Self();
185   Toolkit::RendererFactory::Get().ResetRenderer( mRenderers[0], self, mInputImage );
186
187   BlurImage( 0,  inputImage);
188   for(unsigned int i=1; i<mBlurLevels;i++)
189   {
190     BlurImage( i, mBlurredImage[i-1]);
191   }
192
193   mResourcesCleared = false;
194 }
195
196 Image SuperBlurView::GetImage()
197 {
198   return mInputImage;
199 }
200
201 Property::Index SuperBlurView::GetBlurStrengthPropertyIndex() const
202 {
203   return mBlurStrengthPropertyIndex;
204 }
205
206 void SuperBlurView::SetBlurStrength( float blurStrength )
207 {
208   Self().SetProperty(mBlurStrengthPropertyIndex, blurStrength);
209 }
210
211 float SuperBlurView::GetCurrentBlurStrength() const
212 {
213   float blurStrength;
214   (Self().GetProperty( mBlurStrengthPropertyIndex )).Get(blurStrength);
215
216   return blurStrength;
217 }
218
219 Toolkit::SuperBlurView::SuperBlurViewSignal& SuperBlurView::BlurFinishedSignal()
220 {
221   return mBlurFinishedSignal;
222 }
223
224 Image SuperBlurView::GetBlurredImage( unsigned int level )
225 {
226   DALI_ASSERT_ALWAYS( level>0 && level<=mBlurLevels );
227   return mBlurredImage[level-1];
228 }
229
230 void SuperBlurView::BlurImage( unsigned int idx, Image image )
231 {
232   DALI_ASSERT_ALWAYS( mGaussianBlurView.size()>idx );
233   mGaussianBlurView[idx] = Toolkit::GaussianBlurView::New( GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES+GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION*idx,
234                                                            GAUSSIAN_BLUR_BELL_CURVE_WIDTH + GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION*static_cast<float>(idx),
235                                                            GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT,
236                                                            GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE, GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE, true );
237   mGaussianBlurView[idx].SetParentOrigin(ParentOrigin::CENTER);
238   mGaussianBlurView[idx].SetSize(mTargetSize);
239   Stage::GetCurrent().Add( mGaussianBlurView[idx] );
240   mGaussianBlurView[idx].SetUserImageAndOutputRenderTarget( image, mBlurredImage[idx] );
241   mGaussianBlurView[idx].ActivateOnce();
242   if( idx == mBlurLevels-1 )
243   {
244     mGaussianBlurView[idx].FinishedSignal().Connect( this, &SuperBlurView::OnBlurViewFinished );
245   }
246 }
247
248 void SuperBlurView::OnBlurViewFinished( Toolkit::GaussianBlurView blurView )
249 {
250   ClearBlurResource();
251   Toolkit::SuperBlurView handle( GetOwner() );
252   mBlurFinishedSignal.Emit( handle );
253 }
254
255 void SuperBlurView::ClearBlurResource()
256 {
257   if( !mResourcesCleared )
258   {
259     DALI_ASSERT_ALWAYS( mGaussianBlurView.size() == mBlurLevels && "must synchronize the GaussianBlurView group if blur levels got changed " );
260     for(unsigned int i=0; i<mBlurLevels;i++)
261     {
262       Stage::GetCurrent().Remove( mGaussianBlurView[i] );
263       mGaussianBlurView[i].Deactivate();
264     }
265     mResourcesCleared = true;
266   }
267 }
268
269 void SuperBlurView::OnSizeSet( const Vector3& targetSize )
270 {
271   if( mTargetSize != Vector2(targetSize) )
272   {
273     mTargetSize = Vector2(targetSize);
274
275     Toolkit::RendererFactory rendererFactory = Toolkit::RendererFactory::Get();
276     Actor self = Self();
277     for(unsigned int i=1; i<=mBlurLevels;i++)
278     {
279       float exponent = static_cast<float>(i);
280       mBlurredImage[i-1] = FrameBufferImage::New( mTargetSize.width/std::pow(2.f,exponent) , mTargetSize.height/std::pow(2.f,exponent),
281                                                 GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT, Dali::Image::NEVER );
282       rendererFactory.ResetRenderer( mRenderers[i], self, mBlurredImage[i-1] );
283     }
284
285     if( mInputImage )
286     {
287       SetImage( mInputImage );
288     }
289
290     if( self.OnStage() )
291     {
292       for(unsigned int i=0; i<=mBlurLevels;i++)
293       {
294         mRenderers[i].SetOnStage( self );
295       }
296     }
297   }
298 }
299
300 void SuperBlurView::OnStageConnection( int depth )
301 {
302   Control::OnStageConnection( depth );
303
304   if( mTargetSize == Vector2::ZERO )
305   {
306     return;
307   }
308
309   Actor self = Self();
310   mRenderers[0].SetOnStage( self );
311   for(unsigned int i=1; i<=mBlurLevels;i++)
312   {
313     mRenderers[i].SetOnStage( self );
314
315     Renderer renderer = self.GetRendererAt( i );
316     Property::Index index = renderer.RegisterProperty( ALPHA_UNIFORM_NAME, 0.f );
317     Constraint constraint = Constraint::New<float>( renderer, index, ActorOpacityConstraint(mBlurLevels, i-1) );
318     constraint.AddSource( Source( self, mBlurStrengthPropertyIndex ) );
319     constraint.Apply();
320   }
321 }
322
323 void SuperBlurView::OnStageDisconnection( )
324 {
325   if( mTargetSize == Vector2::ZERO )
326   {
327     return;
328   }
329
330   Actor self = Self();
331   for(unsigned int i=0; i<mBlurLevels+1;i++)
332   {
333     mRenderers[i].SetOffStage( self );
334   }
335
336   Control::OnStageDisconnection();
337 }
338
339 Vector3 SuperBlurView::GetNaturalSize()
340 {
341   if( mInputImage )
342   {
343     return Vector3( mInputImage.GetWidth(), mInputImage.GetHeight(), 0.f );
344   }
345   return Vector3::ZERO;
346 }
347
348 void SuperBlurView::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value )
349 {
350   Toolkit::SuperBlurView superBlurView = Toolkit::SuperBlurView::DownCast( Dali::BaseHandle( object ) );
351
352   if( superBlurView )
353   {
354     SuperBlurView& superBlurViewImpl( GetImpl( superBlurView ) );
355
356     if( propertyIndex == Toolkit::SuperBlurView::Property::IMAGE )
357     {
358       Dali::Image image = Scripting::NewImage( value );
359       if ( image )
360       {
361         superBlurViewImpl.SetImage( image );
362       }
363       else
364       {
365         DALI_LOG_ERROR( "Cannot create image from property value\n" );
366       }
367     }
368   }
369 }
370
371 Property::Value SuperBlurView::GetProperty( BaseObject* object, Property::Index propertyIndex )
372 {
373   Property::Value value;
374
375   Toolkit::SuperBlurView blurView = Toolkit::SuperBlurView::DownCast( Dali::BaseHandle( object ) );
376
377   if( blurView )
378   {
379     SuperBlurView& superBlurViewImpl( GetImpl( blurView ) );
380
381     if( propertyIndex == Toolkit::SuperBlurView::Property::IMAGE )
382     {
383       Property::Map map;
384       Image inputImage = superBlurViewImpl.GetImage();
385       if( !inputImage )
386       {
387         Scripting::CreatePropertyMap( inputImage, map );
388       }
389       value = Property::Value( map );
390     }
391   }
392
393   return value;
394 }
395
396 } // namespace Internal
397
398 } // namespace Toolkit
399
400 } // namespace Dali