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