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