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::strtol(numberString, nullptr, 10) : 0;
51 return (numberOfThreads > 0) ? numberOfThreads : defaultValue;
54 size_t GetNumberOfLocalLoaderThreads()
56 return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
59 size_t GetNumberOfRemoteLoaderThreads()
61 return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
79 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_TEXTURE_MANAGER" );
82 const uint32_t DEFAULT_ATLAS_SIZE( 1024u ); ///< This size can fit 8 by 8 images of average size 128 * 128
83 const Vector4 FULL_ATLAS_RECT( 0.0f, 0.0f, 1.0f, 1.0f ); ///< UV Rectangle that covers the full Texture
84 const char * const BROKEN_IMAGE_URL( DALI_IMAGE_DIR "broken.png" ); ///< URL For the broken image placeholder
85 const int INVALID_INDEX( -1 ); ///< Invalid index used to represent a non-existant TextureInfo struct
86 const int INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index
88 } // Anonymous namespace
90 TextureManager::MaskingData::MaskingData()
92 mAlphaMaskId( INVALID_TEXTURE_ID ),
93 mContentScaleFactor( 1.0f ),
98 TextureManager::TextureManager()
99 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
100 mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
101 mCurrentTextureId( 0 )
105 TextureSet TextureManager::LoadTexture(
106 VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
107 Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
108 bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
109 bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU,
110 Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
111 AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
112 TextureManager::ReloadPolicy reloadPolicy )
114 TextureSet textureSet;
116 loadingStatus = false;
117 textureRect = FULL_ATLAS_RECT;
119 if( VisualUrl::TEXTURE == url.GetProtocolType())
121 std::string location = url.GetLocation();
122 if( location.size() > 0u )
124 TextureId id = std::stoi( location );
125 for( auto&& elem : mExternalTextures )
127 if( elem.textureId == id )
129 return elem.textureSet;
134 else if( synchronousLoading )
139 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
140 orientationCorrection );
143 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
149 textureSet = TextureSet::New();
150 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( BROKEN_IMAGE_URL );
153 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
155 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
156 data.GetWidth(), data.GetHeight() );
157 texture.Upload( data );
158 textureSet = TextureSet::New();
159 textureSet.SetTexture( 0u, texture );
163 if( atlasingStatus ) // attempt atlasing
165 textureSet = imageAtlasManager->Add( textureRect, data );
167 if( !textureSet ) // big image, no atlasing or atlasing failed
169 atlasingStatus = false;
170 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
171 data.GetWidth(), data.GetHeight() );
172 texture.Upload( data );
173 textureSet = TextureSet::New();
174 textureSet.SetTexture( 0u, texture );
180 loadingStatus = true;
183 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver );
185 if( !textureSet ) // big image, no atlasing or atlasing failed
187 atlasingStatus = false;
190 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
191 textureObserver, orientationCorrection, reloadPolicy );
195 textureId = RequestLoad( url,
196 maskInfo->mAlphaMaskId,
197 maskInfo->mContentScaleFactor,
199 fittingMode, samplingMode,
200 TextureManager::NO_ATLAS,
201 maskInfo->mCropToMask,
203 orientationCorrection,
207 TextureManager::LoadState loadState = GetTextureState( textureId );
208 loadingStatus = ( loadState == TextureManager::LOADING );
210 if( loadState == TextureManager::UPLOADED )
212 // UploadComplete has already been called - keep the same texture set
213 textureSet = GetTextureSet( textureId );
218 if( ! atlasingStatus && textureSet )
220 Sampler sampler = Sampler::New();
221 sampler.SetWrapMode( wrapModeU, wrapModeV );
222 textureSet.SetSampler( 0u, sampler );
228 TextureManager::TextureId TextureManager::RequestLoad(
229 const VisualUrl& url,
230 const ImageDimensions desiredSize,
231 FittingMode::Type fittingMode,
232 Dali::SamplingMode::Type samplingMode,
233 const UseAtlas useAtlas,
234 TextureUploadObserver* observer,
235 bool orientationCorrection,
236 TextureManager::ReloadPolicy reloadPolicy )
238 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
239 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy );
242 TextureManager::TextureId TextureManager::RequestLoad(
243 const VisualUrl& url,
244 TextureId maskTextureId,
246 const ImageDimensions desiredSize,
247 FittingMode::Type fittingMode,
248 Dali::SamplingMode::Type samplingMode,
249 const UseAtlas useAtlas,
251 TextureUploadObserver* observer,
252 bool orientationCorrection,
253 TextureManager::ReloadPolicy reloadPolicy )
255 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
256 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy );
259 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
261 // Use the normal load procedure to get the alpha mask.
262 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
263 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
264 TextureManager::ReloadPolicy::CACHED );
267 TextureManager::TextureId TextureManager::RequestLoadInternal(
268 const VisualUrl& url,
269 TextureId maskTextureId,
271 const ImageDimensions desiredSize,
272 FittingMode::Type fittingMode,
273 Dali::SamplingMode::Type samplingMode,
276 StorageType storageType,
277 TextureUploadObserver* observer,
278 bool orientationCorrection,
279 TextureManager::ReloadPolicy reloadPolicy )
281 // First check if the requested Texture is cached.
282 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
285 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
287 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
288 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
291 // Check if the requested Texture exists in the cache.
292 if( cacheIndex != INVALID_CACHE_INDEX )
294 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
296 // Mark this texture being used by another client resource. Forced reload would replace the current texture
297 // without the need for incrementing the reference count.
298 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
300 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
301 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
302 url.GetUrl().c_str(), observer, cacheIndex, textureId );
305 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
307 // We need a new Texture.
308 textureId = GenerateUniqueTextureId();
309 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
310 desiredSize, contentScale, fittingMode, samplingMode,
311 false, cropToMask, useAtlas, textureHash, orientationCorrection ) );
312 cacheIndex = mTextureInfoContainer.size() - 1u;
314 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
315 url.GetUrl().c_str(), observer, cacheIndex, textureId );
318 // The below code path is common whether we are using the cache or not.
319 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
320 // or a new TextureInfo just created.
321 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
322 textureInfo.maskTextureId = maskTextureId;
323 textureInfo.storageType = storageType;
324 textureInfo.orientationCorrection = orientationCorrection;
326 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
327 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
328 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
329 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
330 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
332 // Force reloading of texture by setting loadState unless already loading or cancelled.
333 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
334 TextureManager::CANCELLED != textureInfo.loadState )
336 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
337 url.GetUrl().c_str(), observer, cacheIndex, textureId );
338 textureInfo.loadState = TextureManager::NOT_STARTED;
341 // Check if we should add the observer.
342 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
343 switch( textureInfo.loadState )
345 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
346 case TextureManager::NOT_STARTED:
348 LoadTexture( textureInfo );
349 ObserveTexture( textureInfo, observer );
352 case TextureManager::LOADING:
354 ObserveTexture( textureInfo, observer );
357 case TextureManager::UPLOADED:
361 // The Texture has already loaded. The other observers have already been notified.
362 // We need to send a "late" loaded notification for this observer.
363 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
364 textureInfo.useAtlas, textureInfo.atlasRect );
368 case TextureManager::CANCELLED:
370 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
371 // (it's ref count has already been incremented, above)
372 textureInfo.loadState = TextureManager::LOADING;
373 ObserveTexture( textureInfo, observer );
376 case TextureManager::LOAD_FINISHED:
377 case TextureManager::WAITING_FOR_MASK:
378 // Loading has already completed. Do nothing.
382 // Return the TextureId for which this Texture can now be referenced by externally.
386 void TextureManager::Remove( const TextureManager::TextureId textureId )
388 int textureInfoIndex = GetCacheIndexFromId( textureId );
389 if( textureInfoIndex != INVALID_INDEX )
391 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
393 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
394 textureId, textureInfoIndex,
395 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
396 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
397 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
398 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
400 // Decrement the reference count and check if this is the last user of this Texture.
401 if( --textureInfo.referenceCount <= 0 )
403 // This is the last remove for this Texture.
404 textureInfo.referenceCount = 0;
405 bool removeTextureInfo = false;
407 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
408 if( textureInfo.loadState == UPLOADED )
410 if( textureInfo.atlas )
412 textureInfo.atlas.Remove( textureInfo.atlasRect );
414 removeTextureInfo = true;
416 else if( textureInfo.loadState == LOADING )
418 // We mark the textureInfo for removal.
419 // Once the load has completed, this method will be called again.
420 textureInfo.loadState = CANCELLED;
424 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
425 removeTextureInfo = true;
428 // If the state allows us to remove the TextureInfo data, we do so.
429 if( removeTextureInfo )
431 // Permanently remove the textureInfo struct.
432 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
438 const VisualUrl& TextureManager::GetVisualUrl( TextureId textureId )
440 int cacheIndex = GetCacheIndexFromId( textureId );
441 DALI_ASSERT_DEBUG( cacheIndex != INVALID_CACHE_INDEX && "TextureId out of range");
443 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
444 return cachedTextureInfo.url;
447 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
449 LoadState loadState = TextureManager::NOT_STARTED;
451 int cacheIndex = GetCacheIndexFromId( textureId );
452 if( cacheIndex != INVALID_CACHE_INDEX )
454 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
455 loadState = cachedTextureInfo.loadState;
460 TextureSet TextureManager::GetTextureSet( TextureId textureId )
462 TextureSet textureSet;// empty handle
464 int cacheIndex = GetCacheIndexFromId( textureId );
465 if( cacheIndex != INVALID_CACHE_INDEX )
467 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
468 textureSet = cachedTextureInfo.textureSet;
473 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
475 TextureManager::ExternalTextureInfo info;
476 info.textureId = GenerateUniqueTextureId();
477 info.textureSet = textureSet;
478 mExternalTextures.emplace_back( info );
479 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
482 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
484 if( url.size() > 0u )
486 // get the location from the Url
487 VisualUrl parseUrl( url );
488 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
490 std::string location = parseUrl.GetLocation();
491 if( location.size() > 0u )
493 TextureId id = std::stoi( location );
494 const auto end = mExternalTextures.end();
495 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
497 if( iter->textureId == id )
499 auto textureSet = iter->textureSet;
500 mExternalTextures.erase( iter );
510 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
514 if( textureInfo.loadState == NOT_STARTED )
516 textureInfo.loadState = LOADING;
518 if( !textureInfo.loadSynchronously )
520 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
521 auto loadingHelperIt = loadersContainer.GetNext();
522 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
523 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
524 textureInfo.desiredSize, textureInfo.fittingMode,
525 textureInfo.samplingMode, textureInfo.orientationCorrection );
532 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
533 TextureUploadObserver* observer )
537 textureInfo.observerList.PushBack( observer );
538 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
542 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
543 Devel::PixelBuffer pixelBuffer )
545 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
547 if( loadingContainer.size() >= 1u )
549 AsyncLoadingInfo loadingInfo = loadingContainer.front();
551 if( loadingInfo.loadId == id )
553 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
554 if( cacheIndex != INVALID_CACHE_INDEX )
556 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
558 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
560 if( textureInfo.loadState != CANCELLED )
562 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
563 PostLoad( textureInfo, pixelBuffer );
567 Remove( textureInfo.textureId );
572 loadingContainer.pop_front();
576 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
578 // Was the load successful?
579 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
581 // No atlas support for now
582 textureInfo.useAtlas = NO_ATLAS;
584 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
586 // If there is a mask texture ID associated with this texture, then apply the mask
587 // if it's already loaded. If it hasn't, and the mask is still loading,
588 // wait for the mask to finish loading.
589 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
591 LoadState maskLoadState = GetTextureState( textureInfo.maskTextureId );
592 if( maskLoadState == LOADING )
594 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
595 textureInfo.loadState = WAITING_FOR_MASK;
597 else if( maskLoadState == LOAD_FINISHED )
599 ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
600 UploadTexture( pixelBuffer, textureInfo );
601 NotifyObservers( textureInfo, true );
606 UploadTexture( pixelBuffer, textureInfo );
607 NotifyObservers( textureInfo, true );
612 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
613 textureInfo.loadState = LOAD_FINISHED;
615 // Check if there was another texture waiting for this load to complete
616 // (e.g. if this was an image mask, and its load is on a different thread)
617 CheckForWaitingTexture( textureInfo );
622 DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
623 // @todo If the load was unsuccessful, upload the broken image.
624 textureInfo.loadState = LOAD_FAILED;
625 CheckForWaitingTexture( textureInfo );
626 NotifyObservers( textureInfo, false );
630 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
632 // Search the cache, checking if any texture has this texture id as a
634 const unsigned int size = mTextureInfoContainer.size();
636 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
638 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
639 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
641 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
642 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
643 textureInfo.pixelBuffer.Reset();
645 if( maskTextureInfo.loadState == LOAD_FINISHED )
647 ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
648 UploadTexture( pixelBuffer, textureInfo );
649 NotifyObservers( textureInfo, true );
653 DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
654 textureInfo.loadState = LOAD_FAILED;
655 NotifyObservers( textureInfo, false );
661 void TextureManager::ApplyMask(
662 Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
663 float contentScale, bool cropToMask )
665 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
666 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
667 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
670 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
672 if( textureInfo.useAtlas != USE_ATLAS )
674 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
676 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
677 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
678 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
679 texture.Upload( pixelData );
680 if ( ! textureInfo.textureSet )
682 textureInfo.textureSet = TextureSet::New();
684 textureInfo.textureSet.SetTexture( 0u, texture );
687 // Update the load state.
688 // Note: This is regardless of success as we care about whether a
689 // load attempt is in progress or not. If unsuccessful, a broken
690 // image is still loaded.
691 textureInfo.loadState = UPLOADED;
694 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
696 TextureId textureId = textureInfo.textureId;
698 // If there is an observer: Notify the load is complete, whether successful or not,
699 // and erase it from the list
700 unsigned int observerCount = textureInfo.observerList.Count();
701 TextureInfo* info = &textureInfo;
703 while( observerCount )
705 TextureUploadObserver* observer = info->observerList[0];
707 // During UploadComplete() a Control ResourceReady() signal is emitted.
708 // During that signal the app may add remove /add Textures (e.g. via
709 // ImageViews). At this point no more observers can be added to the
710 // observerList, because textureInfo.loadState = UPLOADED. However it is
711 // possible for observers to be removed, hence we check the observer list
712 // count every iteration.
714 // The reference to the textureInfo struct can also become invalidated,
715 // because new load requests can modify the mTextureInfoContainer list
716 // (e.g. if more requests are pushed back it can cause the list to be
717 // resized invalidating the reference to the TextureInfo ).
718 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect );
719 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
721 // Get the textureInfo from the container again as it may have been
724 int textureInfoIndex = GetCacheIndexFromId( textureId );
725 if( textureInfoIndex == INVALID_CACHE_INDEX)
727 return; // texture has been removed - can stop.
730 info = &mTextureInfoContainer[ textureInfoIndex ];
731 observerCount = info->observerList.Count();
732 if ( observerCount > 0 )
734 // remove the observer that was just triggered if it's still in the list
735 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
739 info->observerList.Erase( j );
748 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
750 return mCurrentTextureId++;
753 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
755 const unsigned int size = mTextureInfoContainer.size();
757 for( unsigned int i = 0; i < size; ++i )
759 if( mTextureInfoContainer[i].textureId == textureId )
765 DALI_LOG_WARNING( "Cannot locate TextureId: %d\n", textureId );
766 return INVALID_CACHE_INDEX;
769 TextureManager::TextureHash TextureManager::GenerateHash(
770 const std::string& url,
771 const ImageDimensions size,
772 const FittingMode::Type fittingMode,
773 const Dali::SamplingMode::Type samplingMode,
774 const UseAtlas useAtlas,
775 TextureId maskTextureId )
777 std::string hashTarget( url );
778 const size_t urlLength = hashTarget.length();
779 const uint16_t width = size.GetWidth();
780 const uint16_t height = size.GetWidth();
782 // If either the width or height has been specified, include the resizing options in the hash
783 if( width != 0 || height != 0 )
785 // We are appending 5 bytes to the URL to form the hash input.
786 hashTarget.resize( urlLength + 5u );
787 char* hashTargetPtr = &( hashTarget[ urlLength ] );
789 // Pack the width and height (4 bytes total).
790 *hashTargetPtr++ = size.GetWidth() & 0xff;
791 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
792 *hashTargetPtr++ = size.GetHeight() & 0xff;
793 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
795 // Bit-pack the FittingMode, SamplingMode and atlasing.
796 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
797 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
801 // We are not including sizing information, but we still need an extra byte for atlasing.
802 hashTarget.resize( urlLength + 1u );
803 // Add the atlasing to the hash input.
804 hashTarget[ urlLength ] = useAtlas;
807 if( maskTextureId != INVALID_TEXTURE_ID )
809 hashTarget.resize( urlLength + sizeof( TextureId ) );
810 TextureId* hashTargetPtr = reinterpret_cast<TextureId*>(&( hashTarget[ urlLength ] ));
812 // Append the hash target to the end of the URL byte by byte:
813 // (to avoid SIGBUS / alignment issues)
814 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
816 *hashTargetPtr++ = maskTextureId & 0xff;
817 maskTextureId >>= 8u;
821 return Dali::CalculateHash( hashTarget );
824 int TextureManager::FindCachedTexture(
825 const TextureManager::TextureHash hash,
826 const std::string& url,
827 const ImageDimensions size,
828 const FittingMode::Type fittingMode,
829 const Dali::SamplingMode::Type samplingMode,
831 TextureId maskTextureId)
833 // Default to an invalid ID, in case we do not find a match.
834 int cacheIndex = INVALID_CACHE_INDEX;
836 // Iterate through our hashes to find a match.
837 const unsigned int count = mTextureInfoContainer.size();
838 for( unsigned int i = 0u; i < count; ++i )
840 if( mTextureInfoContainer[i].hash == hash )
842 // We have a match, now we check all the original parameters in case of a hash collision.
843 TextureInfo& textureInfo( mTextureInfoContainer[i] );
845 if( ( url == textureInfo.url.GetUrl() ) &&
846 ( useAtlas == textureInfo.useAtlas ) &&
847 ( maskTextureId == textureInfo.maskTextureId ) &&
848 ( size == textureInfo.desiredSize ) &&
849 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
850 ( fittingMode == textureInfo.fittingMode &&
851 samplingMode == textureInfo.samplingMode ) ) )
853 // The found Texture is a match.
863 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
865 const unsigned int count = mTextureInfoContainer.size();
866 for( unsigned int i = 0; i < count; ++i )
868 TextureInfo& textureInfo( mTextureInfoContainer[i] );
869 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
870 j != textureInfo.observerList.End(); )
874 j = textureInfo.observerList.Erase( j );
884 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
885 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
886 AsyncLoadingInfoContainerType())
890 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
891 const VisualUrl& url,
892 ImageDimensions desiredSize,
893 FittingMode::Type fittingMode,
894 SamplingMode::Type samplingMode,
895 bool orientationCorrection)
897 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
898 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
899 mLoadingInfoContainer.back().loadId = id;
902 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
903 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
907 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
908 Toolkit::AsyncImageLoader loader,
909 TextureManager& textureManager,
910 AsyncLoadingInfoContainerType&& loadingInfoContainer)
912 mTextureManager(textureManager),
913 mLoadingInfoContainer(std::move(loadingInfoContainer))
915 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
916 this, &AsyncLoadingHelper::AsyncLoadComplete);
919 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
920 Devel::PixelBuffer pixelBuffer)
922 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
925 } // namespace Internal
927 } // namespace Toolkit