2 * Copyright (c) 2017 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 <dali-toolkit/internal/visuals/texture-manager-impl.h>
24 #include <dali/public-api/math/vector4.h>
25 #include <dali/devel-api/adaptor-framework/environment-variable.h>
26 #include <dali/devel-api/adaptor-framework/image-loading.h>
27 #include <dali/devel-api/common/hash.h>
28 #include <dali/devel-api/images/texture-set-image.h>
29 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
30 #include <dali/integration-api/debug.h>
33 #include <dali-toolkit/internal/image-loader/image-atlas-impl.h>
34 #include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
35 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
40 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS = size_t{4u};
41 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
43 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV = "DALI_TEXTURE_LOCAL_THREADS";
44 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
46 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
48 using Dali::EnvironmentVariable::GetEnvironmentVariable;
49 auto numberString = GetEnvironmentVariable(environmentVariable);
50 auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
51 constexpr auto MAX_NUMBER_OF_THREADS = 100u;
52 DALI_ASSERT_DEBUG( numberOfThreads < MAX_NUMBER_OF_THREADS );
53 return ( numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS ) ? numberOfThreads : defaultValue;
56 size_t GetNumberOfLocalLoaderThreads()
58 return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
61 size_t GetNumberOfRemoteLoaderThreads()
63 return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
81 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_TEXTURE_MANAGER" );
84 const uint32_t DEFAULT_ATLAS_SIZE( 1024u ); ///< This size can fit 8 by 8 images of average size 128 * 128
85 const Vector4 FULL_ATLAS_RECT( 0.0f, 0.0f, 1.0f, 1.0f ); ///< UV Rectangle that covers the full Texture
86 const char * const BROKEN_IMAGE_URL( DALI_IMAGE_DIR "broken.png" ); ///< URL For the broken image placeholder
87 const int INVALID_INDEX( -1 ); ///< Invalid index used to represent a non-existant TextureInfo struct
88 const int INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index
91 void PreMultiply( Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
93 if( Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) )
95 if( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD )
97 pixelBuffer.MultiplyColorByAlpha();
102 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
106 } // Anonymous namespace
108 TextureManager::MaskingData::MaskingData()
110 mAlphaMaskId( INVALID_TEXTURE_ID ),
111 mContentScaleFactor( 1.0f ),
116 TextureManager::TextureManager()
117 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
118 mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
119 mCurrentTextureId( 0 )
123 TextureSet TextureManager::LoadTexture(
124 const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
125 Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
126 bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
127 bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU,
128 Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
129 AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
130 TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
132 TextureSet textureSet;
134 loadingStatus = false;
135 textureRect = FULL_ATLAS_RECT;
137 if( VisualUrl::TEXTURE == url.GetProtocolType())
139 std::string location = url.GetLocation();
140 if( location.size() > 0u )
142 TextureId id = std::stoi( location );
143 for( auto&& elem : mExternalTextures )
145 if( elem.textureId == id )
147 textureId = elem.textureId;
148 return elem.textureSet;
153 else if( synchronousLoading )
158 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
159 orientationCorrection );
162 PreMultiply( pixelBuffer, preMultiplyOnLoad );
163 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
169 textureSet = TextureSet::New();
170 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( BROKEN_IMAGE_URL );
173 PreMultiply( pixelBuffer, preMultiplyOnLoad );
174 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
176 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
177 data.GetWidth(), data.GetHeight() );
178 texture.Upload( data );
179 textureSet = TextureSet::New();
180 textureSet.SetTexture( 0u, texture );
184 if( atlasingStatus ) // attempt atlasing
186 textureSet = imageAtlasManager->Add( textureRect, data );
188 if( !textureSet ) // big image, no atlasing or atlasing failed
190 atlasingStatus = false;
191 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
192 data.GetWidth(), data.GetHeight() );
193 texture.Upload( data );
194 textureSet = TextureSet::New();
195 textureSet.SetTexture( 0u, texture );
201 loadingStatus = true;
204 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver );
206 if( !textureSet ) // big image, no atlasing or atlasing failed
208 atlasingStatus = false;
211 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
212 textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
216 textureId = RequestLoad( url,
217 maskInfo->mAlphaMaskId,
218 maskInfo->mContentScaleFactor,
220 fittingMode, samplingMode,
221 TextureManager::NO_ATLAS,
222 maskInfo->mCropToMask,
224 orientationCorrection,
225 reloadPolicy, preMultiplyOnLoad );
228 TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
229 loadingStatus = ( loadState == TextureManager::LOADING );
231 if( loadState == TextureManager::UPLOADED )
233 // UploadComplete has already been called - keep the same texture set
234 textureSet = GetTextureSet( textureId );
239 if( ! atlasingStatus && textureSet )
241 Sampler sampler = Sampler::New();
242 sampler.SetWrapMode( wrapModeU, wrapModeV );
243 textureSet.SetSampler( 0u, sampler );
249 TextureManager::TextureId TextureManager::RequestLoad(
250 const VisualUrl& url,
251 const ImageDimensions desiredSize,
252 FittingMode::Type fittingMode,
253 Dali::SamplingMode::Type samplingMode,
254 const UseAtlas useAtlas,
255 TextureUploadObserver* observer,
256 bool orientationCorrection,
257 TextureManager::ReloadPolicy reloadPolicy,
258 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
260 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
261 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
265 TextureManager::TextureId TextureManager::RequestLoad(
266 const VisualUrl& url,
267 TextureId maskTextureId,
269 const ImageDimensions desiredSize,
270 FittingMode::Type fittingMode,
271 Dali::SamplingMode::Type samplingMode,
272 const UseAtlas useAtlas,
274 TextureUploadObserver* observer,
275 bool orientationCorrection,
276 TextureManager::ReloadPolicy reloadPolicy,
277 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
279 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
280 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
284 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
286 // Use the normal load procedure to get the alpha mask.
287 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
288 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
289 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
290 TextureManager::ReloadPolicy::CACHED, preMultiply );
293 TextureManager::TextureId TextureManager::RequestLoadInternal(
294 const VisualUrl& url,
295 TextureId maskTextureId,
297 const ImageDimensions desiredSize,
298 FittingMode::Type fittingMode,
299 Dali::SamplingMode::Type samplingMode,
302 StorageType storageType,
303 TextureUploadObserver* observer,
304 bool orientationCorrection,
305 TextureManager::ReloadPolicy reloadPolicy,
306 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
308 // First check if the requested Texture is cached.
309 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
310 maskTextureId, preMultiplyOnLoad );
312 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
314 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
315 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
316 maskTextureId, preMultiplyOnLoad );
318 // Check if the requested Texture exists in the cache.
319 if( cacheIndex != INVALID_CACHE_INDEX )
321 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
323 // Mark this texture being used by another client resource. Forced reload would replace the current texture
324 // without the need for incrementing the reference count.
325 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
327 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
328 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
329 url.GetUrl().c_str(), observer, cacheIndex, textureId );
332 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
334 // We need a new Texture.
335 textureId = GenerateUniqueTextureId();
336 bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
337 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
338 desiredSize, contentScale, fittingMode, samplingMode,
339 false, cropToMask, useAtlas, textureHash, orientationCorrection,
341 cacheIndex = mTextureInfoContainer.size() - 1u;
343 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
344 url.GetUrl().c_str(), observer, cacheIndex, textureId );
347 // The below code path is common whether we are using the cache or not.
348 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
349 // or a new TextureInfo just created.
350 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
351 textureInfo.maskTextureId = maskTextureId;
352 textureInfo.storageType = storageType;
353 textureInfo.orientationCorrection = orientationCorrection;
355 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
356 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
357 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
358 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
359 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
361 // Force reloading of texture by setting loadState unless already loading or cancelled.
362 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
363 TextureManager::CANCELLED != textureInfo.loadState )
365 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
366 url.GetUrl().c_str(), observer, cacheIndex, textureId );
367 textureInfo.loadState = TextureManager::NOT_STARTED;
370 // Check if we should add the observer.
371 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
372 switch( textureInfo.loadState )
374 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
375 case TextureManager::NOT_STARTED:
377 LoadTexture( textureInfo );
378 ObserveTexture( textureInfo, observer );
381 case TextureManager::LOADING:
383 ObserveTexture( textureInfo, observer );
386 case TextureManager::UPLOADED:
390 // The Texture has already loaded. The other observers have already been notified.
391 // We need to send a "late" loaded notification for this observer.
392 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
393 textureInfo.useAtlas, textureInfo.atlasRect,
394 textureInfo.preMultiplied );
398 case TextureManager::CANCELLED:
400 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
401 // (it's ref count has already been incremented, above)
402 textureInfo.loadState = TextureManager::LOADING;
403 ObserveTexture( textureInfo, observer );
406 case TextureManager::LOAD_FINISHED:
407 case TextureManager::WAITING_FOR_MASK:
408 // Loading has already completed. Do nothing.
412 // Return the TextureId for which this Texture can now be referenced by externally.
416 void TextureManager::Remove( const TextureManager::TextureId textureId )
418 int textureInfoIndex = GetCacheIndexFromId( textureId );
419 if( textureInfoIndex != INVALID_INDEX )
421 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
423 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
424 textureId, textureInfoIndex,
425 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
426 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
427 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
428 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
430 // Decrement the reference count and check if this is the last user of this Texture.
431 if( --textureInfo.referenceCount <= 0 )
433 // This is the last remove for this Texture.
434 textureInfo.referenceCount = 0;
435 bool removeTextureInfo = false;
437 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
438 if( textureInfo.loadState == UPLOADED )
440 if( textureInfo.atlas )
442 textureInfo.atlas.Remove( textureInfo.atlasRect );
444 removeTextureInfo = true;
446 else if( textureInfo.loadState == LOADING )
448 // We mark the textureInfo for removal.
449 // Once the load has completed, this method will be called again.
450 textureInfo.loadState = CANCELLED;
454 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
455 removeTextureInfo = true;
458 // If the state allows us to remove the TextureInfo data, we do so.
459 if( removeTextureInfo )
461 // Permanently remove the textureInfo struct.
462 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
468 const VisualUrl& TextureManager::GetVisualUrl( TextureId textureId )
470 int cacheIndex = GetCacheIndexFromId( textureId );
471 DALI_ASSERT_DEBUG( cacheIndex != INVALID_CACHE_INDEX && "TextureId out of range");
473 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
474 return cachedTextureInfo.url;
477 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
479 LoadState loadState = TextureManager::NOT_STARTED;
481 int cacheIndex = GetCacheIndexFromId( textureId );
482 if( cacheIndex != INVALID_CACHE_INDEX )
484 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
485 loadState = cachedTextureInfo.loadState;
489 for( auto&& elem : mExternalTextures )
491 if( elem.textureId == textureId )
493 loadState = LoadState::UPLOADED;
501 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
503 LoadState loadState = TextureManager::NOT_STARTED;
505 int cacheIndex = GetCacheIndexFromId( textureId );
506 if( cacheIndex != INVALID_CACHE_INDEX )
508 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
509 loadState = cachedTextureInfo.loadState;
515 TextureSet TextureManager::GetTextureSet( TextureId textureId )
517 TextureSet textureSet;// empty handle
519 int cacheIndex = GetCacheIndexFromId( textureId );
520 if( cacheIndex != INVALID_CACHE_INDEX )
522 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
523 textureSet = cachedTextureInfo.textureSet;
527 for( auto&& elem : mExternalTextures )
529 if( elem.textureId == textureId )
531 textureSet = elem.textureSet;
539 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
541 TextureManager::ExternalTextureInfo info;
542 info.textureId = GenerateUniqueTextureId();
543 info.textureSet = textureSet;
544 mExternalTextures.emplace_back( info );
545 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
548 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
550 if( url.size() > 0u )
552 // get the location from the Url
553 VisualUrl parseUrl( url );
554 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
556 std::string location = parseUrl.GetLocation();
557 if( location.size() > 0u )
559 TextureId id = std::stoi( location );
560 const auto end = mExternalTextures.end();
561 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
563 if( iter->textureId == id )
565 auto textureSet = iter->textureSet;
566 mExternalTextures.erase( iter );
576 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
580 if( textureInfo.loadState == NOT_STARTED )
582 textureInfo.loadState = LOADING;
584 if( !textureInfo.loadSynchronously )
586 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
587 auto loadingHelperIt = loadersContainer.GetNext();
588 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
589 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
590 textureInfo.desiredSize, textureInfo.fittingMode,
591 textureInfo.samplingMode, textureInfo.orientationCorrection );
598 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
599 TextureUploadObserver* observer )
603 textureInfo.observerList.PushBack( observer );
604 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
608 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
609 Devel::PixelBuffer pixelBuffer )
611 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
613 if( loadingContainer.size() >= 1u )
615 AsyncLoadingInfo loadingInfo = loadingContainer.front();
617 if( loadingInfo.loadId == id )
619 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
620 if( cacheIndex != INVALID_CACHE_INDEX )
622 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
624 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
626 if( textureInfo.loadState != CANCELLED )
628 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
629 PostLoad( textureInfo, pixelBuffer );
633 Remove( textureInfo.textureId );
638 loadingContainer.pop_front();
642 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
644 // Was the load successful?
645 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
647 // No atlas support for now
648 textureInfo.useAtlas = NO_ATLAS;
650 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
652 // If there is a mask texture ID associated with this texture, then apply the mask
653 // if it's already loaded. If it hasn't, and the mask is still loading,
654 // wait for the mask to finish loading.
655 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
657 LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
658 if( maskLoadState == LOADING )
660 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
661 textureInfo.loadState = WAITING_FOR_MASK;
663 else if( maskLoadState == LOAD_FINISHED )
665 ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
666 UploadTexture( pixelBuffer, textureInfo );
667 NotifyObservers( textureInfo, true );
672 UploadTexture( pixelBuffer, textureInfo );
673 NotifyObservers( textureInfo, true );
678 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
679 textureInfo.loadState = LOAD_FINISHED;
681 // Check if there was another texture waiting for this load to complete
682 // (e.g. if this was an image mask, and its load is on a different thread)
683 CheckForWaitingTexture( textureInfo );
688 DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
689 // @todo If the load was unsuccessful, upload the broken image.
690 textureInfo.loadState = LOAD_FAILED;
691 CheckForWaitingTexture( textureInfo );
692 NotifyObservers( textureInfo, false );
696 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
698 // Search the cache, checking if any texture has this texture id as a
700 const unsigned int size = mTextureInfoContainer.size();
702 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
704 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
705 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
707 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
708 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
709 textureInfo.pixelBuffer.Reset();
711 if( maskTextureInfo.loadState == LOAD_FINISHED )
713 ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
714 UploadTexture( pixelBuffer, textureInfo );
715 NotifyObservers( textureInfo, true );
719 DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
720 textureInfo.loadState = LOAD_FAILED;
721 NotifyObservers( textureInfo, false );
727 void TextureManager::ApplyMask(
728 Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
729 float contentScale, bool cropToMask )
731 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
732 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
733 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
737 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
739 if( textureInfo.useAtlas != USE_ATLAS )
741 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
743 // If the texture doesn't have an alpha channel, can't pre-multiply it.
744 // Ensure that we don't change the load parameter (it's used for hashing), and instead set
745 // the status for use in the observer.
746 auto preMultiply = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
747 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
748 PreMultiply( pixelBuffer, preMultiply );
749 textureInfo.preMultiplied = (preMultiply == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
751 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
752 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
754 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
755 texture.Upload( pixelData );
756 if ( ! textureInfo.textureSet )
758 textureInfo.textureSet = TextureSet::New();
760 textureInfo.textureSet.SetTexture( 0u, texture );
763 // Update the load state.
764 // Note: This is regardless of success as we care about whether a
765 // load attempt is in progress or not. If unsuccessful, a broken
766 // image is still loaded.
767 textureInfo.loadState = UPLOADED;
770 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
772 TextureId textureId = textureInfo.textureId;
774 // If there is an observer: Notify the load is complete, whether successful or not,
775 // and erase it from the list
776 unsigned int observerCount = textureInfo.observerList.Count();
777 TextureInfo* info = &textureInfo;
779 while( observerCount )
781 TextureUploadObserver* observer = info->observerList[0];
783 // During UploadComplete() a Control ResourceReady() signal is emitted.
784 // During that signal the app may add remove /add Textures (e.g. via
785 // ImageViews). At this point no more observers can be added to the
786 // observerList, because textureInfo.loadState = UPLOADED. However it is
787 // possible for observers to be removed, hence we check the observer list
788 // count every iteration.
790 // The reference to the textureInfo struct can also become invalidated,
791 // because new load requests can modify the mTextureInfoContainer list
792 // (e.g. if more requests are pushed back it can cause the list to be
793 // resized invalidating the reference to the TextureInfo ).
794 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
795 info->preMultiplied );
796 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
798 // Get the textureInfo from the container again as it may have been
801 int textureInfoIndex = GetCacheIndexFromId( textureId );
802 if( textureInfoIndex == INVALID_CACHE_INDEX)
804 return; // texture has been removed - can stop.
807 info = &mTextureInfoContainer[ textureInfoIndex ];
808 observerCount = info->observerList.Count();
809 if ( observerCount > 0 )
811 // remove the observer that was just triggered if it's still in the list
812 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
816 info->observerList.Erase( j );
825 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
827 return mCurrentTextureId++;
830 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
832 const unsigned int size = mTextureInfoContainer.size();
834 for( unsigned int i = 0; i < size; ++i )
836 if( mTextureInfoContainer[i].textureId == textureId )
842 return INVALID_CACHE_INDEX;
845 TextureManager::TextureHash TextureManager::GenerateHash(
846 const std::string& url,
847 const ImageDimensions size,
848 const FittingMode::Type fittingMode,
849 const Dali::SamplingMode::Type samplingMode,
850 const UseAtlas useAtlas,
851 TextureId maskTextureId,
852 TextureManager::MultiplyOnLoad preMultiplyOnLoad)
854 std::string hashTarget( url );
855 const size_t urlLength = hashTarget.length();
856 const uint16_t width = size.GetWidth();
857 const uint16_t height = size.GetWidth();
859 // If either the width or height has been specified, include the resizing options in the hash
860 if( width != 0 || height != 0 )
862 // We are appending 5 bytes to the URL to form the hash input.
863 hashTarget.resize( urlLength + 5u );
864 char* hashTargetPtr = &( hashTarget[ urlLength ] );
866 // Pack the width and height (4 bytes total).
867 *hashTargetPtr++ = size.GetWidth() & 0xff;
868 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
869 *hashTargetPtr++ = size.GetHeight() & 0xff;
870 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
872 // Bit-pack the FittingMode, SamplingMode and atlasing.
873 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
874 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
878 // We are not including sizing information, but we still need an extra byte for atlasing.
879 hashTarget.resize( urlLength + 1u );
880 // Add the atlasing to the hash input.
881 hashTarget[ urlLength ] = useAtlas;
884 if( maskTextureId != INVALID_TEXTURE_ID )
886 auto textureIdIndex = hashTarget.length();
887 hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
888 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
890 // Append the texture id to the end of the URL byte by byte:
891 // (to avoid SIGBUS / alignment issues)
892 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
894 *hashTargetPtr++ = maskTextureId & 0xff;
895 maskTextureId >>= 8u;
899 auto premultipliedIndex = hashTarget.length();
900 hashTarget.resize( premultipliedIndex + 1 );
901 switch( preMultiplyOnLoad )
903 case TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD:
905 hashTarget[ premultipliedIndex ] = 't';
908 case TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY:
910 hashTarget[ premultipliedIndex ] = 'f';
915 return Dali::CalculateHash( hashTarget );
918 int TextureManager::FindCachedTexture(
919 const TextureManager::TextureHash hash,
920 const std::string& url,
921 const ImageDimensions size,
922 const FittingMode::Type fittingMode,
923 const Dali::SamplingMode::Type samplingMode,
925 TextureId maskTextureId,
926 TextureManager::MultiplyOnLoad preMultiplyOnLoad )
928 // Default to an invalid ID, in case we do not find a match.
929 int cacheIndex = INVALID_CACHE_INDEX;
931 // Iterate through our hashes to find a match.
932 const unsigned int count = mTextureInfoContainer.size();
933 for( unsigned int i = 0u; i < count; ++i )
935 if( mTextureInfoContainer[i].hash == hash )
937 // We have a match, now we check all the original parameters in case of a hash collision.
938 TextureInfo& textureInfo( mTextureInfoContainer[i] );
939 auto multiplyOnLoad = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
940 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
942 if( ( url == textureInfo.url.GetUrl() ) &&
943 ( useAtlas == textureInfo.useAtlas ) &&
944 ( maskTextureId == textureInfo.maskTextureId ) &&
945 ( size == textureInfo.desiredSize ) &&
946 ( preMultiplyOnLoad == multiplyOnLoad ) &&
947 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
948 ( fittingMode == textureInfo.fittingMode &&
949 samplingMode == textureInfo.samplingMode ) ) )
951 // The found Texture is a match.
961 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
963 const unsigned int count = mTextureInfoContainer.size();
964 for( unsigned int i = 0; i < count; ++i )
966 TextureInfo& textureInfo( mTextureInfoContainer[i] );
967 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
968 j != textureInfo.observerList.End(); )
972 j = textureInfo.observerList.Erase( j );
983 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
984 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
985 AsyncLoadingInfoContainerType())
989 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
990 const VisualUrl& url,
991 ImageDimensions desiredSize,
992 FittingMode::Type fittingMode,
993 SamplingMode::Type samplingMode,
994 bool orientationCorrection)
996 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
997 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
998 mLoadingInfoContainer.back().loadId = id;
1001 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1002 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1006 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1007 Toolkit::AsyncImageLoader loader,
1008 TextureManager& textureManager,
1009 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1011 mTextureManager(textureManager),
1012 mLoadingInfoContainer(std::move(loadingInfoContainer))
1014 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1015 this, &AsyncLoadingHelper::AsyncLoadComplete);
1018 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1019 Devel::PixelBuffer pixelBuffer)
1021 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1024 } // namespace Internal
1026 } // namespace Toolkit