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