Rounded corner for SVG / Animated Vector Image visual
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / svg / svg-visual.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 "svg-visual.h"
20
21 // INTERNAL INCLUDES
22 #include <dali-toolkit/internal/visuals/svg/svg-rasterize-thread.h>
23 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
24 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
25 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
26 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
27 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
28
29 // EXTERNAL INCLUDES
30 #include <dali/devel-api/common/stage.h>
31 #include <dali/devel-api/adaptor-framework/file-loader.h>
32 #include <dali/integration-api/debug.h>
33
34 namespace Dali
35 {
36
37 namespace Toolkit
38 {
39
40 namespace Internal
41 {
42
43 namespace
44 {
45 // property name
46 const Dali::Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
47
48 }
49
50 SvgVisualPtr SvgVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties )
51 {
52   SvgVisualPtr svgVisual( new SvgVisual( factoryCache, shaderFactory, imageUrl ) );
53   svgVisual->Load();
54   svgVisual->SetProperties(properties);
55   return svgVisual;
56 }
57
58 SvgVisualPtr SvgVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl )
59 {
60   SvgVisualPtr svgVisual( new SvgVisual( factoryCache, shaderFactory, imageUrl ) );
61   svgVisual->Load();
62   return svgVisual;
63 }
64
65 SvgVisual::SvgVisual( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl )
66 : Visual::Base( factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::SVG ),
67   mImageVisualShaderFactory( shaderFactory ),
68   mAtlasRect( FULL_TEXTURE_RECT ),
69   mImageUrl( imageUrl ),
70   mVectorRenderer( VectorImageRenderer::New() ),
71   mDefaultWidth( 0 ),
72   mDefaultHeight( 0 ),
73   mLoaded( false ),
74   mPlacementActor(),
75   mVisualSize(Vector2::ZERO),
76   mAttemptAtlasing( false )
77 {
78   // the rasterized image is with pre-multiplied alpha format
79   mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA;
80 }
81
82 SvgVisual::~SvgVisual()
83 {
84 }
85
86 void SvgVisual::DoSetProperties( const Property::Map& propertyMap )
87 {
88   // url already passed in from constructor
89   for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
90   {
91     KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
92     if( keyValue.first.type == Property::Key::INDEX )
93     {
94       DoSetProperty( keyValue.first.indexKey, keyValue.second );
95     }
96     else if( keyValue.first == IMAGE_ATLASING )
97     {
98       DoSetProperty( Toolkit::ImageVisual::Property::ATLASING, keyValue.second );
99     }
100     else if( keyValue.first == SYNCHRONOUS_LOADING )
101     {
102       DoSetProperty( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second );
103     }
104   }
105 }
106
107 void SvgVisual::DoSetProperty( Property::Index index, const Property::Value& value )
108 {
109   switch( index )
110   {
111     case Toolkit::ImageVisual::Property::ATLASING:
112     {
113       value.Get( mAttemptAtlasing );
114       break;
115     }
116     case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
117     {
118       bool sync = false;
119       if( value.Get( sync ) )
120       {
121         if( sync )
122         {
123           mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
124         }
125         else
126         {
127           mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
128         }
129       }
130       else
131       {
132         DALI_LOG_ERROR("ImageVisual: synchronousLoading property has incorrect type\n");
133       }
134       break;
135     }
136   }
137 }
138
139 void SvgVisual::DoSetOnScene( Actor& actor )
140 {
141   Shader shader;
142   if( !mImpl->mCustomShader )
143   {
144     shader = mImageVisualShaderFactory.GetShader( mFactoryCache, mAttemptAtlasing, true, IsRoundedCornerRequired() );
145   }
146   else
147   {
148     shader = Shader::New( mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource().data() : mImpl->mCustomShader->mVertexShader,
149                           mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource().data() : mImpl->mCustomShader->mFragmentShader,
150                           mImpl->mCustomShader->mHints );
151
152     shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
153   }
154
155   Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
156   TextureSet textureSet = TextureSet::New();
157   mImpl->mRenderer = Renderer::New( geometry, shader );
158   mImpl->mRenderer.SetTextures( textureSet );
159
160   // Register transform properties
161   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
162
163   // Defer the rasterisation task until we get given a size (by Size Negotiation algorithm)
164
165   // Hold the weak handle of the placement actor and delay the adding of renderer until the svg rasterization is finished.
166   mPlacementActor = actor;
167
168   // SVG visual needs it's size set before it can be rasterized hence set ResourceReady once on stage
169   ResourceReady( Toolkit::Visual::ResourceStatus::READY );
170 }
171
172 void SvgVisual::DoSetOffScene( Actor& actor )
173 {
174   mFactoryCache.GetSVGRasterizationThread()->RemoveTask( this );
175
176   actor.RemoveRenderer( mImpl->mRenderer );
177   mImpl->mRenderer.Reset();
178   mPlacementActor.Reset();
179
180   // Reset the visual size to zero so that when adding the actor back to stage the SVG rasterization is forced
181   mVisualSize = Vector2::ZERO;
182 }
183
184 void SvgVisual::GetNaturalSize( Vector2& naturalSize )
185 {
186   if(mLoaded)
187   {
188     naturalSize.x = mDefaultWidth;
189     naturalSize.y = mDefaultHeight;
190   }
191   else
192   {
193     naturalSize = Vector2::ZERO;
194   }
195 }
196
197 void SvgVisual::DoCreatePropertyMap( Property::Map& map ) const
198 {
199   map.Clear();
200   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::SVG );
201   if( mImageUrl.IsValid() )
202   {
203     map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
204     map.Insert( Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing );
205   }
206   map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, IsSynchronousLoadingRequired() );
207 }
208
209 void SvgVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
210 {
211   // Do nothing
212 }
213
214 void SvgVisual::Load()
215 {
216   // load remote resource on svg rasterize thread.
217   if(!mLoaded && mImageUrl.IsLocalResource())
218   {
219     Dali::Vector<uint8_t> buffer;
220     if(Dali::FileLoader::ReadFile(mImageUrl.GetUrl(), buffer))
221     {
222       buffer.PushBack('\0');
223
224       Vector2 dpi = Stage::GetCurrent().GetDpi();
225       float meanDpi = (dpi.height + dpi.width) * 0.5f;
226       if(!mVectorRenderer.Load(buffer, meanDpi))
227       {
228         DALI_LOG_ERROR("SvgVisual::Load: Failed to load file! [%s]\n", mImageUrl.GetUrl().c_str());
229         return;
230       }
231       mVectorRenderer.GetDefaultSize(mDefaultWidth, mDefaultHeight);
232       mLoaded = true;
233     }
234     else
235     {
236       DALI_LOG_ERROR("SvgVisual::Load: Failed to read file! [%s]\n", mImageUrl.GetUrl().c_str());
237     }
238   }
239 }
240
241 void SvgVisual::AddRasterizationTask( const Vector2& size )
242 {
243   if( mImpl->mRenderer )
244   {
245     unsigned int width = static_cast<unsigned int>(size.width);
246     unsigned int height = static_cast<unsigned int>( size.height );
247
248     Vector2 dpi = Stage::GetCurrent().GetDpi();
249     float meanDpi = ( dpi.height + dpi.width ) * 0.5f;
250
251     RasterizingTaskPtr newTask = new RasterizingTask(this, mVectorRenderer, mImageUrl, meanDpi, width, height, mLoaded);
252     if(IsSynchronousLoadingRequired())
253     {
254       newTask->Load();
255       newTask->Rasterize();
256       ApplyRasterizedImage(newTask->GetVectorRenderer(), newTask->GetPixelData(), newTask->IsLoaded());
257     }
258     else
259     {
260       mFactoryCache.GetSVGRasterizationThread()->AddTask( newTask );
261     }
262   }
263 }
264
265 void SvgVisual::ApplyRasterizedImage( VectorImageRenderer vectorRenderer, PixelData rasterizedPixelData, bool isLoaded )
266 {
267   mLoaded = isLoaded;
268
269   if(isLoaded && rasterizedPixelData && IsOnScene())
270   {
271     TextureSet currentTextureSet = mImpl->mRenderer.GetTextures();
272     if( mImpl->mFlags & Impl::IS_ATLASING_APPLIED )
273     {
274       mFactoryCache.GetAtlasManager()->Remove( currentTextureSet, mAtlasRect );
275     }
276
277     TextureSet textureSet;
278
279     if( mAttemptAtlasing && !mImpl->mCustomShader )
280     {
281       Vector4 atlasRect;
282       textureSet = mFactoryCache.GetAtlasManager()->Add(atlasRect, rasterizedPixelData );
283       if( textureSet ) // atlasing
284       {
285         if( textureSet != currentTextureSet )
286         {
287           mImpl->mRenderer.SetTextures( textureSet );
288         }
289         mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, atlasRect );
290         mAtlasRect = atlasRect;
291         mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
292       }
293     }
294
295     if( !textureSet ) // no atlasing - mAttemptAtlasing is false or adding to atlas is failed
296     {
297       Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888,
298                                       rasterizedPixelData.GetWidth(), rasterizedPixelData.GetHeight() );
299       texture.Upload( rasterizedPixelData );
300       mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
301
302       if( mAtlasRect == FULL_TEXTURE_RECT )
303       {
304         textureSet = currentTextureSet;
305       }
306       else
307       {
308         textureSet = TextureSet::New();
309         mImpl->mRenderer.SetTextures( textureSet );
310
311         mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, FULL_TEXTURE_RECT );
312         mAtlasRect = FULL_TEXTURE_RECT;
313       }
314
315       if( textureSet )
316       {
317         textureSet.SetTexture( 0, texture );
318       }
319     }
320
321     // Rasterized pixels are uploaded to texture. If weak handle is holding a placement actor, it is the time to add the renderer to actor.
322     Actor actor = mPlacementActor.GetHandle();
323     if( actor )
324     {
325       actor.AddRenderer( mImpl->mRenderer );
326       // reset the weak handle so that the renderer only get added to actor once
327       mPlacementActor.Reset();
328     }
329
330     // Svg loaded and ready to display
331     ResourceReady( Toolkit::Visual::ResourceStatus::READY );
332   }
333   else if(!isLoaded || !rasterizedPixelData)
334   {
335     ResourceReady( Toolkit::Visual::ResourceStatus::FAILED );
336   }
337 }
338
339 void SvgVisual::OnSetTransform()
340 {
341   Vector2 visualSize = mImpl->mTransform.GetVisualSize( mImpl->mControlSize );
342
343   if( IsOnScene() )
344   {
345     if( visualSize != mVisualSize )
346     {
347       AddRasterizationTask( visualSize );
348       mVisualSize = visualSize;
349     }
350   }
351
352   if(mImpl->mRenderer)
353   {
354     mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
355   }
356 }
357
358 bool SvgVisual::IsResourceReady() const
359 {
360   return ( mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ||
361            mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED );
362 }
363
364 } // namespace Internal
365
366 } // namespace Toolkit
367
368 } // namespace Dali