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