Fix the text visual shaders to work with pre-multiplied alpha
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / visual-base-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 "visual-base-impl.h"
20
21 // EXTERNAL HEADER
22 #include <dali/public-api/common/dali-common.h>
23 #include <dali/devel-api/object/handle-devel.h>
24 #include <dali/integration-api/debug.h>
25
26 //INTERNAL HEARDER
27 #include <dali-toolkit/public-api/visuals/color-visual-properties.h>
28 #include <dali-toolkit/public-api/visuals/primitive-visual-properties.h>
29 #include <dali-toolkit/public-api/visuals/visual-properties.h>
30 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
31 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
32
33 namespace
34 {
35 #if defined(DEBUG_ENABLED)
36 Debug::Filter* gVisualBaseLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VISUAL_BASE" );
37 #endif
38
39 const char * const PRE_MULTIPLIED_ALPHA_PROPERTY( "preMultipliedAlpha" );
40 }
41
42 namespace Dali
43 {
44
45 namespace Toolkit
46 {
47
48 namespace Internal
49 {
50
51 Visual::Base::Base( VisualFactoryCache& factoryCache )
52 : mImpl( new Impl() ),
53   mFactoryCache( factoryCache )
54 {
55 }
56
57 Visual::Base::~Base()
58 {
59   delete mImpl;
60 }
61
62 void Visual::Base::SetCustomShader( const Property::Map& shaderMap )
63 {
64   if( mImpl->mCustomShader )
65   {
66     mImpl->mCustomShader->SetPropertyMap( shaderMap );
67   }
68   else
69   {
70     mImpl->mCustomShader = new Impl::CustomShader( shaderMap );
71   }
72 }
73
74 void Visual::Base::SetProperties( const Property::Map& propertyMap )
75 {
76   for( size_t i = 0; i < propertyMap.Count(); ++i )
77   {
78     const KeyValuePair& pair = propertyMap.GetKeyValue( i );
79     const Property::Key& key = pair.first;
80     const Property::Value& value = pair.second;
81
82     Property::Key matchKey = key;
83     if( matchKey.type == Property::Key::STRING )
84     {
85       if( matchKey == CUSTOM_SHADER )
86       {
87         matchKey = Property::Key( Toolkit::Visual::Property::SHADER );
88       }
89       else if( matchKey == TRANSFORM )
90       {
91         matchKey = Property::Key( Toolkit::Visual::Property::TRANSFORM );
92       }
93       else if( matchKey == PREMULTIPLIED_ALPHA )
94       {
95         matchKey = Property::Key( Toolkit::Visual::Property::PREMULTIPLIED_ALPHA );
96       }
97       else if( matchKey == MIX_COLOR )
98       {
99         matchKey = Property::Key( Toolkit::Visual::Property::MIX_COLOR );
100       }
101       else if( matchKey == OPACITY )
102       {
103         matchKey = Property::Key( Toolkit::Visual::Property::OPACITY );
104       }
105     }
106
107     switch( matchKey.indexKey )
108     {
109       case Toolkit::Visual::Property::SHADER:
110       {
111         Property::Map shaderMap;
112         if( value.Get( shaderMap ) )
113         {
114           SetCustomShader( shaderMap );
115         }
116         break;
117       }
118
119       case Toolkit::Visual::Property::TRANSFORM:
120       {
121         Property::Map map;
122         if( value.Get( map ) )
123         {
124           mImpl->mTransform.SetPropertyMap( map );
125         }
126         break;
127       }
128
129       case Toolkit::Visual::Property::PREMULTIPLIED_ALPHA:
130       {
131         bool premultipliedAlpha = false;
132         if( value.Get( premultipliedAlpha ) )
133         {
134           EnablePreMultipliedAlpha( premultipliedAlpha );
135         }
136         break;
137       }
138
139       case Toolkit::Visual::Property::MIX_COLOR:
140       {
141         Vector4 mixColor;
142         if( value.Get( mixColor ) )
143         {
144           if( value.GetType() == Property::VECTOR4 )
145           {
146             SetMixColor( mixColor );
147           }
148           else
149           {
150             Vector3 mixColor3(mixColor);
151             SetMixColor( mixColor3 );
152           }
153         }
154         break;
155       }
156       case Toolkit::Visual::Property::OPACITY:
157       {
158         float opacity;
159         if( value.Get( opacity ) )
160         {
161           mImpl->mMixColor.a = opacity;
162           SetMixColor( mImpl->mMixColor );
163         }
164         break;
165       }
166     }
167   }
168
169   DoSetProperties( propertyMap );
170 }
171
172 void Visual::Base::SetTransformAndSize( const Property::Map& transform, Size controlSize )
173 {
174   mImpl->mControlSize = controlSize;
175   mImpl->mTransform.UpdatePropertyMap( transform );
176
177 #if defined(DEBUG_ENABLED)
178   std::ostringstream oss;
179   oss << transform;
180   DALI_LOG_INFO( gVisualBaseLogFilter, Debug::General, "Visual::Base::SetTransformAndSize(%s) - [\e[1;32mtransform: %s  controlSize: (%3.1f, %3.1f)]\e[0m\n",
181                  GetName().c_str(), oss.str().c_str(), controlSize.x, controlSize.y );
182 #endif
183
184   OnSetTransform();
185 }
186
187 void Visual::Base::SetName( const std::string& name )
188 {
189   mImpl->mName = name;
190 }
191
192 const std::string& Visual::Base::GetName()
193 {
194   return mImpl->mName;
195 }
196
197 float Visual::Base::GetHeightForWidth( float width )
198 {
199   float aspectCorrectedHeight = 0.f;
200   Vector2 naturalSize;
201   GetNaturalSize( naturalSize );
202   if( naturalSize.width )
203   {
204     aspectCorrectedHeight = naturalSize.height * width / naturalSize.width;
205   }
206   return aspectCorrectedHeight;
207 }
208
209 float Visual::Base::GetWidthForHeight( float height )
210 {
211   float aspectCorrectedWidth = 0.f;
212   Vector2 naturalSize;
213   GetNaturalSize( naturalSize );
214   if( naturalSize.height > 0.0f )
215   {
216     aspectCorrectedWidth = naturalSize.width * height / naturalSize.height;
217   }
218   return aspectCorrectedWidth;
219 }
220
221 void Visual::Base::GetNaturalSize( Vector2& naturalSize )
222 {
223   naturalSize = Vector2::ZERO;
224 }
225
226 void Visual::Base::SetDepthIndex( int index )
227 {
228   mImpl->mDepthIndex = index;
229   if( mImpl->mRenderer )
230   {
231     mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_INDEX, mImpl->mDepthIndex );
232   }
233 }
234
235 int Visual::Base::GetDepthIndex() const
236 {
237   return mImpl->mDepthIndex;
238 }
239
240 void Visual::Base::SetOnStage( Actor& actor )
241 {
242   if( !IsOnStage() )
243   {
244     // To display the actor correctly, renderer should not be added to actor until all required resources are ready.
245     // Thus the calling of actor.AddRenderer() should happen inside derived class as base class does not know the exact timing.
246     DoSetOnStage( actor );
247
248     if( mImpl->mRenderer )
249     {
250       RegisterMixColor();
251
252       mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, IsPreMultipliedAlphaEnabled());
253       mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_INDEX, mImpl->mDepthIndex );
254       mImpl->mFlags |= Impl::IS_ON_STAGE; // Only sets the flag if renderer exists
255     }
256   }
257 }
258
259 void Visual::Base::SetOffStage( Actor& actor )
260 {
261   if( IsOnStage() )
262   {
263     DoSetOffStage( actor );
264     mImpl->mMixColorIndex = Property::INVALID_INDEX;
265     mImpl->mOpacityIndex = Property::INVALID_INDEX;
266     mImpl->mFlags &= ~Impl::IS_ON_STAGE;
267   }
268 }
269
270 void Visual::Base::CreatePropertyMap( Property::Map& map ) const
271 {
272   DoCreatePropertyMap( map );
273
274   if( mImpl->mCustomShader )
275   {
276     mImpl->mCustomShader->CreatePropertyMap( map );
277   }
278
279   Property::Map transform;
280   mImpl->mTransform.GetPropertyMap( transform );
281   map.Insert( Toolkit::Visual::Property::TRANSFORM, transform );
282
283   bool premultipliedAlpha( IsPreMultipliedAlphaEnabled() );
284   map.Insert( Toolkit::Visual::Property::PREMULTIPLIED_ALPHA, premultipliedAlpha );
285
286   // Note, Color and Primitive will also insert their own mix color into the map
287   // which is ok, because they have a different key value range.
288   map.Insert( Toolkit::Visual::Property::MIX_COLOR, mImpl->mMixColor ); // vec4
289   map.Insert( Toolkit::Visual::Property::OPACITY, mImpl->mMixColor.a );
290 }
291
292 void Visual::Base::CreateInstancePropertyMap( Property::Map& map ) const
293 {
294   DoCreateInstancePropertyMap( map );
295
296   if( mImpl->mCustomShader )
297   {
298     mImpl->mCustomShader->CreatePropertyMap( map );
299   }
300
301   //map.Insert( Toolkit::Visual::Property::DEPTH_INDEX, mImpl->mDepthIndex );
302   //map.Insert( Toolkit::Visual::Property::ENABLED, (bool) mImpl->mRenderer );
303 }
304
305
306 void Visual::Base::EnablePreMultipliedAlpha( bool preMultiplied )
307 {
308   if( preMultiplied )
309   {
310     mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA;
311   }
312   else
313   {
314     mImpl->mFlags &= ~Impl::IS_PREMULTIPLIED_ALPHA;
315   }
316
317   if( mImpl->mRenderer )
318   {
319     mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, preMultiplied);
320     mImpl->mRenderer.RegisterProperty( PRE_MULTIPLIED_ALPHA_PROPERTY, static_cast<float>( preMultiplied ) );
321   }
322 }
323
324 bool Visual::Base::IsPreMultipliedAlphaEnabled() const
325 {
326   return mImpl->mFlags & Impl::IS_PREMULTIPLIED_ALPHA;
327 }
328
329 void Visual::Base::DoSetOffStage( Actor& actor )
330 {
331   actor.RemoveRenderer( mImpl->mRenderer );
332   mImpl->mRenderer.Reset();
333 }
334
335 bool Visual::Base::IsOnStage() const
336 {
337   return mImpl->mFlags & Impl::IS_ON_STAGE;
338 }
339
340 void Visual::Base::RegisterMixColor()
341 {
342   // Only register if not already registered.
343   // (Color and Primitive visuals will register their own and save to this index)
344   if( mImpl->mMixColorIndex == Property::INVALID_INDEX )
345   {
346     mImpl->mMixColorIndex = DevelHandle::RegisterProperty(
347       mImpl->mRenderer,
348       Toolkit::Visual::Property::MIX_COLOR,
349       MIX_COLOR,
350       Vector3(mImpl->mMixColor) );
351   }
352
353   if( mImpl->mMixColor.a < 1.f )
354   {
355     mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON );
356   }
357
358   if( mImpl->mOpacityIndex == Property::INVALID_INDEX )
359   {
360     mImpl->mOpacityIndex = DevelHandle::RegisterProperty(
361       mImpl->mRenderer,
362       Toolkit::Visual::Property::OPACITY,
363       OPACITY,
364       mImpl->mMixColor.a );
365   }
366
367   float preMultipliedAlpha = 0.0f;
368   if( IsPreMultipliedAlphaEnabled() )
369   {
370     preMultipliedAlpha = 1.0f;
371   }
372   mImpl->mRenderer.RegisterProperty( PRE_MULTIPLIED_ALPHA_PROPERTY, preMultipliedAlpha );
373 }
374
375 void Visual::Base::SetMixColor( const Vector4& color )
376 {
377   mImpl->mMixColor = color;
378
379   if( mImpl->mRenderer )
380   {
381     mImpl->mRenderer.SetProperty( mImpl->mMixColorIndex, Vector3(color) );
382     mImpl->mRenderer.SetProperty( mImpl->mOpacityIndex, color.a );
383     if( color.a < 1.f )
384     {
385       mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON );
386     }
387   }
388 }
389
390 void Visual::Base::SetMixColor( const Vector3& color )
391 {
392   mImpl->mMixColor.r = color.r;
393   mImpl->mMixColor.g = color.g;
394   mImpl->mMixColor.b = color.b;
395
396   if( mImpl->mRenderer )
397   {
398     mImpl->mRenderer.SetProperty( mImpl->mMixColorIndex, color );
399   }
400 }
401
402 const Vector4& Visual::Base::GetMixColor() const
403 {
404   return mImpl->mMixColor;
405 }
406
407 void Visual::Base::AddResourceObserver( Visual::ResourceObserver& observer)
408 {
409   mImpl->mResourceObserver = &observer;
410 }
411
412 void Visual::Base::RemoveResourceObserver( Visual::ResourceObserver& observer )
413 {
414   mImpl->mResourceObserver = NULL;
415 }
416
417 void Visual::Base::ResourceReady()
418 {
419   if( mImpl->mResourceReady )
420   {
421     // only inform the observer the first time the resource is ready
422     return;
423   }
424   mImpl->mResourceReady = true;
425
426   if( mImpl->mResourceObserver )
427   {
428     // observer is currently a control impl
429     mImpl->mResourceObserver->ResourceReady( *this );
430   }
431 }
432
433 bool Visual::Base::IsResourceReady() const
434 {
435   return mImpl->mResourceReady;
436 }
437
438 Renderer Visual::Base::GetRenderer()
439 {
440   return mImpl->mRenderer;
441 }
442
443 Property::Index Visual::Base::GetPropertyIndex( Property::Key key )
444 {
445   Property::Index index = DevelHandle::GetPropertyIndex( mImpl->mRenderer, key );
446
447   if( index == Property::INVALID_INDEX )
448   {
449     // Is it a shader property?
450     Shader shader = mImpl->mRenderer.GetShader();
451     index = DevelHandle::GetPropertyIndex( shader, key );
452     if( index != Property::INVALID_INDEX )
453     {
454       // Yes - we should register it in the Renderer so it can be set / animated
455       // independently, as shaders are shared across multiple renderers.
456       std::string keyName;
457       Property::Index keyIndex( Property::INVALID_KEY );
458       if( key.type == Property::Key::INDEX )
459       {
460         keyName = shader.GetPropertyName( index );
461         keyIndex = key.indexKey;
462       }
463       else
464       {
465         keyName = key.stringKey;
466         // Leave keyIndex as INVALID_KEY - it can still be registered against the string key.
467       }
468       Property::Value value = shader.GetProperty( index );
469       index = DevelHandle::RegisterProperty( mImpl->mRenderer, keyIndex, keyName, value );
470     }
471   }
472   return index;
473 }
474
475 void Visual::Base::SetupTransition(
476   Dali::Animation& transition,
477   Internal::TransitionData::Animator& animator,
478   Property::Index index,
479   Property::Value& initialValue,
480   Property::Value& targetValue )
481 {
482   if( index != Property::INVALID_INDEX )
483   {
484     if( mImpl->mRenderer )
485     {
486       if( animator.animate == false )
487       {
488         mImpl->mRenderer.SetProperty( index, targetValue );
489       }
490       else
491       {
492         if( animator.initialValue.GetType() != Property::NONE )
493         {
494           mImpl->mRenderer.SetProperty( index, initialValue );
495         }
496
497         if( ! transition )
498         {
499           transition = Dali::Animation::New( 0.1f );
500         }
501
502         transition.AnimateTo( Property( mImpl->mRenderer, index ),
503                               targetValue,
504                               animator.alphaFunction,
505                               TimePeriod( animator.timePeriodDelay,
506                                           animator.timePeriodDuration ) );
507       }
508     }
509   }
510 }
511
512 void Visual::Base::AnimateProperty(
513   Dali::Animation& transition,
514   Internal::TransitionData::Animator& animator )
515 {
516 #if defined(DEBUG_ENABLED)
517   {
518     std::ostringstream oss;
519     oss << "Visual::Base::AnimateProperty(Visual:" << mImpl->mName << " Property:" << animator.propertyKey << " Target: " << animator.targetValue << std::endl;
520     DALI_LOG_INFO( gVisualBaseLogFilter, Debug::General, oss.str().c_str() );
521   }
522 #endif
523
524   Property::Map map;
525   DoCreatePropertyMap( map );
526   Property::Value* valuePtr = map.Find( Toolkit::Visual::Property::TYPE );
527   int visualType = -1;
528   if( valuePtr )
529   {
530     valuePtr->Get( visualType );
531   }
532
533   if( animator.propertyKey == Toolkit::Visual::Property::MIX_COLOR ||
534       animator.propertyKey == MIX_COLOR ||
535       ( visualType == Toolkit::Visual::COLOR &&
536         animator.propertyKey == ColorVisual::Property::MIX_COLOR ) ||
537       ( visualType == Toolkit::Visual::PRIMITIVE &&
538         animator.propertyKey == PrimitiveVisual::Property::MIX_COLOR ) )
539   {
540     AnimateMixColorProperty( transition, animator );
541   }
542   else if(animator.propertyKey == Toolkit::Visual::Property::OPACITY ||
543           animator.propertyKey == OPACITY )
544   {
545     AnimateOpacityProperty( transition, animator );
546   }
547   else if( mImpl->mRenderer )
548   {
549     AnimateRendererProperty( transition, animator );
550   }
551 }
552
553 void Visual::Base::AnimateOpacityProperty(
554   Dali::Animation& transition,
555   Internal::TransitionData::Animator& animator )
556 {
557   Property::Index index = mImpl->mOpacityIndex;
558
559   bool isOpaque = mImpl->mMixColor.a >= 1.0f;
560
561   if( index != Property::INVALID_INDEX )
562   {
563     float initialOpacity;
564     if( animator.initialValue.Get( initialOpacity ) )
565     {
566       isOpaque = (initialOpacity >= 1.0f);
567     }
568
569     float targetOpacity;
570     if( animator.targetValue.Get( targetOpacity ) )
571     {
572       mImpl->mMixColor.a = targetOpacity;
573     }
574
575     SetupTransition( transition, animator, index, animator.initialValue, animator.targetValue );
576     SetupBlendMode( transition, isOpaque, animator.animate );
577   }
578 }
579
580 void Visual::Base::AnimateRendererProperty(
581   Dali::Animation& transition,
582   Internal::TransitionData::Animator& animator )
583 {
584   Property::Index index = GetPropertyIndex( animator.propertyKey );
585   if( index != Property::INVALID_INDEX )
586   {
587     if( animator.targetValue.GetType() != Property::NONE )
588     {
589       // Try writing target value into transform property map
590       // if it's not a valid key, then it won't alter mTransform
591       Property::Map map;
592       if( animator.propertyKey.type == Property::Key::INDEX )
593       {
594         map.Add( animator.propertyKey.indexKey, animator.targetValue );
595       }
596       else
597       {
598         map.Add( animator.propertyKey.stringKey, animator.targetValue );
599       }
600
601       mImpl->mTransform.UpdatePropertyMap( map );
602     }
603
604     SetupTransition( transition, animator, index, animator.initialValue, animator.targetValue );
605   }
606 }
607
608 void Visual::Base::AnimateMixColorProperty(
609   Dali::Animation& transition,
610   Internal::TransitionData::Animator& animator )
611 {
612   Property::Index index = mImpl->mMixColorIndex;
613   bool animateOpacity = false;
614   bool isOpaque = true;
615
616   Property::Value initialOpacity;
617   Property::Value targetOpacity;
618   Property::Value initialMixColor;
619   Property::Value targetMixColor;
620
621   if( index != Property::INVALID_INDEX )
622   {
623     Vector4 initialColor;
624     if( animator.initialValue.Get(initialColor) )
625     {
626       if( animator.initialValue.GetType() == Property::VECTOR4 )
627       {
628         // if there is an initial color specifying alpha, test it
629         isOpaque = initialColor.a >= 1.0f;
630         initialOpacity = initialColor.a;
631       }
632       initialMixColor = Vector3( initialColor );
633     }
634
635     // Set target value into data store
636     if( animator.targetValue.GetType() != Property::NONE )
637     {
638       Vector4 mixColor;
639       animator.targetValue.Get(mixColor);
640       if( animator.targetValue.GetType() == Property::VECTOR4 )
641       {
642         mImpl->mMixColor.a = mixColor.a;
643         targetOpacity = mixColor.a;
644         animateOpacity = true;
645       }
646
647       mImpl->mMixColor.r = mixColor.r;
648       mImpl->mMixColor.g = mixColor.g;
649       mImpl->mMixColor.b = mixColor.b;
650       targetMixColor = Vector3(mixColor);
651     }
652
653     SetupTransition( transition, animator, index, initialMixColor, targetMixColor );
654     if( animateOpacity )
655     {
656       SetupTransition( transition, animator, mImpl->mOpacityIndex, initialOpacity, targetOpacity );
657       SetupBlendMode( transition, isOpaque, animator.animate );
658     }
659   }
660 }
661
662 void Visual::Base::SetupBlendMode( Animation& transition, bool isInitialOpaque, bool animating )
663 {
664   // Ensure the blend mode is turned on if we are animating opacity, and
665   // turned off after the animation ends if the final value is opaque
666   if( ! isInitialOpaque || mImpl->mMixColor.a < 1.0f )
667   {
668     mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON );
669
670     if( animating == true && mImpl->mMixColor.a >= 1.0f )
671     {
672       // When it becomes opaque, set the blend mode back to automatically
673       if( ! mImpl->mBlendSlotDelegate )
674       {
675         mImpl->mBlendSlotDelegate = new SlotDelegate<Visual::Base>(this);
676       }
677       transition.FinishedSignal().Connect( *(mImpl->mBlendSlotDelegate),
678                                            &Visual::Base::OnMixColorFinished );
679     }
680   }
681 }
682
683 void Visual::Base::OnMixColorFinished( Animation& animation )
684 {
685   if( mImpl->mRenderer )
686   {
687     DALI_LOG_INFO( gVisualBaseLogFilter, Debug::General, "Visual::Base::OnMixColorFinished()\n");
688     mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE,
689                                   ( mImpl->mMixColor.a < 1.0 ) ? BlendMode::ON : BlendMode::AUTO );
690   }
691   delete mImpl->mBlendSlotDelegate;
692   mImpl->mBlendSlotDelegate = NULL;
693 }
694
695 } // namespace Internal
696
697 } // namespace Toolkit
698
699 } // namespace Dali