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