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