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