Merge "Shader compilation tool for dali-toolkit" 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) 2020 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/devel-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/public-api/image-loader/sync-image-loader.h>
34 #include <dali-toolkit/devel-api/controls/control-devel.h>
35 #include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
36 #include <dali-toolkit/internal/controls/control/control-renderers.h>
37 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
38 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
39 #include <dali-toolkit/internal/controls/control/control-data-impl.h>
40
41 namespace //Unnamed namespace
42 {
43
44 using namespace Dali;
45
46 //Todo: make these properties instead of constants
47 const unsigned int GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES = 11;
48 const unsigned int GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION = 10;
49 const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH = 4.5f;
50 const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION = 5.f;
51 const Pixel::Format GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888;
52 const float GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE = 0.5f;
53 const float GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE = 0.5f;
54
55 const char* ALPHA_UNIFORM_NAME( "uAlpha" );
56
57 /**
58  * 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.
59  */
60 struct ActorOpacityConstraint
61 {
62   ActorOpacityConstraint(int totalImageNum, int currentImageIdx)
63   {
64     float rangeLength = 1.f / static_cast<float>( totalImageNum );
65     float index = static_cast<float>( currentImageIdx );
66     mRange = Vector2( index*rangeLength, (index+1.f)*rangeLength );
67   }
68
69   void operator()( float& current, const PropertyInputContainer& inputs )
70   {
71     float blurStrength = inputs[0]->GetFloat();
72     if(blurStrength < mRange.x)
73     {
74       current = 0.f;
75     }
76     else if(blurStrength > mRange.y)
77     {
78       current = 1.f;
79     }
80     else
81     {
82       current = ( blurStrength - mRange.x) / ( mRange.y - mRange.x );
83     }
84   }
85
86   Vector2 mRange;
87 };
88
89 } // namespace
90
91 namespace Dali
92 {
93
94 namespace Toolkit
95 {
96
97 namespace Internal
98 {
99
100 namespace
101 {
102
103 const unsigned int DEFAULT_BLUR_LEVEL(5u); ///< The default blur level when creating SuperBlurView from the type registry
104
105 BaseHandle Create()
106 {
107   return Toolkit::SuperBlurView::New( DEFAULT_BLUR_LEVEL );
108 }
109
110 // Setup properties, signals and actions using the type-registry.
111 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::SuperBlurView, Toolkit::Control, Create )
112
113 DALI_PROPERTY_REGISTRATION( Toolkit, SuperBlurView, "imageUrl", STRING, IMAGE_URL )
114
115 DALI_TYPE_REGISTRATION_END()
116
117 } // unnamed namespace
118
119 SuperBlurView::SuperBlurView( unsigned int blurLevels )
120 : Control( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS ) ),
121   mTargetSize( Vector2::ZERO ),
122   mBlurStrengthPropertyIndex(Property::INVALID_INDEX),
123   mBlurLevels( blurLevels ),
124   mResourcesCleared( true )
125 {
126   DALI_ASSERT_ALWAYS( mBlurLevels > 0 && " Minimal blur level is one, otherwise no blur is needed" );
127   mGaussianBlurView.assign( blurLevels, Toolkit::GaussianBlurView() );
128   mBlurredImage.assign( blurLevels, FrameBuffer() );
129   mRenderers.assign( blurLevels+1, Dali::Renderer() );
130 }
131
132 SuperBlurView::~SuperBlurView()
133 {
134 }
135
136 Toolkit::SuperBlurView SuperBlurView::New( unsigned int blurLevels )
137 {
138   //Create the implementation
139   IntrusivePtr<SuperBlurView> superBlurView( new SuperBlurView( blurLevels ) );
140
141   //Pass ownership to CustomActor via derived handle
142   Toolkit::SuperBlurView handle( *superBlurView );
143
144   // Second-phase init of the implementation
145   // This can only be done after the CustomActor connection has been made...
146   superBlurView->Initialize();
147
148   return handle;
149 }
150
151 void SuperBlurView::OnInitialize()
152 {
153   Actor self( Self() );
154
155   mBlurStrengthPropertyIndex = self.RegisterProperty( "blurStrength", 0.f );
156
157   DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) {
158     return std::unique_ptr< Dali::Accessibility::Accessible >(
159       new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) );
160   } );
161 }
162
163 void SuperBlurView::SetTexture( Texture texture )
164 {
165   mInputTexture = texture;
166
167   if( mTargetSize == Vector2::ZERO )
168   {
169     return;
170   }
171
172   ClearBlurResource();
173
174   Actor self( Self() );
175
176   BlurTexture( 0, mInputTexture );
177   SetRendererTexture( mRenderers[0], texture );
178
179   unsigned int i = 1;
180   for(; i<mBlurLevels; i++)
181   {
182     BlurTexture( i, mBlurredImage[i-1].GetColorTexture() );
183     SetRendererTexture( mRenderers[i], mBlurredImage[i-1] );
184   }
185
186   SetRendererTexture( mRenderers[i], mBlurredImage[i-1] );
187
188   mResourcesCleared = false;
189 }
190
191 Property::Index SuperBlurView::GetBlurStrengthPropertyIndex() const
192 {
193   return mBlurStrengthPropertyIndex;
194 }
195
196 void SuperBlurView::SetBlurStrength( float blurStrength )
197 {
198   Self().SetProperty(mBlurStrengthPropertyIndex, blurStrength);
199 }
200
201 float SuperBlurView::GetCurrentBlurStrength() const
202 {
203   float blurStrength;
204   (Self().GetProperty( mBlurStrengthPropertyIndex )).Get(blurStrength);
205
206   return blurStrength;
207 }
208
209 Toolkit::SuperBlurView::SuperBlurViewSignal& SuperBlurView::BlurFinishedSignal()
210 {
211   return mBlurFinishedSignal;
212 }
213
214 Texture SuperBlurView::GetBlurredTexture( unsigned int level )
215 {
216   DALI_ASSERT_ALWAYS( level>0 && level<=mBlurLevels );
217
218   FrameBuffer frameBuffer = mBlurredImage[level-1];
219
220   return frameBuffer.GetColorTexture();
221 }
222
223 void SuperBlurView::BlurTexture( unsigned int idx, Texture texture )
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].SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
231   mGaussianBlurView[idx].SetProperty( Actor::Property::SIZE, mTargetSize );
232   Stage::GetCurrent().Add( mGaussianBlurView[idx] );
233
234   mGaussianBlurView[idx].SetUserImageAndOutputRenderTarget( texture, mBlurredImage[idx] );
235
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
264 void SuperBlurView::OnSizeSet( const Vector3& targetSize )
265 {
266   if( mTargetSize != Vector2(targetSize) )
267   {
268     mTargetSize = Vector2(targetSize);
269
270     Actor self = Self();
271     for( unsigned int i = 1; i <= mBlurLevels; i++ )
272     {
273       float exponent = static_cast<float>(i);
274
275       unsigned int width = mTargetSize.width/std::pow(2.f,exponent);
276       unsigned int height = mTargetSize.height/std::pow(2.f,exponent);
277
278       mBlurredImage[i-1] = FrameBuffer::New( width, height, FrameBuffer::Attachment::NONE );
279       Texture texture = Texture::New( TextureType::TEXTURE_2D, GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT, unsigned(width), unsigned(height) );
280       mBlurredImage[i-1].AttachColorTexture( texture );
281     }
282
283     if( mInputTexture )
284     {
285       SetTexture( mInputTexture );
286     }
287   }
288
289   Control::OnSizeSet( targetSize );
290 }
291
292 void SuperBlurView::OnSceneConnection( int depth )
293 {
294   if( mTargetSize == Vector2::ZERO )
295   {
296     return;
297   }
298
299   // Exception to the rule, chaining up first ensures visuals have SetOnScene called to create their renderers
300   Control::OnSceneConnection( depth );
301
302   Actor self = Self();
303
304   for(unsigned int i=0; i<mBlurLevels+1;i++)
305   {
306     mRenderers[i] = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_SUPER_BLUR_VIEW_FRAG );
307     mRenderers[i].SetProperty( Dali::Renderer::Property::DEPTH_INDEX, (int)i );
308     self.AddRenderer( mRenderers[i] );
309
310     if( i > 0 )
311     {
312       Renderer renderer = mRenderers[i];
313       Property::Index index = renderer.RegisterProperty( ALPHA_UNIFORM_NAME, 0.f );
314       Constraint constraint = Constraint::New<float>( renderer, index, ActorOpacityConstraint(mBlurLevels, i-1) );
315       constraint.AddSource( Source( self, mBlurStrengthPropertyIndex ) );
316       constraint.Apply();
317     }
318   }
319
320   if( mInputTexture )
321   {
322     SetRendererTexture( mRenderers[0], mInputTexture );
323     unsigned int i = 1;
324     for(; i<mBlurLevels; i++)
325     {
326       SetRendererTexture( mRenderers[i], mBlurredImage[i-1] );
327     }
328     SetRendererTexture( mRenderers[i], mBlurredImage[i-1] );
329   }
330 }
331
332 void SuperBlurView::OnSceneDisconnection()
333 {
334   for(unsigned int i=0; i<mBlurLevels+1;i++)
335   {
336     Self().RemoveRenderer( mRenderers[i] );
337     mRenderers[i].Reset();
338   }
339
340   Control::OnSceneDisconnection();
341 }
342
343 Vector3 SuperBlurView::GetNaturalSize()
344 {
345   if( mInputTexture )
346   {
347     return Vector3( mInputTexture.GetWidth(), mInputTexture.GetHeight(), 0.f );
348   }
349   return Vector3::ZERO;
350 }
351
352 void SuperBlurView::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value )
353 {
354   Toolkit::SuperBlurView superBlurView = Toolkit::SuperBlurView::DownCast( Dali::BaseHandle( object ) );
355
356   if( superBlurView )
357   {
358     SuperBlurView& superBlurViewImpl( GetImpl( superBlurView ) );
359
360     if( propertyIndex == Toolkit::SuperBlurView::Property::IMAGE_URL )
361     {
362       value.Get( superBlurViewImpl.mUrl );
363
364       PixelData pixels = SyncImageLoader::Load( superBlurViewImpl.mUrl );
365
366       if ( pixels )
367       {
368         Texture texture = Texture::New( TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight() );
369         texture.Upload( pixels, 0, 0, 0, 0, pixels.GetWidth(), pixels.GetHeight() );
370
371         superBlurViewImpl.SetTexture( texture );
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_URL )
392     {
393       value = superBlurViewImpl.mUrl;
394     }
395   }
396
397   return value;
398 }
399
400 } // namespace Internal
401
402 } // namespace Toolkit
403
404 } // namespace Dali