Merge "Use RegisterUniqueProperty for some more renderers" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / super-blur-view / super-blur-view-impl.cpp
index fa98392..ad90105 100644 (file)
@@ -1,41 +1,57 @@
-//
-// Copyright (c) 2014 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Flora License, Version 1.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://floralicense.org/license/
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an AS IS BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-//EXTERNAL INCLUDES
-#include <cmath>
+/*
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
 
 // CLASS HEADER
 #include "super-blur-view-impl.h"
 
-namespace //unnamed namespace
-{
+// EXTERNAL INCLUDES
+#include <dali/devel-api/common/stage.h>
+#include <dali/devel-api/scripting/scripting.h>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/animation/constraint.h>
+#include <dali/public-api/object/property-map.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/public-api/rendering/renderer.h>
+#include <cmath>
 
-using namespace Dali;
+// INTERNAL_INCLUDES
+#include <dali-toolkit/devel-api/controls/control-devel.h>
+#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/internal/controls/control/control-renderers.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/visuals/visual-base-impl.h>
+#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
+#include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
 
-//Type registration
-TypeRegistration mType( typeid(Toolkit::SuperBlurView), typeid(Toolkit::Control), NULL );
+namespace //Unnamed namespace
+{
+using namespace Dali;
 
 //Todo: make these properties instead of constants
-const unsigned int GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES = 11;
-const unsigned int GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION = 10;
-const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH = 4.5f;
-const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION = 5.f;
-const Pixel::Format GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGB888;
-const float GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE = 0.5f;
-const float GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE = 0.5f;
+const unsigned int  GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES             = 11;
+const unsigned int  GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION      = 10;
+const float         GAUSSIAN_BLUR_BELL_CURVE_WIDTH                = 4.5f;
+const float         GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION = 5.f;
+const Pixel::Format GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT      = Pixel::RGBA8888;
+const float         GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE          = 0.5f;
+const float         GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE         = 0.5f;
+
+const char* ALPHA_UNIFORM_NAME("uAlpha");
 
 /**
  * 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.
@@ -44,25 +60,25 @@ struct ActorOpacityConstraint
 {
   ActorOpacityConstraint(int totalImageNum, int currentImageIdx)
   {
-    float rangeLength = 1.f / static_cast<float>( totalImageNum );
-    float index = static_cast<float>( currentImageIdx );
-    mRange = Vector2( index*rangeLength, (index+1.f)*rangeLength );
+    float rangeLength = 1.f / static_cast<float>(totalImageNum);
+    float index       = static_cast<float>(currentImageIdx);
+    mRange            = Vector2(index * rangeLength, (index + 1.f) * rangeLength);
   }
 
-  float operator()( float current, const PropertyInput& blurProperty )
+  void operator()(float& current, const PropertyInputContainer& inputs)
   {
-    float blurStrength = blurProperty.GetFloat();
-    if(blurStrength <= mRange.x)
+    float blurStrength = inputs[0]->GetFloat();
+    if(blurStrength < mRange.x)
     {
-      return 1.f;
+      current = 0.f;
     }
     else if(blurStrength > mRange.y)
     {
-      return 0.f;
+      current = 1.f;
     }
     else
     {
-      return (mRange.y - blurStrength)/(mRange.y-mRange.x);
+      current = (blurStrength - mRange.x) / (mRange.y - mRange.x);
     }
   }
 
@@ -73,37 +89,52 @@ struct ActorOpacityConstraint
 
 namespace Dali
 {
-
 namespace Toolkit
 {
-
 namespace Internal
 {
+namespace
+{
+const unsigned int DEFAULT_BLUR_LEVEL(5u); ///< The default blur level when creating SuperBlurView from the type registry
 
-SuperBlurView::SuperBlurView( unsigned int blurLevels )
-: ControlImpl( false ),
-  mBlurLevels( blurLevels ),
+BaseHandle Create()
+{
+  return Toolkit::SuperBlurView::New(DEFAULT_BLUR_LEVEL);
+}
+
+// Setup properties, signals and actions using the type-registry.
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::SuperBlurView, Toolkit::Control, Create)
+
+DALI_PROPERTY_REGISTRATION(Toolkit, SuperBlurView, "imageUrl", STRING, IMAGE_URL)
+
+DALI_TYPE_REGISTRATION_END()
+
+} // unnamed namespace
+
+SuperBlurView::SuperBlurView(unsigned int blurLevels)
+: Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)),
+  mTargetSize(Vector2::ZERO),
   mBlurStrengthPropertyIndex(Property::INVALID_INDEX),
-  mResourcesCleared( true ),
-  mTargetSize( Vector2::ZERO )
+  mBlurLevels(blurLevels),
+  mResourcesCleared(true)
 {
-  DALI_ASSERT_ALWAYS( mBlurLevels > 0 && " Minimal blur level is one, otherwise no blur is needed" );
-  mGaussianBlurView.resize( blurLevels );
-  mBlurredImage.resize( blurLevels );
-  mImageActors.resize( blurLevels + 1 );
+  DALI_ASSERT_ALWAYS(mBlurLevels > 0 && " Minimal blur level is one, otherwise no blur is needed");
+  mGaussianBlurView.assign(blurLevels, Toolkit::GaussianBlurView());
+  mBlurredImage.assign(blurLevels, FrameBuffer());
+  mRenderers.assign(blurLevels + 1, Dali::Renderer());
 }
 
 SuperBlurView::~SuperBlurView()
 {
 }
 
-Toolkit::SuperBlurView SuperBlurView::New( unsigned int blurLevels )
+Toolkit::SuperBlurView SuperBlurView::New(unsigned int blurLevels)
 {
   //Create the implementation
-  IntrusivePtr<SuperBlurView> superBlurView( new SuperBlurView( blurLevels ) );
+  IntrusivePtr<SuperBlurView> superBlurView(new SuperBlurView(blurLevels));
 
   //Pass ownership to CustomActor via derived handle
-  Toolkit::SuperBlurView handle( *superBlurView );
+  Toolkit::SuperBlurView handle(*superBlurView);
 
   // Second-phase init of the implementation
   // This can only be done after the CustomActor connection has been made...
@@ -114,46 +145,41 @@ Toolkit::SuperBlurView SuperBlurView::New( unsigned int blurLevels )
 
 void SuperBlurView::OnInitialize()
 {
-  mBlurStrengthPropertyIndex = Self().RegisterProperty( "BLUR_STRENGTH",0.f );
+  Actor self(Self());
 
-  DALI_ASSERT_ALWAYS( mImageActors.size() == mBlurLevels+1 && "must synchronize the ImageActor group if blur levels got changed " );
-  for(unsigned int i=0; i<=mBlurLevels;i++)
-  {
-    mImageActors[i] = ImageActor::New(  );
-    mImageActors[i].SetParentOrigin( ParentOrigin::CENTER );
-    mImageActors[i].SetZ(-static_cast<float>(i)*0.01f);
-    mImageActors[i].SetColorMode( USE_OWN_MULTIPLY_PARENT_ALPHA );
-    Self().Add( mImageActors[i] );
-  }
-
-  for(unsigned int i=0; i < mBlurLevels; i++)
-  {
-    mImageActors[i].ApplyConstraint( Constraint::New<float>( Actor::COLOR_ALPHA, ParentSource( mBlurStrengthPropertyIndex ), ActorOpacityConstraint(mBlurLevels, i) ) );
-  }
+  mBlurStrengthPropertyIndex = self.RegisterUniqueProperty("blurStrength", 0.f);
 
-  Self().SetSize(Stage::GetCurrent().GetSize());
+  DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
+    return std::unique_ptr<Dali::Accessibility::Accessible>(
+      new DevelControl::ControlAccessible(actor, Dali::Accessibility::Role::FILLER));
+  });
 }
 
-void SuperBlurView::SetImage(Image inputImage)
+void SuperBlurView::SetTexture(Texture texture)
 {
-  DALI_ASSERT_ALWAYS( mImageActors.size() == mBlurLevels+1 && "must synchronize the ImageActor group if blur levels got changed " );
-  DALI_ASSERT_ALWAYS( mBlurredImage.size() == mBlurLevels && "must synchronize the blurred image group if blur levels got changed " );
+  mInputTexture = texture;
+
+  if(mTargetSize == Vector2::ZERO)
+  {
+    return;
+  }
 
   ClearBlurResource();
 
-  mImageActors[0].SetImage( inputImage );
+  Actor self(Self());
 
-  for(unsigned int i=1; i<=mBlurLevels;i++)
-  {
-    mImageActors[i].SetImage( mBlurredImage[i-1] );
-  }
+  BlurTexture(0, mInputTexture);
+  SetRendererTexture(mRenderers[0], texture);
 
-  BlurImage( 0,  inputImage);
-  for(unsigned int i=1; i<mBlurLevels;i++)
+  unsigned int i = 1;
+  for(; i < mBlurLevels; i++)
   {
-    BlurImage( i,  mBlurredImage[i-1]);
+    BlurTexture(i, mBlurredImage[i - 1].GetColorTexture());
+    SetRendererTexture(mRenderers[i], mBlurredImage[i - 1]);
   }
 
+  SetRendererTexture(mRenderers[i], mBlurredImage[i - 1]);
+
   mResourcesCleared = false;
 }
 
@@ -162,7 +188,7 @@ Property::Index SuperBlurView::GetBlurStrengthPropertyIndex() const
   return mBlurStrengthPropertyIndex;
 }
 
-void SuperBlurView::SetBlurStrength( float blurStrength )
+void SuperBlurView::SetBlurStrength(float blurStrength)
 {
   Self().SetProperty(mBlurStrengthPropertyIndex, blurStrength);
 }
@@ -170,7 +196,7 @@ void SuperBlurView::SetBlurStrength( float blurStrength )
 float SuperBlurView::GetCurrentBlurStrength() const
 {
   float blurStrength;
-  (Self().GetProperty( mBlurStrengthPropertyIndex )).Get(blurStrength);
+  (Self().GetProperty(mBlurStrengthPropertyIndex)).Get(blurStrength);
 
   return blurStrength;
 }
@@ -180,75 +206,192 @@ Toolkit::SuperBlurView::SuperBlurViewSignal& SuperBlurView::BlurFinishedSignal()
   return mBlurFinishedSignal;
 }
 
-Image SuperBlurView::GetBlurredImage( unsigned int level )
+Texture SuperBlurView::GetBlurredTexture(unsigned int level)
 {
-  DALI_ASSERT_ALWAYS( level>0 && level<=mBlurLevels );
-  return mBlurredImage[level-1];
+  DALI_ASSERT_ALWAYS(level > 0 && level <= mBlurLevels);
+
+  FrameBuffer frameBuffer = mBlurredImage[level - 1];
+
+  return frameBuffer.GetColorTexture();
 }
 
-void SuperBlurView::BlurImage( unsigned int idx, Image image )
+void SuperBlurView::BlurTexture(unsigned int idx, Texture texture)
 {
-  DALI_ASSERT_ALWAYS( mGaussianBlurView.size()>idx );
-  mGaussianBlurView[idx] = Toolkit::GaussianBlurView::New( GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES+GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION*idx,
-                                                           GAUSSIAN_BLUR_BELL_CURVE_WIDTH + GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION*static_cast<float>(idx),
-                                                           GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT,
-                                                           GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE, GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE, true );
-  mGaussianBlurView[idx].SetParentOrigin(ParentOrigin::CENTER);
-  mGaussianBlurView[idx].SetSize(mTargetSize);
-  mGaussianBlurView[idx].SetUserImageAndOutputRenderTarget( image, mBlurredImage[idx] );
-  if( idx == mBlurLevels-1 )
+  DALI_ASSERT_ALWAYS(mGaussianBlurView.size() > idx);
+  mGaussianBlurView[idx] = Toolkit::GaussianBlurView::New(GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES + GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION * idx,
+                                                          GAUSSIAN_BLUR_BELL_CURVE_WIDTH + GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION * static_cast<float>(idx),
+                                                          GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT,
+                                                          GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE,
+                                                          GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE,
+                                                          true);
+  mGaussianBlurView[idx].SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+  mGaussianBlurView[idx].SetProperty(Actor::Property::SIZE, mTargetSize);
+  Stage::GetCurrent().Add(mGaussianBlurView[idx]);
+
+  mGaussianBlurView[idx].SetUserImageAndOutputRenderTarget(texture, mBlurredImage[idx]);
+
+  mGaussianBlurView[idx].ActivateOnce();
+  if(idx == mBlurLevels - 1)
   {
-    mGaussianBlurView[idx].FinishedSignal().Connect( this, &SuperBlurView::OnBlurViewFinished );
+    mGaussianBlurView[idx].FinishedSignal().Connect(this, &SuperBlurView::OnBlurViewFinished);
   }
-  Stage::GetCurrent().Add( mGaussianBlurView[idx] );
-  mGaussianBlurView[idx].ActivateOnce();
 }
 
-void SuperBlurView::OnBlurViewFinished( Toolkit::GaussianBlurView blurView )
+void SuperBlurView::OnBlurViewFinished(Toolkit::GaussianBlurView blurView)
 {
   ClearBlurResource();
-  Toolkit::SuperBlurView handle( GetOwner() );
-  mBlurFinishedSignal.Emit( handle );
+  Toolkit::SuperBlurView handle(GetOwner());
+  mBlurFinishedSignal.Emit(handle);
 }
 
 void SuperBlurView::ClearBlurResource()
 {
-  if( !mResourcesCleared )
+  if(!mResourcesCleared)
   {
-    DALI_ASSERT_ALWAYS( mGaussianBlurView.size() == mBlurLevels && "must synchronize the GaussianBlurView group if blur levels got changed " );
-    for(unsigned int i=0; i<mBlurLevels;i++)
+    DALI_ASSERT_ALWAYS(mGaussianBlurView.size() == mBlurLevels && "must synchronize the GaussianBlurView group if blur levels got changed ");
+    for(unsigned int i = 0; i < mBlurLevels; i++)
     {
-      Stage::GetCurrent().Remove( mGaussianBlurView[i] );
+      Stage::GetCurrent().Remove(mGaussianBlurView[i]);
       mGaussianBlurView[i].Deactivate();
-      mGaussianBlurView[i].Reset();
     }
     mResourcesCleared = true;
   }
 }
 
-void SuperBlurView::OnRelaidOut( Vector2 size, ActorSizeContainer& container )
+void SuperBlurView::OnSizeSet(const Vector3& targetSize)
+{
+  if(mTargetSize != Vector2(targetSize))
+  {
+    mTargetSize = Vector2(targetSize);
+
+    Actor self = Self();
+    for(unsigned int i = 1; i <= mBlurLevels; i++)
+    {
+      float exponent = static_cast<float>(i);
+
+      unsigned int width  = mTargetSize.width / std::pow(2.f, exponent);
+      unsigned int height = mTargetSize.height / std::pow(2.f, exponent);
+
+      mBlurredImage[i - 1] = FrameBuffer::New(width, height, FrameBuffer::Attachment::NONE);
+      Texture texture      = Texture::New(TextureType::TEXTURE_2D, GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT, unsigned(width), unsigned(height));
+      mBlurredImage[i - 1].AttachColorTexture(texture);
+    }
+
+    if(mInputTexture)
+    {
+      SetTexture(mInputTexture);
+    }
+  }
+
+  Control::OnSizeSet(targetSize);
+}
+
+void SuperBlurView::OnSceneConnection(int depth)
 {
-  unsigned int numChildren = Self().GetChildCount();
+  if(mTargetSize == Vector2::ZERO)
+  {
+    return;
+  }
+
+  // Exception to the rule, chaining up first ensures visuals have SetOnScene called to create their renderers
+  Control::OnSceneConnection(depth);
+
+  Actor self = Self();
+
+  for(unsigned int i = 0; i < mBlurLevels + 1; i++)
+  {
+    mRenderers[i] = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_SUPER_BLUR_VIEW_FRAG);
+    mRenderers[i].SetProperty(Dali::Renderer::Property::DEPTH_INDEX, (int)i);
+    self.AddRenderer(mRenderers[i]);
 
-  for( unsigned int i=0; i<numChildren; ++i )
+    if(i > 0)
+    {
+      Renderer        renderer   = mRenderers[i];
+      Property::Index index      = renderer.RegisterUniqueProperty(ALPHA_UNIFORM_NAME, 0.f);
+      Constraint      constraint = Constraint::New<float>(renderer, index, ActorOpacityConstraint(mBlurLevels, i - 1));
+      constraint.AddSource(Source(self, mBlurStrengthPropertyIndex));
+      constraint.Apply();
+    }
+  }
+
+  if(mInputTexture)
   {
-    Self().GetChildAt(i).SetSize(size);
+    SetRendererTexture(mRenderers[0], mInputTexture);
+    unsigned int i = 1;
+    for(; i < mBlurLevels; i++)
+    {
+      SetRendererTexture(mRenderers[i], mBlurredImage[i - 1]);
+    }
+    SetRendererTexture(mRenderers[i], mBlurredImage[i - 1]);
   }
 }
 
-void SuperBlurView::OnControlSizeSet( const Vector3& targetSize )
+void SuperBlurView::OnSceneDisconnection()
 {
-  if( mTargetSize != Vector2(targetSize) )
+  for(unsigned int i = 0; i < mBlurLevels + 1; i++)
   {
-    mTargetSize = Vector2(targetSize);
+    Self().RemoveRenderer(mRenderers[i]);
+    mRenderers[i].Reset();
+  }
+
+  Control::OnSceneDisconnection();
+}
+
+Vector3 SuperBlurView::GetNaturalSize()
+{
+  if(mInputTexture)
+  {
+    return Vector3(mInputTexture.GetWidth(), mInputTexture.GetHeight(), 0.f);
+  }
+  return Vector3::ZERO;
+}
+
+void SuperBlurView::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value)
+{
+  Toolkit::SuperBlurView superBlurView = Toolkit::SuperBlurView::DownCast(Dali::BaseHandle(object));
+
+  if(superBlurView)
+  {
+    SuperBlurView& superBlurViewImpl(GetImpl(superBlurView));
+
+    if(propertyIndex == Toolkit::SuperBlurView::Property::IMAGE_URL)
+    {
+      value.Get(superBlurViewImpl.mUrl);
+
+      PixelData pixels = SyncImageLoader::Load(superBlurViewImpl.mUrl);
 
-    for(unsigned int i=0; i<mBlurLevels;i++)
+      if(pixels)
+      {
+        Texture texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight());
+        texture.Upload(pixels, 0, 0, 0, 0, pixels.GetWidth(), pixels.GetHeight());
+
+        superBlurViewImpl.SetTexture(texture);
+      }
+      else
+      {
+        DALI_LOG_ERROR("Cannot create image from property value\n");
+      }
+    }
+  }
+}
+
+Property::Value SuperBlurView::GetProperty(BaseObject* object, Property::Index propertyIndex)
+{
+  Property::Value value;
+
+  Toolkit::SuperBlurView blurView = Toolkit::SuperBlurView::DownCast(Dali::BaseHandle(object));
+
+  if(blurView)
+  {
+    SuperBlurView& superBlurViewImpl(GetImpl(blurView));
+
+    if(propertyIndex == Toolkit::SuperBlurView::Property::IMAGE_URL)
     {
-      float exponent = static_cast<float>(i+1);
-      mBlurredImage[i] = FrameBufferImage::New( mTargetSize.width/std::pow(2.f,exponent) , mTargetSize.height/std::pow(2.f,exponent),
-                                                GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT, Dali::Image::Never );
+      value = superBlurViewImpl.mUrl;
     }
   }
+
+  return value;
 }
 
 } // namespace Internal