2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "npatch-visual.h"
22 #include <dali/devel-api/adaptor-framework/image-loading.h>
23 #include <dali/devel-api/common/stage.h>
24 #include <dali/devel-api/rendering/renderer-devel.h>
25 #include <dali/integration-api/debug.h>
28 #include <dali-toolkit/devel-api/utility/npatch-helper.h>
29 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
30 #include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
31 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
32 #include <dali-toolkit/internal/visuals/npatch-loader.h>
33 #include <dali-toolkit/internal/visuals/rendering-addon.h>
34 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
35 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
36 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
37 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
38 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
39 #include <dali-toolkit/public-api/visuals/visual-properties.h>
49 const int CUSTOM_PROPERTY_COUNT(10); // 5 transform properties + fixed(3),stretch,aux
52 /////////////////NPatchVisual////////////////
54 NPatchVisualPtr NPatchVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties)
56 NPatchVisualPtr nPatchVisual(new NPatchVisual(factoryCache, shaderFactory));
57 nPatchVisual->mImageUrl = imageUrl;
58 nPatchVisual->SetProperties(properties);
59 nPatchVisual->Initialize();
63 NPatchVisualPtr NPatchVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl)
65 NPatchVisualPtr nPatchVisual(new NPatchVisual(factoryCache, shaderFactory));
66 nPatchVisual->mImageUrl = imageUrl;
67 nPatchVisual->Initialize();
71 void NPatchVisual::LoadImages()
73 TextureManager& textureManager = mFactoryCache.GetTextureManager();
74 bool synchronousLoading = mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
76 if(mId == NPatchData::INVALID_NPATCH_DATA_ID && (mImageUrl.IsLocalResource() || mImageUrl.IsBufferResource()))
78 bool preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader ? true : false;
79 mId = mLoader.Load(textureManager, this, mImageUrl, mBorder, preMultiplyOnLoad, synchronousLoading);
81 const NPatchData* data;
82 if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE)
84 EnablePreMultipliedAlpha(data->IsPreMultiplied());
88 if(!mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && (mAuxiliaryUrl.IsLocalResource() || mAuxiliaryUrl.IsBufferResource()))
90 // Load the auxiliary image
91 auto preMultiplyOnLoading = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
92 mAuxiliaryPixelBuffer = textureManager.LoadPixelBuffer(mAuxiliaryUrl, Dali::ImageDimensions(), FittingMode::DEFAULT, SamplingMode::BOX_THEN_LINEAR, synchronousLoading, this, true, preMultiplyOnLoading);
96 void NPatchVisual::GetNaturalSize(Vector2& naturalSize)
101 // load now if not already loaded
102 const NPatchData* data;
103 if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() != NPatchData::LoadingState::LOADING)
105 naturalSize.x = data->GetCroppedWidth();
106 naturalSize.y = data->GetCroppedHeight();
110 if(mImageUrl.IsValid())
112 ImageDimensions dimensions = Dali::GetOriginalImageSize(mImageUrl.GetUrl());
113 if(dimensions != ImageDimensions(0, 0))
115 naturalSize.x = dimensions.GetWidth();
116 naturalSize.y = dimensions.GetHeight();
121 if(mAuxiliaryPixelBuffer)
123 naturalSize.x = std::max(naturalSize.x, float(mAuxiliaryPixelBuffer.GetWidth()));
124 naturalSize.y = std::max(naturalSize.y, float(mAuxiliaryPixelBuffer.GetHeight()));
128 void NPatchVisual::DoSetProperties(const Property::Map& propertyMap)
130 // URL is already passed in via constructor
132 Property::Value* borderOnlyValue = propertyMap.Find(Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY);
135 borderOnlyValue->Get(mBorderOnly);
138 Property::Value* borderValue = propertyMap.Find(Toolkit::ImageVisual::Property::BORDER, BORDER);
139 if(borderValue && !borderValue->Get(mBorder)) // If value exists and is rect, just set mBorder
141 // Not a rect so try vector4
143 if(borderValue->Get(border))
145 mBorder.left = static_cast<int>(border.x);
146 mBorder.right = static_cast<int>(border.y);
147 mBorder.bottom = static_cast<int>(border.z);
148 mBorder.top = static_cast<int>(border.w);
152 Property::Value* auxImage = propertyMap.Find(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, AUXILIARY_IMAGE_NAME);
156 if(auxImage->Get(url))
162 Property::Value* auxImageAlpha = propertyMap.Find(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, AUXILIARY_IMAGE_ALPHA_NAME);
165 auxImageAlpha->Get(mAuxiliaryImageAlpha);
168 Property::Value* synchronousLoading = propertyMap.Find(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, SYNCHRONOUS_LOADING);
169 if(synchronousLoading)
172 synchronousLoading->Get(sync);
175 mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
179 mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
183 Property::Value* releasePolicy = propertyMap.Find(Toolkit::ImageVisual::Property::RELEASE_POLICY, RELEASE_POLICY_NAME);
186 releasePolicy->Get(mReleasePolicy);
190 void NPatchVisual::DoSetOnScene(Actor& actor)
192 // load when first go on stage
195 const NPatchData* data;
196 if(mLoader.GetNPatchData(mId, data))
198 Geometry geometry = CreateGeometry();
199 Shader shader = CreateShader();
201 mImpl->mRenderer.SetGeometry(geometry);
202 mImpl->mRenderer.SetShader(shader);
204 mPlacementActor = actor;
205 if(data->GetLoadingState() != NPatchData::LoadingState::LOADING)
207 if(RenderingAddOn::Get().IsValid())
209 RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap());
212 ApplyTextureAndUniforms();
213 actor.AddRenderer(mImpl->mRenderer);
214 mPlacementActor.Reset();
216 // npatch loaded and ready to display
217 ResourceReady(Toolkit::Visual::ResourceStatus::READY);
222 void NPatchVisual::DoSetOffScene(Actor& actor)
224 if((mId != NPatchData::INVALID_NPATCH_DATA_ID) && mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED)
226 mLoader.Remove(mId, this);
227 mImpl->mResourceStatus = Toolkit::Visual::ResourceStatus::PREPARING;
228 mId = NPatchData::INVALID_NPATCH_DATA_ID;
231 actor.RemoveRenderer(mImpl->mRenderer);
232 mPlacementActor.Reset();
235 void NPatchVisual::OnSetTransform()
239 mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
243 void NPatchVisual::DoCreatePropertyMap(Property::Map& map) const
246 bool sync = IsSynchronousLoadingRequired();
247 map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync);
248 map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::N_PATCH);
249 map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl());
250 map.Insert(Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly);
251 map.Insert(Toolkit::ImageVisual::Property::BORDER, mBorder);
252 map.Insert(Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy);
254 if(mAuxiliaryUrl.IsValid())
256 map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl());
257 map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha);
261 void NPatchVisual::DoCreateInstancePropertyMap(Property::Map& map) const
263 if(mAuxiliaryUrl.IsValid())
265 map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl());
266 map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha);
270 NPatchVisual::NPatchVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory)
271 : Visual::Base(factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::N_PATCH),
273 mLoader(factoryCache.GetNPatchLoader()),
274 mImageVisualShaderFactory(shaderFactory),
277 mId(NPatchData::INVALID_NPATCH_DATA_ID),
280 mAuxiliaryImageAlpha(0.0f),
281 mReleasePolicy(Toolkit::ImageVisual::ReleasePolicy::DETACHED)
283 EnablePreMultipliedAlpha(mFactoryCache.GetPreMultiplyOnLoad());
286 NPatchVisual::~NPatchVisual()
288 if(Stage::IsInstalled() && (mId != NPatchData::INVALID_NPATCH_DATA_ID) && (mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER))
290 mLoader.Remove(mId, this);
291 mId = NPatchData::INVALID_NPATCH_DATA_ID;
295 void NPatchVisual::OnInitialize()
297 // Get basic geometry and shader
298 Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
299 Shader shader = mImageVisualShaderFactory.GetShader(
301 ImageVisualShaderFeature::FeatureBuilder());
303 mImpl->mRenderer = Renderer::New(geometry, shader);
304 mImpl->mRenderer.ReserveCustomProperties(CUSTOM_PROPERTY_COUNT);
306 //Register transform properties
307 mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
310 Geometry NPatchVisual::CreateGeometry()
313 const NPatchData* data;
314 if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE)
316 if(data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1)
318 if(DALI_UNLIKELY(mBorderOnly))
320 geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY);
324 if(data->GetRenderingMap())
326 uint32_t elementCount[2];
327 geometry = RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), Uint16Pair(3, 3), elementCount);
330 RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap());
335 geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_GEOMETRY);
339 else if(data->GetStretchPixelsX().Size() > 0 || data->GetStretchPixelsY().Size() > 0)
341 Uint16Pair gridSize(2 * data->GetStretchPixelsX().Size() + 1, 2 * data->GetStretchPixelsY().Size() + 1);
342 if(!data->GetRenderingMap())
344 geometry = !mBorderOnly ? NPatchHelper::CreateGridGeometry(gridSize) : NPatchHelper::CreateBorderGeometry(gridSize);
348 uint32_t elementCount[2];
349 geometry = !mBorderOnly ? RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), gridSize, elementCount) : NPatchHelper::CreateBorderGeometry(gridSize);
352 RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap());
359 // no N patch data so use default geometry
360 geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_GEOMETRY);
365 Shader NPatchVisual::CreateShader()
368 const NPatchData* data;
369 // 0 is either no data (load failed?) or no stretch regions on image
370 // for both cases we use the default shader
371 NPatchUtility::StretchRanges::SizeType xStretchCount = 0;
372 NPatchUtility::StretchRanges::SizeType yStretchCount = 0;
374 auto fragmentShader = mAuxiliaryPixelBuffer ? SHADER_NPATCH_VISUAL_MASK_SHADER_FRAG
375 : SHADER_NPATCH_VISUAL_SHADER_FRAG;
376 auto shaderType = mAuxiliaryPixelBuffer ? VisualFactoryCache::NINE_PATCH_MASK_SHADER
377 : VisualFactoryCache::NINE_PATCH_SHADER;
379 // ask loader for the regions
380 if(mLoader.GetNPatchData(mId, data))
382 xStretchCount = data->GetStretchPixelsX().Count();
383 yStretchCount = data->GetStretchPixelsY().Count();
386 if(DALI_LIKELY(!mImpl->mCustomShader))
388 if(DALI_LIKELY((xStretchCount == 1 && yStretchCount == 1) ||
389 (xStretchCount == 0 && yStretchCount == 0)))
391 shader = mFactoryCache.GetShader(shaderType);
392 if(DALI_UNLIKELY(!shader))
394 shader = Shader::New(SHADER_NPATCH_VISUAL_3X3_SHADER_VERT, fragmentShader);
395 // Only cache vanilla 9 patch shaders
396 mFactoryCache.SaveShader(shaderType, shader);
399 else if(xStretchCount > 0 || yStretchCount > 0)
401 std::stringstream vertexShader;
402 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
403 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
404 << SHADER_NPATCH_VISUAL_SHADER_VERT;
406 shader = Shader::New(vertexShader.str(), fragmentShader);
411 Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
413 if(!mImpl->mCustomShader->mFragmentShader.empty())
415 fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
417 hints = mImpl->mCustomShader->mHints;
419 /* Apply Custom Vertex Shader only if image is 9-patch */
420 if((xStretchCount == 1 && yStretchCount == 1) ||
421 (xStretchCount == 0 && yStretchCount == 0))
423 const char* vertexShader = SHADER_NPATCH_VISUAL_3X3_SHADER_VERT.data();
425 if(!mImpl->mCustomShader->mVertexShader.empty())
427 vertexShader = mImpl->mCustomShader->mVertexShader.c_str();
429 shader = Shader::New(vertexShader, fragmentShader, hints);
431 else if(xStretchCount > 0 || yStretchCount > 0)
433 std::stringstream vertexShader;
434 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
435 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
436 << SHADER_NPATCH_VISUAL_SHADER_VERT;
438 shader = Shader::New(vertexShader.str(), fragmentShader, hints);
445 void NPatchVisual::ApplyTextureAndUniforms()
447 const NPatchData* data;
448 TextureSet textureSet;
450 if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE)
452 textureSet = data->GetTextures();
453 NPatchHelper::ApplyTextureAndUniforms(mImpl->mRenderer, data);
457 DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str());
458 textureSet = TextureSet::New();
460 Actor actor = mPlacementActor.GetHandle();
461 Vector2 imageSize = Vector2::ZERO;
464 imageSize = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
466 mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize);
469 if(mAuxiliaryPixelBuffer)
471 // If the auxiliary image is smaller than the un-stretched NPatch, use CPU resizing to enlarge it to the
472 // same size as the unstretched NPatch. This will give slightly higher quality results than just relying
473 // on GL interpolation alone.
474 if(mAuxiliaryPixelBuffer.GetWidth() < data->GetCroppedWidth() &&
475 mAuxiliaryPixelBuffer.GetHeight() < data->GetCroppedHeight())
477 mAuxiliaryPixelBuffer.Resize(data->GetCroppedWidth(), data->GetCroppedHeight());
480 // Note, this resets mAuxiliaryPixelBuffer handle
481 auto auxiliaryPixelData = Devel::PixelBuffer::Convert(mAuxiliaryPixelBuffer);
483 auto texture = Texture::New(TextureType::TEXTURE_2D,
484 auxiliaryPixelData.GetPixelFormat(),
485 auxiliaryPixelData.GetWidth(),
486 auxiliaryPixelData.GetHeight());
487 texture.Upload(auxiliaryPixelData);
488 textureSet.SetTexture(1, texture);
489 mImpl->mRenderer.RegisterProperty(DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA,
490 AUXILIARY_IMAGE_ALPHA_NAME,
491 mAuxiliaryImageAlpha);
493 mImpl->mRenderer.SetTextures(textureSet);
495 // Register transform properties
496 mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
499 Geometry NPatchVisual::GetNinePatchGeometry(VisualFactoryCache::GeometryType subType)
501 Geometry geometry = mFactoryCache.GetGeometry(subType);
504 if(DALI_LIKELY(VisualFactoryCache::NINE_PATCH_GEOMETRY == subType))
506 geometry = NPatchHelper::CreateGridGeometry(Uint16Pair(3, 3));
508 else if(VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType)
510 geometry = NPatchHelper::CreateBorderGeometry(Uint16Pair(3, 3));
512 mFactoryCache.SaveGeometry(subType, geometry);
517 void NPatchVisual::SetResource()
519 const NPatchData* data;
520 if(mImpl->mRenderer && mLoader.GetNPatchData(mId, data))
522 Geometry geometry = CreateGeometry();
523 Shader shader = CreateShader();
525 mImpl->mRenderer.SetGeometry(geometry);
526 mImpl->mRenderer.SetShader(shader);
528 Actor actor = mPlacementActor.GetHandle();
531 ApplyTextureAndUniforms();
532 actor.AddRenderer(mImpl->mRenderer);
533 mPlacementActor.Reset();
535 // npatch loaded and ready to display
536 ResourceReady(Toolkit::Visual::ResourceStatus::READY);
541 void NPatchVisual::LoadComplete(bool loadSuccess, TextureInformation textureInformation)
543 if(textureInformation.returnType == TextureUploadObserver::ReturnType::TEXTURE)
545 EnablePreMultipliedAlpha(textureInformation.preMultiplied);
548 // Image loaded and ready to display
549 ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
552 if(mAuxiliaryPixelBuffer || !mAuxiliaryUrl.IsValid())
557 else // for the ReturnType::PIXEL_BUFFER
559 if(loadSuccess && textureInformation.url == mAuxiliaryUrl.GetUrl())
561 mAuxiliaryPixelBuffer = textureInformation.pixelBuffer;
566 // Image loaded and ready to display
567 ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
572 } // namespace Internal
574 } // namespace Toolkit