From: David Steele Date: Fri, 19 Mar 2021 09:12:36 +0000 (+0000) Subject: Merge "Change BuildRequires of dali2-toolkit to Requires" into devel/master X-Git-Tag: dali_2.0.19~13 X-Git-Url: http://review.tizen.org/git/?p=platform%2Fcore%2Fuifw%2Fdali-toolkit.git;a=commitdiff_plain;h=b8da2e53925b9abb9fa362560069e8ca4aa62f81;hp=88f5c28e662678cc93e13a2bcc462ff2446012c1 Merge "Change BuildRequires of dali2-toolkit to Requires" into devel/master --- diff --git a/automated-tests/src/dali-toolkit-internal/dali-toolkit-test-utils/dummy-visual.cpp b/automated-tests/src/dali-toolkit-internal/dali-toolkit-test-utils/dummy-visual.cpp index c1d0585..1d8d611 100644 --- a/automated-tests/src/dali-toolkit-internal/dali-toolkit-test-utils/dummy-visual.cpp +++ b/automated-tests/src/dali-toolkit-internal/dali-toolkit-test-utils/dummy-visual.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ DummyVisualPtr DummyVisual::New( const Property::Map& properties ) VisualFactoryCache* factoryCache = new VisualFactoryCache(false); DummyVisualPtr dummyVisualPtr( new DummyVisual( *factoryCache ) ); - + dummyVisualPtr->Initialize(); return dummyVisualPtr; } @@ -43,6 +43,11 @@ DummyVisual::DummyVisual( VisualFactoryCache& factoryCache ) { } +void DummyVisual::OnInitialize() +{ + // Implement if required +} + void DummyVisual::DoCreatePropertyMap( Property::Map& map ) const { // Implement if required diff --git a/automated-tests/src/dali-toolkit-internal/dali-toolkit-test-utils/dummy-visual.h b/automated-tests/src/dali-toolkit-internal/dali-toolkit-test-utils/dummy-visual.h index ef4c37b..41b2c21 100644 --- a/automated-tests/src/dali-toolkit-internal/dali-toolkit-test-utils/dummy-visual.h +++ b/automated-tests/src/dali-toolkit-internal/dali-toolkit-test-utils/dummy-visual.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_TEST_DUMMY_VISUAL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,6 +75,7 @@ protected: DummyVisual( VisualFactoryCache& factoryCache ); + void OnInitialize() override; void DoCreatePropertyMap( Property::Map& map ) const override; void DoCreateInstancePropertyMap( Property::Map& map ) const override; void DoSetProperties( const Property::Map& propertyMap ) override; diff --git a/automated-tests/src/dali-toolkit-internal/utc-Dali-Text-ViewModel.cpp b/automated-tests/src/dali-toolkit-internal/utc-Dali-Text-ViewModel.cpp index f243f08..fc4f9ac 100755 --- a/automated-tests/src/dali-toolkit-internal/utc-Dali-Text-ViewModel.cpp +++ b/automated-tests/src/dali-toolkit-internal/utc-Dali-Text-ViewModel.cpp @@ -572,6 +572,24 @@ int UtcDaliTextViewModelElideText01(void) DALI_TEST_CHECK( NULL != glyphs ); DALI_TEST_CHECK( NULL != layouts ); + // When the ellipsis is enabled, at least a glyph has to be rendered. + // Even if the given width is too narrow for rendering an ellipsis glyph. + controller->SetText( "…" ); + Vector3 sizeEllipsis = controller->GetNaturalSize(); + controller->SetText( "A" ); + Vector3 sizeA = controller->GetNaturalSize(); + float testWidth = sizeA.width < sizeEllipsis.width ? sizeA.width : sizeEllipsis.width - 1.0; + + controller->SetText( "AB" ); + Vector3 sizeAB = controller->GetNaturalSize(); + + controller->Relayout( Size(testWidth, sizeAB.height) ); + + // Elide the glyphs. + model->ElideGlyphs(); + DALI_TEST_EQUALS( 1u, model->GetNumberOfGlyphs(), TEST_LOCATION ); + DALI_TEST_EQUALS( 1u, model->GetNumberOfLines(), TEST_LOCATION ); + tet_result(TET_PASS); END_TEST; } diff --git a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/dali-test-suite-utils.h b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/dali-test-suite-utils.h index a4b45c9..c6e63e7 100644 --- a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/dali-test-suite-utils.h +++ b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/dali-test-suite-utils.h @@ -2,7 +2,7 @@ #define DALI_TEST_SUITE_UTILS_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -417,25 +417,25 @@ inline void DALI_TEST_PRINT_ASSERT(DaliException& e) * @param expressions code to execute * @param except the exception expected in the assert */ -#define DALI_TEST_THROWS(expressions, except) \ - try \ - { \ - TestApplication::EnableLogging(false); \ - expressions; \ - TestApplication::EnableLogging(true); \ - fprintf(stderr, "Test failed in %s, expected exception: '%s' didn't occur\n", __FILELINE__, #except); \ - tet_result(TET_FAIL); \ - throw("TET_FAIL"); \ - } \ - catch(except &) \ - { \ - tet_result(TET_PASS); \ - } \ - catch(...) \ - { \ - fprintf(stderr, "Test failed in %s, unexpected exception\n", __FILELINE__); \ - tet_result(TET_FAIL); \ - throw; \ +#define DALI_TEST_THROWS(expressions, except) \ + try \ + { \ + TestApplication::EnableLogging(false); \ + expressions; \ + TestApplication::EnableLogging(true); \ + fprintf(stderr, "Test failed in %s, expected exception: '%s' didn't occur\n", __FILELINE__, #except); \ + tet_result(TET_FAIL); \ + throw("TET_FAIL"); \ + } \ + catch(except&) \ + { \ + tet_result(TET_PASS); \ + } \ + catch(...) \ + { \ + fprintf(stderr, "Test failed in %s, unexpected exception\n", __FILELINE__); \ + tet_result(TET_FAIL); \ + throw; \ } // Functor to test whether an Applied signal is emitted diff --git a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-vector-animation-renderer.cpp b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-vector-animation-renderer.cpp index b0075d2..18ce2ef 100755 --- a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-vector-animation-renderer.cpp +++ b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-vector-animation-renderer.cpp @@ -35,8 +35,8 @@ class VectorAnimationRenderer: public Dali::BaseObject { public: - VectorAnimationRenderer( const std::string& url ) - : mUrl( url ), + VectorAnimationRenderer() + : mUrl(), mRenderer(), mWidth( 0 ), mHeight( 0 ), @@ -57,6 +57,16 @@ public: mCount--; } + bool Load(const std::string& url) + { + mUrl = url; + if(mUrl == "invalid.json") + { + return false; + } + return true; + } + void SetRenderer( Dali::Renderer renderer ) { mRenderer = renderer; @@ -187,9 +197,9 @@ inline const VectorAnimationRenderer& GetImplementation( const Dali::VectorAnima /********************************* PUBLIC CLASS *******************************/ /********************************************************************************/ -VectorAnimationRenderer VectorAnimationRenderer::New( const std::string& url ) +VectorAnimationRenderer VectorAnimationRenderer::New() { - Internal::Adaptor::VectorAnimationRenderer* animationRenderer = new Internal::Adaptor::VectorAnimationRenderer( url ); + Internal::Adaptor::VectorAnimationRenderer* animationRenderer = new Internal::Adaptor::VectorAnimationRenderer(); return VectorAnimationRenderer( animationRenderer ); } @@ -222,6 +232,11 @@ void VectorAnimationRenderer::Finalize() { } +bool VectorAnimationRenderer::Load(const std::string& url) +{ + return Internal::Adaptor::GetImplementation( *this ).Load(url); +} + void VectorAnimationRenderer::SetRenderer( Renderer renderer ) { Internal::Adaptor::GetImplementation( *this ).SetRenderer( renderer ); diff --git a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-web-engine.cpp b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-web-engine.cpp index e5077fe..01b5ae5 100755 --- a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-web-engine.cpp +++ b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-web-engine.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,9 +23,10 @@ #include #include #include +#include +#include #include #include -#include #include namespace Dali @@ -41,27 +42,34 @@ class WebEngine; namespace { -static WebEngine* gInstance = NULL; + +// Generally only one WebEngine instance exists. +// If > 1, a new web engine has been created by CreateWindowSignal. +static WebEngine* gInstance = 0; static int gInstanceCount = 0; bool OnGoBack(); bool OnGoForward(); bool OnLoadUrl(); bool OnEvaluteJavaScript(); +bool OnJavaScriptAlert(); +bool OnJavaScriptConfirm(); +bool OnJavaScriptPrompt(); +bool OnScrollEdge(); bool OnClearHistory(); -static void ConnectToGlobalSignal( bool (*func)() ) +static void ConnectToGlobalSignal( bool ( *func )() ) { Dali::Timer timer = Dali::Timer::New( 0 ); timer.TickSignal().Connect( func ); } -static void DisconnectFromGlobalSignal( bool (*func)() ) +static void DisconnectFromGlobalSignal( bool ( *func )() ) { Dali::Timer timer = Dali::Timer::New( 0 ); timer.TickSignal().Disconnect( func ); } -} +} // namespace anonymous class MockWebEngineContext : public Dali::WebEngineContext { @@ -213,6 +221,18 @@ public: MockWebEngineSettings() : mockDefaultFontSize( 16 ), mockJavaScriptEnabled( true ), + mockAutoFittingEnabled ( true ), + mockPluginsEnabled ( true ), + mockPrivateBrowsingEnabled( true ), + mockLinkMagnifierEnabled( true ), + mockKeypadWithoutUserActionUsed( true ), + mockAutofillPasswordFormEnabled( true ), + mockFormCandidateDataEnabled( true ), + mockTextSelectionEnabled( true ), + mockTextAutosizingEnable( true ), + mockArrowScrollEnable( true ), + mockClipboardEnabled( true ), + mockImePanelEnabled( true ), mockImageLoadedAutomatically( true ), mockDefaultTextEncodingName() { @@ -238,6 +258,126 @@ public: mockJavaScriptEnabled = enabled; } + bool IsAutoFittingEnabled() const override + { + return mockAutoFittingEnabled; + } + + void EnableAutoFitting( bool enabled ) override + { + mockAutoFittingEnabled = enabled; + } + + bool ArePluginsEnabled() const override + { + return mockPluginsEnabled; + } + + void EnablePlugins( bool enabled ) override + { + mockPluginsEnabled = enabled; + } + + bool IsPrivateBrowsingEnabled() const override + { + return mockPrivateBrowsingEnabled; + } + + void EnablePrivateBrowsing( bool enabled ) override + { + mockPrivateBrowsingEnabled = enabled; + } + + bool IsLinkMagnifierEnabled() const override + { + return mockLinkMagnifierEnabled; + } + + void EnableLinkMagnifier( bool enabled ) override + { + mockLinkMagnifierEnabled = enabled; + } + + bool IsKeypadWithoutUserActionUsed() const override + { + return mockKeypadWithoutUserActionUsed; + } + + void UseKeypadWithoutUserAction( bool used ) override + { + mockKeypadWithoutUserActionUsed = used; + } + + bool IsAutofillPasswordFormEnabled() const override + { + return mockAutofillPasswordFormEnabled; + } + + void EnableAutofillPasswordForm( bool enabled ) override + { + mockAutofillPasswordFormEnabled = enabled; + } + + bool IsFormCandidateDataEnabled() const override + { + return mockFormCandidateDataEnabled; + } + + void EnableFormCandidateData( bool enabled ) override + { + mockFormCandidateDataEnabled = enabled; + } + + bool IsTextSelectionEnabled() const override + { + return mockTextSelectionEnabled; + } + + void EnableTextSelection( bool enabled ) override + { + mockTextSelectionEnabled = enabled; + } + + bool IsTextAutosizingEnabled() const override + { + return mockTextAutosizingEnable; + } + + void EnableTextAutosizing( bool enabled ) override + { + mockTextAutosizingEnable = enabled; + } + + bool IsArrowScrollEnabled() const override + { + return mockArrowScrollEnable; + } + + void EnableArrowScroll( bool enabled ) override + { + mockArrowScrollEnable = enabled; + } + + bool IsClipboardEnabled() const override + { + return mockClipboardEnabled; + } + + void EnableClipboard( bool enabled ) override + { + mockClipboardEnabled = enabled; + } + + bool IsImePanelEnabled() const override + { + return mockImePanelEnabled; + } + + void EnableImePanel( bool enabled ) override + { + mockImePanelEnabled = enabled; + } + bool AreImagesLoadedAutomatically() const override { return mockImageLoadedAutomatically; @@ -270,6 +410,18 @@ public: { } + void EnableCacheBuilder( bool enabled ) override + { + } + + void UseScrollbarThumbFocusNotifications( bool used ) override + { + } + + void EnableDoNotTrack( bool enabled ) override + { + } + void AllowFileAccessFromExternalUrl( bool allowed ) override { } @@ -281,6 +433,18 @@ public: private: int mockDefaultFontSize; bool mockJavaScriptEnabled; + bool mockAutoFittingEnabled; + bool mockPluginsEnabled; + bool mockPrivateBrowsingEnabled; + bool mockLinkMagnifierEnabled; + bool mockKeypadWithoutUserActionUsed; + bool mockAutofillPasswordFormEnabled; + bool mockFormCandidateDataEnabled; + bool mockTextSelectionEnabled; + bool mockTextAutosizingEnable; + bool mockArrowScrollEnable; + bool mockClipboardEnabled; + bool mockImePanelEnabled; bool mockImageLoadedAutomatically; std::string mockDefaultTextEncodingName; }; @@ -289,6 +453,11 @@ class WebEngine: public Dali::BaseObject { public: + using JavaScriptEvaluatedResultCallback = std::function; + using JavaScriptAlertCallback = std::function; + using JavaScriptConfirmCallback = std::function; + using JavaScriptPromptCallback = std::function; + WebEngine() : mUrl() , mCurrentPlusOnePos( 0 ) @@ -299,7 +468,10 @@ public: , mContentSize( 500, 500 ) { gInstanceCount++; - gInstance = this; + if ( gInstanceCount == 1 ) // only first web engine need be saved. + { + gInstance = this; + } mockWebEngineSettings = new MockWebEngineSettings(); mockWebEngineContext = new MockWebEngineContext(); @@ -312,7 +484,7 @@ public: gInstanceCount--; if( !gInstanceCount ) { - gInstance = NULL; + gInstance = 0; } delete mockWebEngineSettings; @@ -352,6 +524,37 @@ public: return mUrl; } + std::string GetTitle() const + { + return std::string("title"); + } + + Dali::PixelData GetFavicon() const + { + uint8_t* faviconData = new uint8_t[ 16 ]; + + faviconData[ 0 ] = 0xff; + faviconData[ 1 ] = 0x00; + faviconData[ 2 ] = 0x00; + faviconData[ 3 ] = 0xff; + faviconData[ 4 ] = 0xff; + faviconData[ 5 ] = 0x00; + faviconData[ 6 ] = 0x00; + faviconData[ 7 ] = 0xff; + faviconData[ 8 ] = 0xff; + faviconData[ 9 ] = 0x00; + faviconData[ 10 ] = 0x00; + faviconData[ 11 ] = 0xff; + faviconData[ 12 ] = 0xff; + faviconData[ 13 ] = 0x00; + faviconData[ 14 ] = 0x00; + faviconData[ 15 ] = 0xff; + + return Dali::PixelData::New( faviconData, 16, 2, 2, + Dali::Pixel::Format::RGBA8888, + Dali::PixelData::ReleaseFunction::DELETE_ARRAY ); + } + bool CanGoForward() const { return mHistory.size() > mCurrentPlusOnePos; @@ -384,6 +587,33 @@ public: } } + void RegisterJavaScriptAlertCallback( Dali::WebEnginePlugin::JavaScriptAlertCallback callback ) + { + if ( callback ) + { + ConnectToGlobalSignal( &OnJavaScriptAlert ); + mJavaScriptAlertCallback = callback; + } + } + + void RegisterJavaScriptConfirmCallback( Dali::WebEnginePlugin::JavaScriptConfirmCallback callback ) + { + if ( callback ) + { + ConnectToGlobalSignal( &OnJavaScriptConfirm ); + mJavaScriptConfirmCallback = callback; + } + } + + void RegisterJavaScriptPromptCallback( Dali::WebEnginePlugin::JavaScriptPromptCallback callback ) + { + if ( callback ) + { + ConnectToGlobalSignal( &OnJavaScriptPrompt ); + mJavaScriptPromptCallback = callback; + } + } + void ClearHistory() { ConnectToGlobalSignal( &OnClearHistory ); @@ -404,7 +634,7 @@ public: mScrollPosition += Dali::Vector2( dx, dy ); if ( mScrollPosition.y + mScrollSize.height > mContentSize.height ) { - gInstance->mScrollEdgeReachedSignal.Emit( Dali::WebEnginePlugin::ScrollEdge::BOTTOM ); + ConnectToGlobalSignal( &OnScrollEdge ); } } @@ -414,22 +644,19 @@ public: mScrollPosition.y = y; } - void GetScrollPosition( int& x, int& y ) const + Dali::Vector2 GetScrollPosition() const { - x = mScrollPosition.x; - y = mScrollPosition.y; + return mScrollPosition; } - void GetScrollSize( int& w, int& h ) const + Dali::Vector2 GetScrollSize() const { - w = mScrollSize.width; - h = mScrollSize.height; + return mScrollSize; } - void GetContentSize( int& w, int& h ) const + Dali::Vector2 GetContentSize() const { - w = mContentSize.width; - h = mContentSize.height; + return mContentSize; } Dali::WebEnginePlugin::WebEnginePageLoadSignalType& PageLoadStartedSignal() @@ -437,6 +664,11 @@ public: return mPageLoadStartedSignal; } + Dali::WebEnginePlugin::WebEnginePageLoadSignalType& PageLoadInProgressSignal() + { + return mPageLoadInProgressSignal; + } + Dali::WebEnginePlugin::WebEnginePageLoadSignalType& PageLoadFinishedSignal() { return mPageLoadFinishedSignal; @@ -452,14 +684,20 @@ public: return mScrollEdgeReachedSignal; } + Dali::WebEnginePlugin::WebEngineUrlChangedSignalType& UrlChangedSignal() + { + return mUrlChangedSignal; + } + std::string mUrl; std::vector< std::string > mHistory; size_t mCurrentPlusOnePos; std::string mUserAgent; Dali::WebEnginePlugin::WebEnginePageLoadSignalType mPageLoadStartedSignal; + Dali::WebEnginePlugin::WebEnginePageLoadSignalType mPageLoadInProgressSignal; Dali::WebEnginePlugin::WebEnginePageLoadSignalType mPageLoadFinishedSignal; Dali::WebEnginePlugin::WebEnginePageLoadErrorSignalType mPageLoadErrorSignal; - std::vector< std::function< void( const std::string& ) > > mResultCallbacks; + std::vector mResultCallbacks; bool mEvaluating; Dali::WebEnginePlugin::WebEngineScrollEdgeReachedSignalType mScrollEdgeReachedSignal; @@ -470,21 +708,13 @@ public: WebEngineContext* mockWebEngineContext; WebEngineCookieManager* mockWebEngineCookieManager; WebEngineSettings* mockWebEngineSettings; -}; + Dali::WebEnginePlugin::WebEngineUrlChangedSignalType mUrlChangedSignal; -inline WebEngine& GetImplementation( Dali::WebEngine& webEngine ) -{ - DALI_ASSERT_ALWAYS( webEngine && "WebEngine handle is empty." ); - BaseObject& handle = webEngine.GetBaseObject(); - return static_cast< Internal::Adaptor::WebEngine& >( handle ); -} + JavaScriptAlertCallback mJavaScriptAlertCallback; + JavaScriptConfirmCallback mJavaScriptConfirmCallback; + JavaScriptPromptCallback mJavaScriptPromptCallback; +}; -inline const WebEngine& GetImplementation( const Dali::WebEngine& webEngine ) -{ - DALI_ASSERT_ALWAYS( webEngine && "WebEngine handle is empty." ); - const BaseObject& handle = webEngine.GetBaseObject(); - return static_cast< const Internal::Adaptor::WebEngine& >( handle ); -} namespace { @@ -524,8 +754,22 @@ bool OnLoadUrl() gInstance->mHistory.push_back( gInstance->mUrl ); gInstance->mCurrentPlusOnePos++; gInstance->mPageLoadStartedSignal.Emit( gInstance->mUrl ); + gInstance->mPageLoadInProgressSignal.Emit( gInstance->mUrl ); gInstance->mPageLoadFinishedSignal.Emit( gInstance->mUrl ); + gInstance->mUrlChangedSignal.Emit( "http://new-test" ); + } + return false; +} + +bool OnScrollEdge() +{ + DisconnectFromGlobalSignal( &OnScrollEdge ); + + if( gInstance ) + { + gInstance->mScrollEdgeReachedSignal.Emit( Dali::WebEnginePlugin::ScrollEdge::BOTTOM ); } + return false; } @@ -544,11 +788,42 @@ bool OnEvaluteJavaScript() return false; } +bool OnJavaScriptAlert() +{ + DisconnectFromGlobalSignal( &OnJavaScriptAlert ); + if ( gInstance ) + { + gInstance->mJavaScriptAlertCallback( "this is an alert popup." ); + } + return false; +} + +bool OnJavaScriptConfirm() +{ + DisconnectFromGlobalSignal( &OnJavaScriptConfirm ); + if ( gInstance ) + { + gInstance->mJavaScriptConfirmCallback( "this is a confirm popup." ); + } + return false; +} + +bool OnJavaScriptPrompt() +{ + DisconnectFromGlobalSignal( &OnJavaScriptPrompt ); + if ( gInstance ) + { + gInstance->mJavaScriptPromptCallback( "this is a prompt pompt.", "" ); + } + return false; +} + bool OnClearHistory() { DisconnectFromGlobalSignal( &OnClearHistory ); - if( gInstance && gInstance->mCurrentPlusOnePos ) { + if( gInstance && gInstance->mCurrentPlusOnePos ) + { std::string url = gInstance->mHistory[ gInstance->mCurrentPlusOnePos - 1 ]; std::vector< std::string >().swap( gInstance->mHistory ); gInstance->mHistory.push_back( url ); @@ -556,13 +831,27 @@ bool OnClearHistory() } return false; } + } // namespace +inline WebEngine& GetImplementation( Dali::WebEngine& webEngine ) +{ + DALI_ASSERT_ALWAYS( webEngine && "WebEngine handle is empty." ); + BaseObject& handle = webEngine.GetBaseObject(); + return static_cast< Internal::Adaptor::WebEngine& >( handle ); +} + +inline const WebEngine& GetImplementation( const Dali::WebEngine& webEngine ) +{ + DALI_ASSERT_ALWAYS( webEngine && "WebEngine handle is empty." ); + const BaseObject& handle = webEngine.GetBaseObject(); + return static_cast< const Internal::Adaptor::WebEngine& >( handle ); +} + } // namespace Adaptor } // namespace Internal - // Dali::WebEngine Implementation WebEngine::WebEngine() { @@ -604,6 +893,10 @@ void WebEngine::Create( int width, int height, const std::string& locale, const { } +void WebEngine::Create( int width, int height, int argc, char** argv ) +{ +} + void WebEngine::Destroy() { } @@ -633,6 +926,16 @@ void WebEngine::LoadUrl( const std::string& url ) return Internal::Adaptor::GetImplementation( *this ).LoadUrl( url ); } +std::string WebEngine::GetTitle() const +{ + return Internal::Adaptor::GetImplementation( *this ).GetTitle(); +} + +Dali::PixelData WebEngine::GetFavicon() const +{ + return Internal::Adaptor::GetImplementation( *this ).GetFavicon(); +} + const std::string& WebEngine::GetUrl() { return Internal::Adaptor::GetImplementation( *this ).GetUrl(); @@ -694,6 +997,37 @@ void WebEngine::AddJavaScriptMessageHandler( const std::string& exposedObjectNam { } +void WebEngine::RegisterJavaScriptAlertCallback( Dali::WebEnginePlugin::JavaScriptAlertCallback callback ) +{ + Internal::Adaptor::GetImplementation( *this ).RegisterJavaScriptAlertCallback( callback ); +} + +void WebEngine::JavaScriptAlertReply() +{ +} + +void WebEngine::RegisterJavaScriptConfirmCallback( Dali::WebEnginePlugin::JavaScriptConfirmCallback callback ) +{ + Internal::Adaptor::GetImplementation( *this ).RegisterJavaScriptConfirmCallback( callback ); +} + +void WebEngine::JavaScriptConfirmReply( bool confirmed ) +{ +} + +void WebEngine::RegisterJavaScriptPromptCallback( Dali::WebEnginePlugin::JavaScriptPromptCallback callback ) +{ + Internal::Adaptor::GetImplementation( *this ).RegisterJavaScriptPromptCallback( callback ); +} + +void WebEngine::JavaScriptPromptReply( const std::string& result ) +{ +} + +void WebEngine::ClearAllTilesResources() +{ +} + void WebEngine::ClearHistory() { Internal::Adaptor::GetImplementation( *this ).ClearHistory(); @@ -719,19 +1053,19 @@ void WebEngine::SetScrollPosition( int x, int y ) Internal::Adaptor::GetImplementation( *this ).SetScrollPosition( x, y ); } -void WebEngine::GetScrollPosition( int& x, int& y ) const +Dali::Vector2 WebEngine::GetScrollPosition() const { - Internal::Adaptor::GetImplementation( *this ).GetScrollPosition( x, y ); + return Internal::Adaptor::GetImplementation( *this ).GetScrollPosition(); } -void WebEngine::GetScrollSize( int& w, int& h ) const +Dali::Vector2 WebEngine::GetScrollSize() const { - Internal::Adaptor::GetImplementation( *this ).GetScrollSize( w, h ); + return Internal::Adaptor::GetImplementation( *this ).GetScrollSize(); } -void WebEngine::GetContentSize( int& w, int& h ) const +Dali::Vector2 WebEngine::GetContentSize() const { - Internal::Adaptor::GetImplementation( *this ).GetContentSize( w, h ); + return Internal::Adaptor::GetImplementation( *this ).GetContentSize(); } void WebEngine::SetSize( int width, int height ) @@ -752,11 +1086,24 @@ void WebEngine::SetFocus( bool focused ) { } +void WebEngine::UpdateDisplayArea( Dali::Rect< int > displayArea ) +{ +} + +void WebEngine::EnableVideoHole( bool enabled ) +{ +} + Dali::WebEnginePlugin::WebEnginePageLoadSignalType& WebEngine::PageLoadStartedSignal() { return Internal::Adaptor::GetImplementation( *this ).PageLoadStartedSignal(); } +Dali::WebEnginePlugin::WebEnginePageLoadSignalType& WebEngine::PageLoadInProgressSignal() +{ + return Internal::Adaptor::GetImplementation( *this ).PageLoadInProgressSignal(); +} + Dali::WebEnginePlugin::WebEnginePageLoadSignalType& WebEngine::PageLoadFinishedSignal() { return Internal::Adaptor::GetImplementation( *this ).PageLoadFinishedSignal(); @@ -772,5 +1119,10 @@ Dali::WebEnginePlugin::WebEngineScrollEdgeReachedSignalType& WebEngine::ScrollEd return Internal::Adaptor::GetImplementation( *this ).ScrollEdgeReachedSignal(); } +Dali::WebEnginePlugin::WebEngineUrlChangedSignalType& WebEngine::UrlChangedSignal() +{ + return Internal::Adaptor::GetImplementation( *this ).UrlChangedSignal(); +} + } // namespace Dali; diff --git a/automated-tests/src/dali-toolkit/utc-Dali-Alignment.cpp b/automated-tests/src/dali-toolkit/utc-Dali-Alignment.cpp index d3aba7e..f4b809d 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-Alignment.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-Alignment.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -844,7 +844,7 @@ int UtcDaliAlignmentSetPaddingNegative(void) } catch (DaliException& e) { - DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION ); } try @@ -855,7 +855,7 @@ int UtcDaliAlignmentSetPaddingNegative(void) } catch (DaliException& e) { - DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION ); } try @@ -866,7 +866,7 @@ int UtcDaliAlignmentSetPaddingNegative(void) } catch (DaliException& e) { - DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION ); } try @@ -877,7 +877,7 @@ int UtcDaliAlignmentSetPaddingNegative(void) } catch (DaliException& e) { - DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION ); } END_TEST; } diff --git a/automated-tests/src/dali-toolkit/utc-Dali-AnimatedVectorImageVisual.cpp b/automated-tests/src/dali-toolkit/utc-Dali-AnimatedVectorImageVisual.cpp index 42a9e91..b692ebb 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-AnimatedVectorImageVisual.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-AnimatedVectorImageVisual.cpp @@ -50,6 +50,7 @@ namespace { const char* TEST_VECTOR_IMAGE_FILE_NAME = TEST_RESOURCE_DIR "/insta_camera.json"; +const char* TEST_VECTOR_IMAGE_INVALID_FILE_NAME = "invalid.json"; bool gAnimationFinishedSignalFired = false; @@ -1491,3 +1492,41 @@ int UtcDaliAnimatedVectorImageVisualWindowVisibilityChanged(void) END_TEST; } + +int UtcDaliAnimatedVectorImageVisualInvalidFile(void) +{ + ToolkitTestApplication application; + tet_infoline("Request loading with invalid file - should draw broken image"); + + TestGlAbstraction& gl = application.GetGlAbstraction(); + TraceCallStack& textureTrace = gl.GetTextureTrace(); + textureTrace.Enable(true); + + Property::Map propertyMap; + propertyMap.Add(Toolkit::Visual::Property::TYPE, DevelVisual::ANIMATED_VECTOR_IMAGE) + .Add(ImageVisual::Property::URL, TEST_VECTOR_IMAGE_INVALID_FILE_NAME); + + Visual::Base visual = VisualFactory::Get().CreateVisual(propertyMap); + DALI_TEST_CHECK(visual); + + DummyControl actor = DummyControl::New(true); + DummyControlImpl& dummyImpl = static_cast< DummyControlImpl& >(actor.GetImplementation()); + dummyImpl.RegisterVisual(DummyControl::Property::TEST_VISUAL, visual); + + actor.SetProperty(Actor::Property::SIZE, Vector2(20.0f, 20.0f)); + + application.GetScene().Add(actor); + + application.SendNotification(); + application.Render(); + + // Check resource status + Visual::ResourceStatus status = actor.GetVisualResourceStatus(DummyControl::Property::TEST_VISUAL); + DALI_TEST_EQUALS(status, Visual::ResourceStatus::FAILED, TEST_LOCATION); + + // The broken image should be shown. + DALI_TEST_EQUALS(actor.GetRendererCount(), 1u, TEST_LOCATION); + DALI_TEST_EQUALS(textureTrace.FindMethod("BindTexture"), true, TEST_LOCATION); + + END_TEST; +} diff --git a/automated-tests/src/dali-toolkit/utc-Dali-BubbleEmitter.cpp b/automated-tests/src/dali-toolkit/utc-Dali-BubbleEmitter.cpp index 1c46455..b5a0d5f 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-BubbleEmitter.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-BubbleEmitter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -259,7 +259,7 @@ int UtcDaliBubbleEmitterSetBubbleDensity02(void) catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT( e ); - DALI_TEST_ASSERT(e, "density>0 && density<=9", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "density > 0 && density <= 9", TEST_LOCATION ); } END_TEST; } diff --git a/automated-tests/src/dali-toolkit/utc-Dali-ImageView.cpp b/automated-tests/src/dali-toolkit/utc-Dali-ImageView.cpp index 2be7c5a..033340f 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-ImageView.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-ImageView.cpp @@ -2627,11 +2627,6 @@ int UtcDaliImageViewSvgLoadingFailure(void) application.GetScene().Add( imageView ); application.SendNotification(); - - // loading started, this waits for the loader thread - DALI_TEST_EQUALS( Test::WaitForEventThreadTrigger( 1 ), true, TEST_LOCATION ); - - application.SendNotification(); application.Render(16); DALI_TEST_EQUALS( gResourceReadySignalFired, true, TEST_LOCATION ); @@ -2652,11 +2647,6 @@ int UtcDaliImageViewSvgLoadingFailure(void) application.GetScene().Add( imageView ); application.SendNotification(); - - // loading started, this waits for the loader thread - DALI_TEST_EQUALS( Test::WaitForEventThreadTrigger( 1 ), true, TEST_LOCATION ); - - application.SendNotification(); application.Render(16); DALI_TEST_EQUALS( gResourceReadySignalFired, true, TEST_LOCATION ); diff --git a/automated-tests/src/dali-toolkit/utc-Dali-TextEditor.cpp b/automated-tests/src/dali-toolkit/utc-Dali-TextEditor.cpp index 66f8db3..06d3307 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-TextEditor.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-TextEditor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -964,20 +964,113 @@ int utcDaliTextEditorTextChangedP(void) gTextChangedCallBackCalled = false; editor.SetProperty( TextEditor::Property::TEXT, "ABC" ); + application.SendNotification(); + application.Render(); DALI_TEST_CHECK( gTextChangedCallBackCalled ); DALI_TEST_CHECK( textChangedSignal ); + editor.SetKeyInputFocus(); + + gTextChangedCallBackCalled = false; + application.ProcessEvent( GenerateKey( "D", "", "D", KEY_D_CODE, 0, 0, Integration::KeyEvent::DOWN, "D", DEFAULT_DEVICE_NAME, Device::Class::NONE, Device::Subclass::NONE ) ); + application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( gTextChangedCallBackCalled ); + + // Remove all text + editor.SetProperty( TextField::Property::TEXT, "" ); + application.SendNotification(); + application.Render(); + + // Pressing backspace key: TextChangedCallback should not be called when there is no text in texteditor. + gTextChangedCallBackCalled = false; + application.ProcessEvent( GenerateKey( "", "", "", DALI_KEY_BACKSPACE, 0, 0, Integration::KeyEvent::DOWN, "", DEFAULT_DEVICE_NAME, Device::Class::NONE, Device::Subclass::NONE ) ); + application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( !gTextChangedCallBackCalled ); + + // Pressing delete key: TextChangedCallback should not be called when there is no text in texteditor. + gTextChangedCallBackCalled = false; + application.ProcessEvent( GenerateKey( "", "", "", Dali::DevelKey::DALI_KEY_DELETE, 0, 0, Integration::KeyEvent::DOWN, "Delete", DEFAULT_DEVICE_NAME, Device::Class::NONE, Device::Subclass::NONE ) ); application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( !gTextChangedCallBackCalled ); + + END_TEST; +} + +int utcDaliTextEditorTextChangedWithInputMethodContext(void) +{ + ToolkitTestApplication application; + tet_infoline(" utcDaliTextEditorTextChangedWithInputMethodContext"); + TextEditor editor = TextEditor::New(); + DALI_TEST_CHECK( editor ); + + + application.GetScene().Add( editor ); + + // connect to the text changed signal. + ConnectionTracker* testTracker = new ConnectionTracker(); + editor.TextChangedSignal().Connect(&TestTextChangedCallback); + bool textChangedSignal = false; + editor.ConnectSignal( testTracker, "textChanged", CallbackFunctor(&textChangedSignal) ); + + + // get InputMethodContext + std::string text; + InputMethodContext::EventData imfEvent; + InputMethodContext inputMethodContext = DevelTextEditor::GetInputMethodContext( editor ); editor.SetKeyInputFocus(); + editor.SetProperty( DevelTextEditor::Property::ENABLE_EDITING, true ); + // input text gTextChangedCallBackCalled = false; - application.ProcessEvent( GenerateKey( "D", "", "D", KEY_D_CODE, 0, 0, Integration::KeyEvent::DOWN, "D", DEFAULT_DEVICE_NAME, Device::Class::NONE, Device::Subclass::NONE ) ); + imfEvent = InputMethodContext::EventData( InputMethodContext::PRE_EDIT, "ㅎ", 0, 1 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( gTextChangedCallBackCalled ); + DALI_TEST_EQUALS( editor.GetProperty( TextEditor::Property::TEXT ), std::string("ㅎ"), TEST_LOCATION ); + + gTextChangedCallBackCalled = false; + imfEvent = InputMethodContext::EventData( InputMethodContext::PRE_EDIT, "호", 0, 1 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( gTextChangedCallBackCalled ); + DALI_TEST_EQUALS( editor.GetProperty( TextEditor::Property::TEXT ), std::string("호"), TEST_LOCATION ); + + gTextChangedCallBackCalled = false; + imfEvent = InputMethodContext::EventData( InputMethodContext::PRE_EDIT, "혿", 0, 1 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + application.SendNotification(); + application.Render(); DALI_TEST_CHECK( gTextChangedCallBackCalled ); + DALI_TEST_EQUALS( editor.GetProperty( TextEditor::Property::TEXT ), std::string("혿"), TEST_LOCATION ); + + gTextChangedCallBackCalled = false; + imfEvent = InputMethodContext::EventData( InputMethodContext::PRE_EDIT, "", 0, 1 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + DALI_TEST_CHECK( !gTextChangedCallBackCalled ); + + imfEvent = InputMethodContext::EventData( InputMethodContext::COMMIT, "호", 0, 1 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + DALI_TEST_CHECK( !gTextChangedCallBackCalled ); + + imfEvent = InputMethodContext::EventData( InputMethodContext::PRE_EDIT, "두", 1, 2 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + DALI_TEST_CHECK( !gTextChangedCallBackCalled ); + + application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( gTextChangedCallBackCalled ); + DALI_TEST_EQUALS( editor.GetProperty( TextEditor::Property::TEXT ), std::string("호두"), TEST_LOCATION ); END_TEST; } + int utcDaliTextEditorInputStyleChanged01(void) { // The text-editor emits signals when the input style changes. These changes of style are diff --git a/automated-tests/src/dali-toolkit/utc-Dali-TextField.cpp b/automated-tests/src/dali-toolkit/utc-Dali-TextField.cpp index 93d8f7d..0795816 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-TextField.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-TextField.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -1034,20 +1034,113 @@ int utcDaliTextFieldTextChangedP(void) gTextChangedCallBackCalled = false; field.SetProperty( TextField::Property::TEXT, "ABC" ); + application.SendNotification(); + application.Render(); DALI_TEST_CHECK( gTextChangedCallBackCalled ); DALI_TEST_CHECK( textChangedSignal ); + field.SetKeyInputFocus(); + + gTextChangedCallBackCalled = false; + application.ProcessEvent( GenerateKey( "D", "", "D", KEY_D_CODE, 0, 0, Integration::KeyEvent::DOWN, "D", DEFAULT_DEVICE_NAME, Device::Class::NONE, Device::Subclass::NONE ) ); + application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( gTextChangedCallBackCalled ); + + // Remove all text + field.SetProperty( TextField::Property::TEXT, "" ); application.SendNotification(); + application.Render(); + + // Pressing backspace key: TextChangedCallback should not be called when there is no text in textfield. + gTextChangedCallBackCalled = false; + application.ProcessEvent( GenerateKey( "", "", "", DALI_KEY_BACKSPACE, 0, 0, Integration::KeyEvent::DOWN, "", DEFAULT_DEVICE_NAME, Device::Class::NONE, Device::Subclass::NONE ) ); + application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( !gTextChangedCallBackCalled ); + + // Pressing delete key: TextChangedCallback should not be called when there is no text in textfield. + gTextChangedCallBackCalled = false; + application.ProcessEvent( GenerateKey( "", "", "", Dali::DevelKey::DALI_KEY_DELETE, 0, 0, Integration::KeyEvent::DOWN, "Delete", DEFAULT_DEVICE_NAME, Device::Class::NONE, Device::Subclass::NONE ) ); + application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( !gTextChangedCallBackCalled ); + + END_TEST; +} + +int utcDaliTextFieldTextChangedWithInputMethodContext(void) +{ + ToolkitTestApplication application; + tet_infoline(" utcDaliTextFieldTextChangedWithInputMethodContext"); + TextField field = TextField::New(); + DALI_TEST_CHECK( field ); + + + application.GetScene().Add( field ); + + // connect to the text changed signal. + ConnectionTracker* testTracker = new ConnectionTracker(); + field.TextChangedSignal().Connect(&TestTextChangedCallback); + bool textChangedSignal = false; + field.ConnectSignal( testTracker, "textChanged", CallbackFunctor(&textChangedSignal) ); + + + // get InputMethodContext + std::string text; + InputMethodContext::EventData imfEvent; + InputMethodContext inputMethodContext = DevelTextField::GetInputMethodContext( field ); field.SetKeyInputFocus(); + field.SetProperty( DevelTextField::Property::ENABLE_EDITING, true ); + // input text gTextChangedCallBackCalled = false; - application.ProcessEvent( GenerateKey( "D", "", "D", KEY_D_CODE, 0, 0, Integration::KeyEvent::DOWN, "D", DEFAULT_DEVICE_NAME, Device::Class::NONE, Device::Subclass::NONE ) ); + imfEvent = InputMethodContext::EventData( InputMethodContext::PRE_EDIT, "ㅎ", 0, 1 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( gTextChangedCallBackCalled ); + DALI_TEST_EQUALS( field.GetProperty( TextField::Property::TEXT ), std::string("ㅎ"), TEST_LOCATION ); + + gTextChangedCallBackCalled = false; + imfEvent = InputMethodContext::EventData( InputMethodContext::PRE_EDIT, "호", 0, 1 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( gTextChangedCallBackCalled ); + DALI_TEST_EQUALS( field.GetProperty( TextField::Property::TEXT ), std::string("호"), TEST_LOCATION ); + + gTextChangedCallBackCalled = false; + imfEvent = InputMethodContext::EventData( InputMethodContext::PRE_EDIT, "혿", 0, 1 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + application.SendNotification(); + application.Render(); DALI_TEST_CHECK( gTextChangedCallBackCalled ); + DALI_TEST_EQUALS( field.GetProperty( TextField::Property::TEXT ), std::string("혿"), TEST_LOCATION ); + + gTextChangedCallBackCalled = false; + imfEvent = InputMethodContext::EventData( InputMethodContext::PRE_EDIT, "", 0, 1 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + DALI_TEST_CHECK( !gTextChangedCallBackCalled ); + + imfEvent = InputMethodContext::EventData( InputMethodContext::COMMIT, "호", 0, 1 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + DALI_TEST_CHECK( !gTextChangedCallBackCalled ); + + imfEvent = InputMethodContext::EventData( InputMethodContext::PRE_EDIT, "두", 1, 2 ); + inputMethodContext.EventReceivedSignal().Emit(inputMethodContext, imfEvent); + DALI_TEST_CHECK( !gTextChangedCallBackCalled ); + + application.SendNotification(); + application.Render(); + DALI_TEST_CHECK( gTextChangedCallBackCalled ); + DALI_TEST_EQUALS( field.GetProperty( TextField::Property::TEXT ), std::string("호두"), TEST_LOCATION ); END_TEST; } + // Negative test for the textChanged signal. int utcDaliTextFieldTextChangedN(void) { @@ -1066,6 +1159,8 @@ int utcDaliTextFieldTextChangedN(void) gTextChangedCallBackCalled = false; field.SetProperty( TextField::Property::PLACEHOLDER_TEXT, "ABC" ); // Setting placeholder, not TEXT + application.SendNotification(); + application.Render(); DALI_TEST_CHECK( !gTextChangedCallBackCalled ); DALI_TEST_CHECK( !textChangedSignal ); diff --git a/automated-tests/src/dali-toolkit/utc-Dali-TransitionData.cpp b/automated-tests/src/dali-toolkit/utc-Dali-TransitionData.cpp index ca57b44..a68ac7a 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-TransitionData.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-TransitionData.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -755,49 +755,6 @@ int UtcDaliTransitionDataMap1N(void) END_TEST; } - -int UtcDaliTransitionDataMapN3(void) -{ - ToolkitTestApplication application; - - tet_printf("Testing visual lookup with no renderers\n"); - - Property::Map map; - map["target"] = "visual1"; - map["property"] = "mixColor"; - map["initialValue"] = Vector3(Color::MAGENTA); - map["targetValue"] = Vector3(Color::RED); - map["animator"] = Property::Map() - .Add("alphaFunction", "EASE_OUT_BACK") - .Add("timePeriod", Property::Map() - .Add("delay", 0.5f) - .Add("duration", 1.0f)); - - Dali::Toolkit::TransitionData transition = TransitionData::New( map ); - CHECK_MAP_EQUALS( map, transition.GetAnimatorAt(0) ); - - DummyControl actor = DummyControl::New(); - actor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); - actor.SetProperty( Dali::Actor::Property::NAME,"Actor1"); - actor.SetProperty( Actor::Property::COLOR,Color::CYAN); - // Don't stage actor - - DummyControlImpl& dummyImpl = static_cast(actor.GetImplementation()); - Property::Map visualMap; - visualMap[Visual::Property::TYPE] = Visual::COLOR; - visualMap[ColorVisual::Property::MIX_COLOR] = Vector3(Color::MAGENTA); - Visual::Base visual = VisualFactory::Get().CreateVisual( visualMap ); - visual.SetName( "visual1" ); - - Property::Index visualIndex = Control::CONTROL_PROPERTY_END_INDEX + 1; - dummyImpl.RegisterVisual( visualIndex, visual ); - - Animation anim = dummyImpl.CreateTransition( transition ); - DALI_TEST_CHECK( !anim ); - END_TEST; -} - - int UtcDaliTransitionDataMapN4(void) { ToolkitTestApplication application; diff --git a/automated-tests/src/dali-toolkit/utc-Dali-Visual.cpp b/automated-tests/src/dali-toolkit/utc-Dali-Visual.cpp index 761e88e..fbf3438 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-Visual.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-Visual.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -4136,13 +4136,6 @@ int UtcDaliVisualGetVisualProperty01(void) DALI_TEST_CHECK(!property3.object); DALI_TEST_CHECK(property3.propertyIndex == Property::INVALID_INDEX); - // Test after the control is unparented - dummyControl.Unparent(); - - Property property4 = DevelControl::GetVisualProperty(dummyControl, DummyControl::Property::TEST_VISUAL, Visual::Property::MIX_COLOR); - DALI_TEST_CHECK(!property4.object); - DALI_TEST_CHECK(property4.propertyIndex == Property::INVALID_INDEX); - END_TEST; } diff --git a/automated-tests/src/dali-toolkit/utc-Dali-WebView.cpp b/automated-tests/src/dali-toolkit/utc-Dali-WebView.cpp old mode 100644 new mode 100755 index 2088d90..7b7e397 --- a/automated-tests/src/dali-toolkit/utc-Dali-WebView.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-WebView.cpp @@ -24,6 +24,8 @@ #include #include #include +#include +#include #include #include #include @@ -32,7 +34,6 @@ #include #include - using namespace Dali; using namespace Toolkit; @@ -43,9 +44,14 @@ const char* const TEST_URL1( "http://www.somewhere.valid1.com" ); const char* const TEST_URL2( "http://www.somewhere.valid2.com" ); static int gPageLoadStartedCallbackCalled = 0; +static int gPageLoadInProgressCallbackCalled = 0; static int gPageLoadFinishedCallbackCalled = 0; static int gScrollEdgeReachedCallbackCalled = 0; +static int gUrlChangedCallbackCalled = 0; static int gEvaluateJavaScriptCallbackCalled = 0; +static int gJavaScriptAlertCallbackCalled = 0; +static int gJavaScriptConfirmCallbackCalled = 0; +static int gJavaScriptPromptCallbackCalled = 0; static bool gTouched = false; struct CallbackFunctor @@ -67,6 +73,11 @@ static void OnPageLoadStarted( WebView view, const std::string& url ) gPageLoadStartedCallbackCalled++; } +static void OnPageLoadInProgress( WebView view, const std::string& url ) +{ + gPageLoadInProgressCallbackCalled++; +} + static void OnPageLoadFinished( WebView view, const std::string& url ) { gPageLoadFinishedCallbackCalled++; @@ -77,6 +88,11 @@ static void OnScrollEdgeReached( WebView view, Dali::WebEnginePlugin::ScrollEdge gScrollEdgeReachedCallbackCalled++; } +static void OnUrlChanged( WebView view, const std::string& url ) +{ + gUrlChangedCallbackCalled++; +} + static void OnPageLoadError( WebView view, const std::string& url, WebView::LoadErrorCode errorCode ) { } @@ -86,6 +102,24 @@ static void OnEvaluateJavaScript( const std::string& result ) gEvaluateJavaScriptCallbackCalled++; } +static bool OnJavaScriptAlert( const std::string& result ) +{ + gJavaScriptAlertCallbackCalled++; + return true; +} + +static bool OnJavaScriptConfirm( const std::string& result ) +{ + gJavaScriptConfirmCallbackCalled++; + return true; +} + +static bool OnJavaScriptPrompt( const std::string& meesage1, const std::string& message2 ) +{ + gJavaScriptPromptCallbackCalled++; + return true; +} + static bool OnTouched( Actor actor, const Dali::TouchEvent& touch ) { gTouched = true; @@ -166,26 +200,35 @@ int UtcDaliWebViewPageNavigation(void) ConnectionTracker* testTracker = new ConnectionTracker(); view.PageLoadStartedSignal().Connect( &OnPageLoadStarted ); + view.PageLoadInProgressSignal().Connect( &OnPageLoadInProgress ); view.PageLoadFinishedSignal().Connect( &OnPageLoadFinished ); view.PageLoadErrorSignal().Connect( &OnPageLoadError ); + view.UrlChangedSignal().Connect( &OnUrlChanged ); bool signal1 = false; bool signal2 = false; bool signal3 = false; + bool signal4 = false; + bool signal5 = false; view.ConnectSignal( testTracker, "pageLoadStarted", CallbackFunctor(&signal1) ); - view.ConnectSignal( testTracker, "pageLoadFinished", CallbackFunctor(&signal2) ); - view.ConnectSignal( testTracker, "invalidname", CallbackFunctor(&signal3) ); + view.ConnectSignal( testTracker, "pageLoadInProgress", CallbackFunctor(&signal2) ); + view.ConnectSignal( testTracker, "pageLoadFinished", CallbackFunctor(&signal3) ); + view.ConnectSignal( testTracker, "urlChanged", CallbackFunctor(&signal4) ); + view.ConnectSignal( testTracker, "invalidname", CallbackFunctor(&signal5) ); DALI_TEST_EQUALS( gPageLoadStartedCallbackCalled, 0, TEST_LOCATION ); + DALI_TEST_EQUALS( gPageLoadInProgressCallbackCalled, 0, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadFinishedCallbackCalled, 0, TEST_LOCATION ); - + DALI_TEST_EQUALS( gUrlChangedCallbackCalled, 0, TEST_LOCATION ); view.LoadUrl( TEST_URL1 ); view.GetNaturalSize(); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( view.CanGoBack(), false, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadStartedCallbackCalled, 1, TEST_LOCATION ); + DALI_TEST_EQUALS( gPageLoadInProgressCallbackCalled, 1, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadFinishedCallbackCalled, 1, TEST_LOCATION ); - DALI_TEST_CHECK( signal1 & signal2 ); - DALI_TEST_CHECK( !signal3 ); + DALI_TEST_EQUALS( gUrlChangedCallbackCalled, 1, TEST_LOCATION ); + DALI_TEST_CHECK( signal1 & signal2 & signal3 & signal4 ); + DALI_TEST_CHECK( !signal5 ); view.LoadUrl( TEST_URL2 ); view.Suspend(); @@ -197,7 +240,9 @@ int UtcDaliWebViewPageNavigation(void) DALI_TEST_EQUALS( view.CanGoBack(), true, TEST_LOCATION ); DALI_TEST_EQUALS( view.CanGoForward(), false, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadStartedCallbackCalled, 2, TEST_LOCATION ); + DALI_TEST_EQUALS( gPageLoadInProgressCallbackCalled, 2, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadFinishedCallbackCalled, 2, TEST_LOCATION ); + DALI_TEST_EQUALS( gUrlChangedCallbackCalled, 2, TEST_LOCATION ); view.GoBack(); Test::EmitGlobalTimerSignal(); @@ -289,6 +334,54 @@ int UtcDaliWebViewFocusGainedAndLost(void) END_TEST; } +int UtcDaliWebViewMove(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); + view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); + view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); + view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); + + application.GetScene().Add( view ); + application.SendNotification(); + application.Render(); + + view.SetProperty( Actor::Property::POSITION, Vector2( 100, 100 )); + Vector3 viewPos = view.GetProperty( Actor::Property::POSITION ); + DALI_TEST_EQUALS( viewPos, Vector3( 100, 100, 0 ), TEST_LOCATION ); + + END_TEST; +} + +int UtcDaliWebViewPropertyVideoHole(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + const bool kDefaultValue = true; + const bool kTestValue = false; + + // Check default value + bool output; + Property::Value value = view.GetProperty( WebView::Property::VIDEO_HOLE_ENABLED ); + DALI_TEST_CHECK( value.Get( output ) ); + DALI_TEST_EQUALS( output, kDefaultValue, TEST_LOCATION ); + + // Check Set/GetProperty + view.SetProperty( WebView::Property::VIDEO_HOLE_ENABLED, kTestValue ); + value = view.GetProperty( WebView::Property::VIDEO_HOLE_ENABLED ); + DALI_TEST_CHECK( value.Get( output ) ); + DALI_TEST_EQUALS( output, kTestValue, TEST_LOCATION ); + + END_TEST; +} + int UtcDaliWebViewGetWebBackForwardList(void) { ToolkitTestApplication application; @@ -416,6 +509,33 @@ int UtcDaliWebViewProperty9(void) END_TEST; } +int UtcDaliWebViewPropertyTitleFavicon(void) +{ + // SCROLL_POSITION + ToolkitTestApplication application; + + char argv[] = "--test"; + WebView view = WebView::New( 1, (char**)&argv ); + DALI_TEST_CHECK( view ); + + // reset something + view.ClearAllTilesResources(); + + // Check default value of title + std::string testValue("title"); + std::string output; + view.GetProperty( WebView::Property::TITLE ).Get( output ); + DALI_TEST_EQUALS( output, testValue, TEST_LOCATION ); + + // Check default value of favicon + Dali::Toolkit::ImageView* favicon = &view.GetFavicon(); + DALI_TEST_CHECK( favicon ); + Dali::Vector3 iconsize = favicon->GetProperty< Vector3 >( Dali::Actor::Property::SIZE ); + DALI_TEST_CHECK( ( int )iconsize.width == 2 && ( int )iconsize.height == 2 ); + + END_TEST; +} + int UtcDaliWebViewScrollBy(void) { ToolkitTestApplication application; @@ -442,6 +562,8 @@ int UtcDaliWebViewScrollBy(void) // scroll by and trigger scrollEdgeReached event. view.ScrollBy( 50, 50 ); + Test::EmitGlobalTimerSignal(); + view.GetProperty( WebView::Property::SCROLL_POSITION ).Get( output ); DALI_TEST_CHECK( output.x == 150 && output.y == 150 ); DALI_TEST_EQUALS( gScrollEdgeReachedCallbackCalled, 1, TEST_LOCATION ); @@ -466,6 +588,33 @@ int UtcDaliWebViewEvaluteJavaScript(void) END_TEST; } +int UtcDaliWebViewJavaScriptAlertConfirmPrompt(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New( "ko-KR", "Asia/Seoul" ); + + view.RegisterJavaScriptAlertCallback( &OnJavaScriptAlert ); + view.LoadHtmlString( "Hello World!" ); + view.JavaScriptAlertReply(); + Test::EmitGlobalTimerSignal(); + DALI_TEST_EQUALS( gJavaScriptAlertCallbackCalled, 1, TEST_LOCATION ); + + view.RegisterJavaScriptConfirmCallback( &OnJavaScriptConfirm ); + view.LoadHtmlString( "Hello World!" ); + view.JavaScriptConfirmReply( true ); + Test::EmitGlobalTimerSignal(); + DALI_TEST_EQUALS( gJavaScriptConfirmCallbackCalled, 1, TEST_LOCATION ); + + view.RegisterJavaScriptPromptCallback( &OnJavaScriptPrompt ); + view.LoadHtmlString( "Hello World!" ); + view.JavaScriptPromptReply( "it is a prompt." ); + Test::EmitGlobalTimerSignal(); + DALI_TEST_EQUALS( gJavaScriptPromptCallbackCalled, 1, TEST_LOCATION ); + + END_TEST; +} + int UtcDaliWebViewMethodsForCoverage(void) { ToolkitTestApplication application; @@ -601,6 +750,9 @@ int UtcDaliWebSettingsGetSetDefaultFontSize(void) settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); @@ -630,6 +782,9 @@ int UtcDaliWebSettingsCheckEnableJavaScript(void) settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); @@ -645,6 +800,384 @@ int UtcDaliWebSettingsCheckEnableJavaScript(void) END_TEST; } +int UtcDaliWebSettingsCheckEnableAutoFitting(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ) + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->IsAutoFittingEnabled(); + DALI_TEST_CHECK( value ); + + // Check Set/GetProperty + settings->EnableAutoFitting( false ); + value = settings->IsAutoFittingEnabled(); + DALI_TEST_CHECK( !value ); + + END_TEST; +} + +int UtcDaliWebSettingsCheckEnablePlugins(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ) + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->ArePluginsEnabled(); + DALI_TEST_CHECK( value ); + + // Check Set/GetProperty + settings->EnablePlugins( false ); + value = settings->ArePluginsEnabled(); + DALI_TEST_CHECK( !value ); + + END_TEST; +} + +int UtcDaliWebSettingsCheckEnablePrivateBrowsing(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ) + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->IsPrivateBrowsingEnabled(); + DALI_TEST_CHECK( value ); + + // Check Set/GetProperty + settings->EnablePrivateBrowsing( false ); + value = settings->IsPrivateBrowsingEnabled(); + DALI_TEST_CHECK( !value ); + + END_TEST; +} + +int UtcDaliWebSettingsCheckEnableLinkMagnifier(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ) + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->IsLinkMagnifierEnabled(); + DALI_TEST_CHECK( value ); + + // Check Set/GetProperty + settings->EnableLinkMagnifier( false ); + value = settings->IsLinkMagnifierEnabled(); + DALI_TEST_CHECK( !value ); + + END_TEST; +} + +int UtcDaliWebSettingsCheckUseKeypadWithoutUserAction(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ) + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->IsKeypadWithoutUserActionUsed(); + DALI_TEST_CHECK( value ); + + // Check Set/GetProperty + settings->UseKeypadWithoutUserAction( false ); + value = settings->IsKeypadWithoutUserActionUsed(); + DALI_TEST_CHECK( !value ); + + END_TEST; +} + +int UtcDaliWebSettingsCheckEnableAutofillPasswordForm(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ) + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->IsAutofillPasswordFormEnabled(); + DALI_TEST_CHECK( value ); + settings->EnableAutofillPasswordForm( false ); + value = settings->IsAutofillPasswordFormEnabled(); + DALI_TEST_CHECK( !value ); + END_TEST; +} + +int UtcDaliWebSettingsCheckEnableFormCandidateData(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ); + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->IsFormCandidateDataEnabled(); + DALI_TEST_CHECK( value ); + + // Check Set/GetProperty + settings->EnableFormCandidateData( false ); + value = settings->IsFormCandidateDataEnabled(); + DALI_TEST_CHECK( !value ); + + END_TEST; +} + +int UtcDaliWebSettingsCheckEnableTextSelection(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ); + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->IsTextSelectionEnabled(); + DALI_TEST_CHECK( value ); + + //Check Set/GetProperty + settings->EnableTextSelection(false); + value = settings->IsTextSelectionEnabled(); + DALI_TEST_CHECK( !value ); + + END_TEST; +} + +int UtcDaliWebSettingsCheckEnableTextAutosizing(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ); + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->IsTextAutosizingEnabled(); + DALI_TEST_CHECK( value ); + + // Check Set/GetProperty + settings->EnableTextAutosizing(false); + value = settings->IsTextAutosizingEnabled(); + DALI_TEST_CHECK( !value ); + + END_TEST; +} + +int UtcDaliWebSettingsCheckEnableArrowScroll(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ); + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->IsArrowScrollEnabled(); + DALI_TEST_CHECK( value ); + + // Check Set/GetProperty + settings->EnableArrowScroll(false); + value = settings->IsArrowScrollEnabled(); + DALI_TEST_CHECK( !value ); + + END_TEST; +} + +int UtcDaliWebSettingsCheckEnableClipboard(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ); + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->IsClipboardEnabled(); + DALI_TEST_CHECK( value ); + settings->EnableClipboard(false); + value = settings->IsClipboardEnabled(); + DALI_TEST_CHECK( !value ); + END_TEST; +} + +int UtcDaliWebSettingsCheckEnableImePanel(void) +{ + ToolkitTestApplication application; + + WebView view = WebView::New(); + DALI_TEST_CHECK( view ); + + Dali::Toolkit::WebSettings* settings = view.GetSettings(); + DALI_TEST_CHECK( settings != 0 ); + + // Reset something + settings->AllowMixedContents( false ); + settings->EnableSpatialNavigation( false ); + settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); + settings->AllowFileAccessFromExternalUrl( false ); + settings->AllowScriptsOpenWindows( false ); + + // Check default value is true or not + bool value = settings->IsImePanelEnabled(); + DALI_TEST_CHECK( value ); + + // Check Set/GetProperty + settings->EnableImePanel(false); + value = settings->IsImePanelEnabled(); + DALI_TEST_CHECK( !value ); + + END_TEST; +} + int UtcDaliWebSettingsCheckAllowImagesLoadAutomatically(void) { ToolkitTestApplication application; @@ -659,6 +1192,9 @@ int UtcDaliWebSettingsCheckAllowImagesLoadAutomatically(void) settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); @@ -691,6 +1227,9 @@ int UtcDaliWebSettingsGetSetDefaultTextEncodingName(void) settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); + settings->EnableCacheBuilder( false ); + settings->EnableDoNotTrack( false ); + settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); diff --git a/build/tizen/CMakeLists.txt b/build/tizen/CMakeLists.txt index 840ff92..a7bc0e6 100644 --- a/build/tizen/CMakeLists.txt +++ b/build/tizen/CMakeLists.txt @@ -515,6 +515,11 @@ IF( ENABLE_COVERAGE ) ENDIF( LCOV_BIN ) ENDIF() +IF ( BUILD_SCENE_LOADER ) + ADD_SUBDIRECTORY( ${CMAKE_CURRENT_SOURCE_DIR}/dali-scene-loader ) +ENDIF() + + # Build documentation if doxygen tool is available SET( doxygenEnabled OFF ) IF( DOXYGEN_FOUND ) @@ -527,14 +532,29 @@ IF( DOXYGEN_FOUND ) SET( DOXYGEN_INTERNAL_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/docs-internal ) CONFIGURE_FILE( ${DOXYGEN_SRC_DIR}/dali.doxy.in ${DOXYGEN_SRC_DIR}/dali.doxy @ONLY ) CONFIGURE_FILE( ${DOXYGEN_INTERNAL_SRC_DIR}/dali-internal.doxy.in ${DOXYGEN_INTERNAL_SRC_DIR}/dali-internal.doxy @ONLY ) - ADD_CUSTOM_TARGET( doc_doxygen ALL - DEPENDS ${name} - COMMAND ${DOXYGEN_EXECUTABLE} -u ${DOXYGEN_SRC_DIR}/dali.doxy - COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_SRC_DIR}/dali.doxy - COMMAND ${CMAKE_COMMAND} -P ${DOXYGEN_SRC_DIR}/check_for_errors.cmake - COMMENT "Generating API documentation with Doxygen" - WORKING_DIRECTORY ${DOXYGEN_SRC_DIR} - VERBATIM ) + + IF ( BUILD_SCENE_LOADER ) + ADD_CUSTOM_TARGET( doc_doxygen ALL + DEPENDS ${name} dali2-scene-loader + COMMAND ${DOXYGEN_EXECUTABLE} -u ${DOXYGEN_SRC_DIR}/dali.doxy + COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_SRC_DIR}/dali.doxy + COMMAND ${CMAKE_COMMAND} -P ${DOXYGEN_SRC_DIR}/check_for_errors.cmake + COMMENT "Generating API documentation with Doxygen" + WORKING_DIRECTORY ${DOXYGEN_SRC_DIR} + VERBATIM ) + ELSE() + ADD_CUSTOM_TARGET( doc_doxygen ALL + DEPENDS ${name} + COMMAND ${DOXYGEN_EXECUTABLE} -u ${DOXYGEN_SRC_DIR}/dali.doxy + COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_SRC_DIR}/dali.doxy + COMMAND ${CMAKE_COMMAND} -P ${DOXYGEN_SRC_DIR}/check_for_errors.cmake + COMMENT "Generating API documentation with Doxygen" + WORKING_DIRECTORY ${DOXYGEN_SRC_DIR} + VERBATIM ) + ENDIF() + + # Following target is optional - it doesn't run by default + # Build using "make doc_doxygen_internal". ADD_CUSTOM_TARGET( doc_doxygen_internal COMMAND ${DOXYGEN_EXECUTABLE} -u ${DOXYGEN_INTERNAL_SRC_DIR}/dali-internal.doxy COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_INTERNAL_SRC_DIR}/dali-internal.doxy @@ -549,9 +569,6 @@ IF( CONFIGURE_AUTOMATED_TESTS ) ${ROOT_SRC_DIR}/automated-tests/CMakeLists.txt @ONLY ) ENDIF() -IF ( BUILD_SCENE_LOADER ) - ADD_SUBDIRECTORY( ${CMAKE_CURRENT_SOURCE_DIR}/dali-scene-loader ) -ENDIF() # Configuration Messages MESSAGE( STATUS "Configuration:\n" ) diff --git a/build/tizen/docs-internal/dali-internal.doxy.in b/build/tizen/docs-internal/dali-internal.doxy.in index 1d6036f..5364753 100644 --- a/build/tizen/docs-internal/dali-internal.doxy.in +++ b/build/tizen/docs-internal/dali-internal.doxy.in @@ -2368,7 +2368,7 @@ EXTERNAL_PAGES = YES # interpreter (i.e. the result of 'which perl'). # The default file (with absolute path) is: /usr/bin/perl. -PERL_PATH = /usr/bin/perl +#PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool @@ -2390,7 +2390,7 @@ CLASS_DIAGRAMS = YES # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. -MSCGEN_PATH = +#MSCGEN_PATH = # You can include diagrams made with dia in doxygen documentation. Doxygen will # then run dia to produce the diagram and insert it in the documentation. The diff --git a/build/tizen/docs/dali.doxy.in b/build/tizen/docs/dali.doxy.in index 0a9d553..8ef9112 100644 --- a/build/tizen/docs/dali.doxy.in +++ b/build/tizen/docs/dali.doxy.in @@ -2348,7 +2348,7 @@ EXTERNAL_PAGES = YES # interpreter (i.e. the result of 'which perl'). # The default file (with absolute path) is: /usr/bin/perl. -PERL_PATH = /usr/bin/perl +#PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool @@ -2370,7 +2370,7 @@ CLASS_DIAGRAMS = YES # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. -MSCGEN_PATH = +#MSCGEN_PATH = # You can include diagrams made with dia in doxygen documentation. Doxygen will # then run dia to produce the diagram and insert it in the documentation. The diff --git a/dali-scene-loader/internal/gltf2-asset.cpp b/dali-scene-loader/internal/gltf2-asset.cpp index e77a6f5..d0e183a 100644 --- a/dali-scene-loader/internal/gltf2-asset.cpp +++ b/dali-scene-loader/internal/gltf2-asset.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2020 Samsung Electronics Co., Ltd. +* Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,14 @@ * */ #include "dali-scene-loader/internal/gltf2-asset.h" -#include "dali/public-api/math/matrix.h" #include #include +#include "dali/public-api/math/matrix.h" -#define ENUM_STRING_MAPPING(t, x) { #x, t::x } +#define ENUM_STRING_MAPPING(t, x) \ + { \ +#x, t::x \ + } using namespace Dali; @@ -27,7 +30,6 @@ namespace gltf2 { namespace { - constexpr uint32_t ACCESSOR_TYPE_ELEMENT_COUNT[]{ 1, 2, @@ -36,8 +38,7 @@ constexpr uint32_t ACCESSOR_TYPE_ELEMENT_COUNT[]{ 4, 9, 16, - static_cast(-1) -}; + static_cast(-1)}; const std::map ACCESSOR_TYPES{ ENUM_STRING_MAPPING(AccessorType, SCALAR), @@ -79,7 +80,7 @@ const std::map ANIMATION_CHA ENUM_STRING_MAPPING(Animation::Channel::Target::Type, WEIGHTS), }; -} +} // namespace bool Component::IsUnsigned(Type t) { @@ -88,19 +89,19 @@ bool Component::IsUnsigned(Type t) uint32_t Component::Size(Type t) { - switch (t) + switch(t) { - case BYTE: - case UNSIGNED_BYTE: - return 1; - case SHORT: - case UNSIGNED_SHORT: - return 2; - case UNSIGNED_INT: - case FLOAT: - return 4; - default: - return -1; + case BYTE: + case UNSIGNED_BYTE: + return 1; + case SHORT: + case UNSIGNED_SHORT: + return 2; + case UNSIGNED_INT: + case FLOAT: + return 4; + default: + return -1; } } @@ -112,7 +113,7 @@ uint32_t AccessorType::ElementCount(Type t) AccessorType::Type AccessorType::FromString(const char* s, size_t len) { auto iFind = ACCESSOR_TYPES.find(std::string_view(s, len)); - if (iFind != ACCESSOR_TYPES.end()) + if(iFind != ACCESSOR_TYPES.end()) { return iFind->second; } @@ -122,7 +123,7 @@ AccessorType::Type AccessorType::FromString(const char* s, size_t len) AlphaMode::Type AlphaMode::FromString(const char* s, size_t len) { auto iFind = ALPHA_MODE_TYPES.find(std::string_view(s, len)); - if (iFind != ALPHA_MODE_TYPES.end()) + if(iFind != ALPHA_MODE_TYPES.end()) { return iFind->second; } @@ -132,7 +133,7 @@ AlphaMode::Type AlphaMode::FromString(const char* s, size_t len) Attribute::Type Attribute::FromString(const char* s, size_t len) { auto iFind = ATTRIBUTE_TYPES.find(std::string_view(s, len)); - if (iFind != ATTRIBUTE_TYPES.end()) + if(iFind != ATTRIBUTE_TYPES.end()) { return iFind->second; } @@ -142,7 +143,7 @@ Attribute::Type Attribute::FromString(const char* s, size_t len) Animation::Sampler::Interpolation::Type Animation::Sampler::Interpolation::FromString(const char* s, size_t len) { auto iFind = ANIMATION_SAMPLER_INTERPOLATION.find(std::string_view(s, len)); - if (iFind != ANIMATION_SAMPLER_INTERPOLATION.end()) + if(iFind != ANIMATION_SAMPLER_INTERPOLATION.end()) { return iFind->second; } @@ -160,7 +161,7 @@ Animation::Channel::Target::Type Animation::Channel::Target::FromString(const ch std::transform(target.begin(), target.end(), target.begin(), ::toupper); auto iFind = ANIMATION_CHANNEL_TARGET_PATH_TYPES.find(std::string_view(target.c_str(), len)); - if (iFind != ANIMATION_CHANNEL_TARGET_PATH_TYPES.end()) + if(iFind != ANIMATION_CHANNEL_TARGET_PATH_TYPES.end()) { return iFind->second; } @@ -172,9 +173,9 @@ void Node::SetMatrix(const Matrix& m) m.GetTransformComponents(mTranslation, mRotation, mScale); } -Quaternion ReadQuaternion(const json_value_s & j) +Quaternion ReadQuaternion(const json_value_s& j) { - return Quaternion(ReadDaliVector(j)); + return Quaternion(ReadDaliVector(j)); } -} +} // namespace gltf2 diff --git a/dali-scene-loader/internal/gltf2-asset.h b/dali-scene-loader/internal/gltf2-asset.h index 79a72db..1ec67e2 100644 --- a/dali-scene-loader/internal/gltf2-asset.h +++ b/dali-scene-loader/internal/gltf2-asset.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_GLTF2_ASSET_H_ #define DALI_SCENE_LOADER_GLTF2_ASSET_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,23 +18,22 @@ */ // INTERNAL INCLUDES -#include "dali-scene-loader/public-api/index.h" #include "dali-scene-loader/internal/json-reader.h" +#include "dali-scene-loader/public-api/index.h" // EXTERNAL INCLUDES -#include "dali/public-api/math/vector4.h" -#include "dali/public-api/math/quaternion.h" -#include "dali/public-api/common/vector-wrapper.h" -#include "dali/devel-api/common/map-wrapper.h" #include #include +#include "dali/devel-api/common/map-wrapper.h" +#include "dali/public-api/common/vector-wrapper.h" +#include "dali/public-api/math/quaternion.h" +#include "dali/public-api/math/vector4.h" namespace gltf2 { - using Index = Dali::SceneLoader::Index; -template +template class Ref { public: @@ -42,14 +41,18 @@ public: Ref(std::vector& v, Index i) : mVector(&v), mIndex(i) - {} + { + } /** * @return The index of the object into the vector. * @note It is client code responsibility to ensure that the vector is unambiguous. It should be in * a glTF document, since there's one vector for each type. */ - Index GetIndex() const { return mIndex; } + Index GetIndex() const + { + return mIndex; + } /** * @brief There may be scenarios in which the object, whose vector we're populating, changes, e.g. @@ -60,9 +63,18 @@ public: mVector = &v; } - operator bool() const { return mVector != nullptr; } - T* operator->() const { return &(*mVector)[mIndex]; } - T& operator*() const { return (*mVector)[mIndex]; } + operator bool() const + { + return mVector != nullptr; + } + T* operator->() const + { + return &(*mVector)[mIndex]; + } + T& operator*() const + { + return (*mVector)[mIndex]; + } bool operator==(const Ref& other) const { @@ -76,7 +88,7 @@ public: private: std::vector* mVector = nullptr; - Index mIndex = Dali::SceneLoader::INVALID_INDEX; + Index mIndex = Dali::SceneLoader::INVALID_INDEX; }; struct Asset @@ -88,16 +100,16 @@ struct Component { enum Type { - BYTE = 5120, - UNSIGNED_BYTE = 5121, - SHORT = 5122, + BYTE = 5120, + UNSIGNED_BYTE = 5121, + SHORT = 5122, UNSIGNED_SHORT = 5123, - UNSIGNED_INT = 5125, - FLOAT = 5126, - INVALID = -1 + UNSIGNED_INT = 5125, + FLOAT = 5126, + INVALID = -1 }; - static bool IsUnsigned(Type t); + static bool IsUnsigned(Type t); static uint32_t Size(Type t); Component() = delete; @@ -161,7 +173,7 @@ struct Attribute struct Buffer { - uint32_t mByteLength; + uint32_t mByteLength; std::string_view mUri; //TODO: extensions //TODO: extras @@ -174,7 +186,7 @@ struct BufferView enum Type { NONE, - ARRAY_BUFFER = 34962, + ARRAY_BUFFER = 34962, ELEMENT_ARRAY_BUFFER = 34963 }; @@ -182,10 +194,10 @@ struct BufferView }; Ref mBuffer; - uint32_t mByteOffset = 0; - uint32_t mByteLength; - uint32_t mByteStride = 0; // if 0 after reading, it needs to be calculated - uint32_t mTarget; + uint32_t mByteOffset = 0; + uint32_t mByteLength; + uint32_t mByteStride = 0; // if 0 after reading, it needs to be calculated + uint32_t mTarget; //TODO: extensions //TODO: extras }; @@ -193,7 +205,7 @@ struct BufferView struct BufferViewClient { Ref mBufferView; - uint32_t mByteOffset = 0; + uint32_t mByteOffset = 0; }; struct ComponentTypedBufferViewClient : BufferViewClient @@ -215,18 +227,18 @@ struct Accessor : ComponentTypedBufferViewClient, Named { struct Sparse { - uint32_t mCount; + uint32_t mCount; ComponentTypedBufferViewClient mIndices; - BufferViewClient mValues; + BufferViewClient mValues; //TODO: extensions //TODO: extras }; - uint32_t mCount; - bool mNormalized = false; - AccessorType::Type mType = AccessorType::INVALID; - std::vector mMin; - std::vector mMax; + uint32_t mCount; + bool mNormalized = false; + AccessorType::Type mType = AccessorType::INVALID; + std::vector mMin; + std::vector mMax; std::unique_ptr mSparse; //TODO: extensions //TODO: extras @@ -247,11 +259,11 @@ struct Accessor : ComponentTypedBufferViewClient, Named } }; -struct Image: Named +struct Image : Named { std::string_view mUri; std::string_view mMimeType; - Ref mBufferView; + Ref mBufferView; //TODO: extensions //TODO: extras }; @@ -260,12 +272,12 @@ struct Filter { enum Type { - NEAREST = 9728, - LINEAR = 9729, + NEAREST = 9728, + LINEAR = 9729, NEAREST_MIPMAP_NEAREST = 9984, - NEAREST_MIPMAP_LINEAR = 9985, - LINEAR_MIPMAP_NEAREST = 9986, - LINEAR_MIPMAP_LINEAR = 9987, + NEAREST_MIPMAP_LINEAR = 9985, + LINEAR_MIPMAP_NEAREST = 9986, + LINEAR_MIPMAP_LINEAR = 9987, }; Filter() = delete; @@ -275,8 +287,8 @@ struct Wrap { enum Type { - REPEAT = 10497, - CLAMP_TO_EDGE = 33071, + REPEAT = 10497, + CLAMP_TO_EDGE = 33071, MIRRORED_REPEAT = 33648, }; @@ -287,23 +299,23 @@ struct Sampler { Filter::Type mMinFilter = Filter::LINEAR; Filter::Type mMagFilter = Filter::LINEAR; - Wrap::Type mWrapS = Wrap::CLAMP_TO_EDGE; - Wrap::Type mWrapT = Wrap::CLAMP_TO_EDGE; + Wrap::Type mWrapS = Wrap::CLAMP_TO_EDGE; + Wrap::Type mWrapT = Wrap::CLAMP_TO_EDGE; //TODO: extensions //TODO: extras }; struct Texture { - Ref mSource; + Ref mSource; Ref mSampler; }; struct TextureInfo { Ref mTexture; - uint32_t mTexCoord = 0; - float mScale = 1.f; + uint32_t mTexCoord = 0; + float mScale = 1.f; operator bool() const { @@ -311,32 +323,32 @@ struct TextureInfo } }; -struct Material: Named +struct Material : Named { - struct Pbr//MetallicRoughness + struct Pbr //MetallicRoughness { Dali::Vector4 mBaseColorFactor = Dali::Vector4::ONE; - TextureInfo mBaseColorTexture; - float mMetallicFactor = 1.f; - float mRoughnessFactor = 1.f; - TextureInfo mMetallicRoughnessTexture; + TextureInfo mBaseColorTexture; + float mMetallicFactor = 1.f; + float mRoughnessFactor = 1.f; + TextureInfo mMetallicRoughnessTexture; //TODO: extensions //TODO: extras }; - Pbr mPbrMetallicRoughness; - TextureInfo mNormalTexture; - TextureInfo mOcclusionTexture; - TextureInfo mEmissiveTexture; - Dali::Vector3 mEmissiveFactor; - AlphaMode::Type mAlphaMode = AlphaMode::OPAQUE; - float mAlphaCutoff = .5f; - bool mDoubleSided = false; + Pbr mPbrMetallicRoughness; + TextureInfo mNormalTexture; + TextureInfo mOcclusionTexture; + TextureInfo mEmissiveTexture; + Dali::Vector3 mEmissiveFactor; + AlphaMode::Type mAlphaMode = AlphaMode::OPAQUE; + float mAlphaCutoff = .5f; + bool mDoubleSided = false; //TODO: extensions //TODO: extras }; -struct Mesh: Named +struct Mesh : Named { struct Primitive { @@ -352,11 +364,11 @@ struct Mesh: Named INVALID }; - std::map> mAttributes; + std::map> mAttributes; std::vector>> mTargets; - Ref mIndices; - Ref mMaterial; - Mode mMode = TRIANGLES; + Ref mIndices; + Ref mMaterial; + Mode mMode = TRIANGLES; //TODO: [morph] targets //TODO: extras @@ -364,7 +376,7 @@ struct Mesh: Named }; std::vector mPrimitives; - std::vector mWeights; + std::vector mWeights; //TODO: extras //TODO: extensions }; @@ -373,14 +385,14 @@ struct Node; struct Skin : Named { - Ref mInverseBindMatrices; - Ref mSkeleton; + Ref mInverseBindMatrices; + Ref mSkeleton; std::vector> mJoints; //TODO: extras //TODO: extensions }; -struct Camera: Named +struct Camera : Named { struct Perspective { @@ -403,21 +415,21 @@ struct Camera: Named }; std::string_view mType; - Perspective mPerspective; - Orthographic mOrthographic; + Perspective mPerspective; + Orthographic mOrthographic; //TODO: extras //TODO: extensions }; -struct Node: Named +struct Node : Named { - Dali::Vector3 mTranslation = Dali::Vector3::ZERO; - Dali::Quaternion mRotation = Dali::Quaternion::IDENTITY; - Dali::Vector3 mScale = Dali::Vector3::ONE; + Dali::Vector3 mTranslation = Dali::Vector3::ZERO; + Dali::Quaternion mRotation = Dali::Quaternion::IDENTITY; + Dali::Vector3 mScale = Dali::Vector3::ONE; - Ref mCamera; + Ref mCamera; std::vector> mChildren; - Ref mMesh; + Ref mMesh; Ref mSkin; //TODO: [morph] weights @@ -443,8 +455,8 @@ struct Animation : Named static Type FromString(const char* s, size_t len); }; - Ref mInput; - Ref mOutput; + Ref mInput; + Ref mOutput; Interpolation::Type mInterpolation; //TODO: extras @@ -467,11 +479,11 @@ struct Animation : Named static Type FromString(const char* s, size_t len); Ref mNode; - Type mPath; + Type mPath; }; Ref mSampler; - Target mTarget; + Target mTarget; //TODO: extras //TODO: extensions }; @@ -480,7 +492,7 @@ struct Animation : Named std::vector mChannels; }; -struct Scene: Named +struct Scene : Named { std::vector> mNodes; }; @@ -489,29 +501,29 @@ struct Document { Asset mAsset; - std::vector mBuffers; + std::vector mBuffers; std::vector mBufferViews; - std::vector mAccessors; + std::vector mAccessors; - std::vector mImages; - std::vector mSamplers; - std::vector mTextures; + std::vector mImages; + std::vector mSamplers; + std::vector mTextures; std::vector mMaterials; std::vector mMeshes; std::vector mSkins; std::vector mCameras; - std::vector mNodes; + std::vector mNodes; std::vector mAnimations; std::vector mScenes; - Ref mScene; + Ref mScene; - Document() = default; + Document() = default; Document(const Document&) = delete; - Document(Document&&) = default; + Document(Document&&) = default; Document& operator=(const Document&) = delete; Document& operator=(Document&&) = default; @@ -521,12 +533,12 @@ struct Document * @brief Provides a json::Property::ReadFn for interpreting unsigned integers * as a Ref into a std::vector data member of a type T. */ -template +template struct RefReader { static T* sObject; - template T::* V> + template T::*V> static Ref Read(const json_value_s& j) { uint32_t index = json::Read::Number(j); @@ -534,13 +546,13 @@ struct RefReader } }; -template +template T* RefReader::sObject = nullptr; /** * @brief Convenience method to set the object for RefReader. */ -template +template void SetRefReaderObject(T& object) { RefReader::sObject = &object; @@ -551,7 +563,7 @@ void SetRefReaderObject(T& object) * @note The enum must: 1, be called Type, nested to T, 2, provide a FromString static method taking a const char* * (string data) and a size_t (string length) and returning T::Type. */ -template // T must have a nested enum called Type and a static Type FromString(const char*) method. +template // T must have a nested enum called Type and a static Type FromString(const char*) method. typename T::Type ReadStringEnum(const json_value_s& j) { auto str = json::Read::StringView(j); @@ -564,12 +576,11 @@ typename T::Type ReadStringEnum(const json_value_s& j) * @note T must provide an AsFloat() member method returning the non-const array of its * float components. */ -template -inline -T ReadDaliVector(const json_value_s& j) +template +inline T ReadDaliVector(const json_value_s& j) { std::vector floats = json::Read::Array>(j); - T result; + T result; std::copy(floats.begin(), std::min(floats.end(), floats.begin() + sizeof(T) / sizeof(float)), result.AsFloat()); return result; } @@ -580,6 +591,6 @@ T ReadDaliVector(const json_value_s& j) */ Dali::Quaternion ReadQuaternion(const json_value_s& j); -} +} // namespace gltf2 #endif //DALI_SCENE_LOADER_GLTF2_ASSET_H_ diff --git a/dali-scene-loader/internal/hash.cpp b/dali-scene-loader/internal/hash.cpp index e863f0a..43d410f 100644 --- a/dali-scene-loader/internal/hash.cpp +++ b/dali-scene-loader/internal/hash.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ namespace Dali { namespace SceneLoader { - Hash::Hash(uint64_t initial) : mValue(initial) -{} +{ +} Hash& Hash::Add(bool b) { @@ -54,26 +54,26 @@ Hash& Hash::Add(float f) return AddObjectBytes(f); } -Hash& Hash::Add(const char * cStr) +Hash& Hash::Add(const char* cStr) { return Add(cStr, strlen(cStr)); } -Hash& Hash::Add(const char * cStr, size_t len) +Hash& Hash::Add(const char* cStr, size_t len) { auto i0 = reinterpret_cast(cStr); return AddBytes(i0, i0 + len); } -Hash& Hash::Add(const std::string & str) +Hash& Hash::Add(const std::string& str) { auto i0 = reinterpret_cast(str.c_str()); return AddBytes(i0, i0 + str.size()); } -Hash& Hash::AddBytes(const uint8_t * i0, const uint8_t * i1) +Hash& Hash::AddBytes(const uint8_t* i0, const uint8_t* i1) { - while (i0 != i1) + while(i0 != i1) { mValue = Concatenate(*i0); ++i0; @@ -91,5 +91,5 @@ uint64_t Hash::Concatenate(uint64_t value) return mValue * 31 + value; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/internal/hash.h b/dali-scene-loader/internal/hash.h index 32c69da..22b770e 100644 --- a/dali-scene-loader/internal/hash.h +++ b/dali-scene-loader/internal/hash.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_HASH_H_ #define DALI_SCENE_LOADER_HASH_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,15 +17,14 @@ * */ -#include -#include #include +#include +#include namespace Dali { namespace SceneLoader { - /** * @brief Rudimentary hash generator that follows a builder pattern. */ @@ -94,7 +93,7 @@ public: * @brief Applies the bytes of an object @a value, to the hash. * @return Its updated self. */ - template + template Hash& AddObjectBytes(const T& value); operator uint64_t() const; @@ -105,13 +104,12 @@ private: uint64_t Concatenate(uint64_t value); }; - template -Hash& Hash::AddObjectBytes(const T & value) +Hash& Hash::AddObjectBytes(const T& value) { auto i0 = reinterpret_cast(&value); auto i1 = i0 + sizeof(T); - while (i0 != i1) + while(i0 != i1) { mValue = Concatenate(*i0); ++i0; @@ -119,7 +117,7 @@ Hash& Hash::AddObjectBytes(const T & value) return *this; } -} -} +} // namespace SceneLoader +} // namespace Dali #endif // DALI_SCENE_LOADER_HASH_H_ diff --git a/dali-scene-loader/internal/json-reader.cpp b/dali-scene-loader/internal/json-reader.cpp index 6b12d1d..0353817 100644 --- a/dali-scene-loader/internal/json-reader.cpp +++ b/dali-scene-loader/internal/json-reader.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2020 Samsung Electronics Co., Ltd. +* Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,28 +20,25 @@ namespace json { - int StrCmp(const json_string_s& js, const char* s) { - auto sSize = strlen(s); + auto sSize = strlen(s); auto shorter = std::min(js.string_size, sSize); - auto base = strncmp(js.string, s, shorter); - return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? - -s[shorter] : js.string[shorter]); + auto base = strncmp(js.string, s, shorter); + return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? -s[shorter] : js.string[shorter]); } int StrCmp(const json_string_s& js, const std::string& s) { - auto sSize = s.size(); + auto sSize = s.size(); auto shorter = std::min(js.string_size, sSize); - auto base = strncmp(js.string, s.c_str(), shorter); - return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? - -s[shorter] : js.string[shorter]); + auto base = strncmp(js.string, s.c_str(), shorter); + return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? -s[shorter] : js.string[shorter]); } -void Validate(const json_value_s & jv, json_type_e type) +void Validate(const json_value_s& jv, json_type_e type) { - if (jv.type != type) + if(jv.type != type) { throw std::runtime_error("Invalid type; expected: " + std::to_string(type) + ", got: " + std::to_string(jv.type)); } @@ -50,9 +47,9 @@ void Validate(const json_value_s & jv, json_type_e type) json_value_s* FindObjectChild(const std::string& key, json_object_s& obj) { auto i = obj.start; - while (i) + while(i) { - if (0 == StrCmp(*i->name, key)) + if(0 == StrCmp(*i->name, key)) { return i->value; } @@ -61,4 +58,4 @@ json_value_s* FindObjectChild(const std::string& key, json_object_s& obj) return nullptr; } -} +} // namespace json diff --git a/dali-scene-loader/internal/json-reader.h b/dali-scene-loader/internal/json-reader.h index 2f769a7..4fb6f7a 100644 --- a/dali-scene-loader/internal/json-reader.h +++ b/dali-scene-loader/internal/json-reader.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_JSON_READER_H_ #define DALI_SCENE_LOADER_JSON_READER_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,17 +21,16 @@ #include "dali-scene-loader/third-party/json.h" // EXTERNAL INCLUDES -#include "dali/public-api/common/vector-wrapper.h" #include -#include -#include -#include #include +#include #include +#include +#include +#include "dali/public-api/common/vector-wrapper.h" namespace json { - /** * @brief Helper for freeing the memory allocated by json_parse() */ @@ -60,9 +59,8 @@ int StrCmp(const json_string_s& js, const std::string& s); * @brief Convenience function to compare json_string_s and other supported string type, * in swapped order. */ -template -inline -int StrCmp(String& s, const json_string_s& js) +template +inline int StrCmp(String& s, const json_string_s& js) { return -StrCmp(js, s); } @@ -77,28 +75,33 @@ namespace detail /** * @brief Compile-time type-enum mapping. */ -template +template struct Type2Enum -{}; - -#define TYPE2ENUM(x) template<> struct Type2Enum\ -{\ - enum { VALUE = json_type_## x };\ +{ }; +#define TYPE2ENUM(x) \ + template<> \ + struct Type2Enum \ + { \ + enum \ + { \ + VALUE = json_type_##x \ + }; \ + }; + TYPE2ENUM(object) TYPE2ENUM(array) TYPE2ENUM(string) TYPE2ENUM(number) #undef TYPE2ENUM -} +} // namespace detail /** * @brief Casts the payload of a json_value_s to the given type. */ -template -inline -const Out& Cast(const json_value_s& j) +template +inline const Out& Cast(const json_value_s& j) { Validate(j, static_cast(detail::Type2Enum::type>::VALUE)); return *static_cast(j.payload); @@ -108,9 +111,8 @@ const Out& Cast(const json_value_s& j) * @brief Casts the payload of a json_value_s to the given type. * @note std::runtime_error is thrown if the value is not the given type. */ -template -inline -Out& Cast(json_value_s& j) +template +inline Out& Cast(json_value_s& j) { Validate(j, static_cast(detail::Type2Enum::type>::VALUE)); return *static_cast(j.payload); @@ -129,11 +131,11 @@ struct Read { static bool Boolean(const json_value_s& j) { - if (j.type == json_type_true) + if(j.type == json_type_true) { return true; } - else if (j.type == json_type_false) + else if(j.type == json_type_false) { return false; } @@ -143,25 +145,25 @@ struct Read } } - template + template static T Number(const json_value_s& j) { - auto& jn = Cast(j); + auto& jn = Cast(j); std::stringstream ss; - for (auto i0 = jn.number, i1 = i0 + jn.number_size; i0 != i1; ++i0) + for(auto i0 = jn.number, i1 = i0 + jn.number_size; i0 != i1; ++i0) { ss.put(*i0); } T result; - if (ss >> result) + if(ss >> result) { return result; } throw std::runtime_error("Failed to convert value to number"); } - template + template static E Enum(const json_value_s& j) { size_t number = Number(j); @@ -180,14 +182,14 @@ struct Read return std::string(js.string, js.string_size); } - template + template static std::vector Array(const json_value_s& j) { - auto& ja = Cast(j); + auto& ja = Cast(j); std::vector result; result.reserve(ja.length); auto i = ja.start; - while (i) + while(i) { result.push_back(std::move(readElement(*i->value))); i = i->next; @@ -204,9 +206,13 @@ struct PropertyCore protected: explicit PropertyCore(const std::string& key) : mKey(key) - {} + { + } - const std::string& GetKey() const { return mKey; } + const std::string& GetKey() const + { + return mKey; + } private: std::string mKey; @@ -215,17 +221,19 @@ private: /** * @brief Base class for the properties of a type T. */ -template +template struct PropertyBase : PropertyCore { using PropertyCore::GetKey; explicit PropertyBase(const std::string& key) : PropertyCore(key) - {} + { + } virtual ~PropertyBase() - {} + { + } virtual void Read(const json_value_s& j, T& obj) = 0; }; @@ -233,28 +241,31 @@ struct PropertyBase : PropertyCore /** * @brief Concrete property of an object to read into from JSON with a given function. */ -template +template struct Property : PropertyBase { - using ReadFn = U(*)(const json_value_s&); - using MemberPtr = U T::*; + using ReadFn = U (*)(const json_value_s&); + using MemberPtr = U T::*; using SetterArgType = typename std::conditional::type; - using Setter = void (T::*)(SetterArgType); + using Setter = void (T::*)(SetterArgType); Property(const std::string& key, ReadFn read, MemberPtr ptr) : PropertyBase(key), mRead(read), mAccessor(new DirectAccessor(ptr)) - {} + { + } Property(const std::string& key, ReadFn read, Setter setter) : PropertyBase(key), mRead(read), mAccessor(new SetterAccessor(setter)) - {} + { + } ~Property() - {} + { + } void Read(const json_value_s& j, T& obj) override { @@ -265,7 +276,8 @@ private: struct AccessorBase { virtual ~AccessorBase() - {} + { + } virtual void Set(U value, T& obj) const = 0; }; @@ -274,7 +286,8 @@ private: { DirectAccessor(MemberPtr ptr) : mPointer(ptr) - {} + { + } void Set(U value, T& obj) const override { @@ -288,7 +301,8 @@ private: { SetterAccessor(Setter setter) : mSetter(setter) - {} + { + } void Set(U value, T& obj) const override { @@ -298,16 +312,15 @@ private: Setter mSetter; }; - ReadFn mRead; + ReadFn mRead; std::unique_ptr mAccessor; }; /** * @brief Helper function to make a Property for a member of type U, of object of type T. */ -template -Property* MakeProperty(const std::string& key, typename Property::ReadFn readFn, - U T::* ptr) +template +Property* MakeProperty(const std::string& key, typename Property::ReadFn readFn, U T::*ptr) { return new Property(key, readFn, ptr); } @@ -333,7 +346,7 @@ protected: * @brief Object Reader template for reading into an object of a given type, * with properties registered for the various members. */ -template +template class Reader : protected ReaderCore { public: @@ -347,7 +360,7 @@ public: ~Reader() { - for (auto& p : mProperties) + for(auto& p : mProperties) { delete Cast(p); } @@ -355,9 +368,8 @@ public: Reader& Register(PropertyBase& prop) { - auto iInsert = std::lower_bound(mProperties.begin(), mProperties.end(), &prop, - SortPredicate); - if (iInsert == mProperties.end() || Cast(*iInsert)->GetKey() != prop.GetKey()) + auto iInsert = std::lower_bound(mProperties.begin(), mProperties.end(), &prop, SortPredicate); + if(iInsert == mProperties.end() || Cast(*iInsert)->GetKey() != prop.GetKey()) { mProperties.insert(iInsert, &prop); } @@ -372,14 +384,13 @@ public: void Read(const json_object_s& jo, T& obj) const { auto i = jo.start; - while (i) + while(i) { - auto iFind = std::lower_bound(mProperties.begin(), mProperties.end(), - *i->name, FindPredicate); - if (iFind != mProperties.end()) + auto iFind = std::lower_bound(mProperties.begin(), mProperties.end(), *i->name, FindPredicate); + if(iFind != mProperties.end()) { auto prop = Cast(*iFind); - if (0 == StrCmp(*i->name, prop->GetKey())) + if(0 == StrCmp(*i->name, prop->GetKey())) { prop->Read(*i->value, obj); } @@ -411,29 +422,29 @@ private: * @brief Wraps a Reader in a function usable as a Property::ReadFn, i.e. to facilitate * deserializing structures of nested objects. */ -template +template struct ObjectReader { static const Reader* sReader; static T Read(const json_value_s& j) { - T result; + T result; auto& jo = Cast(j); sReader->Read(jo, result); return result; } }; -template +template const Reader* ObjectReader::sReader = nullptr; -template +template void SetObjectReader(const Reader& r) { ObjectReader::sReader = &r; } -} // json +} // namespace json #endif //DALI_SCENE_LOADER_JSON_READER_H_ diff --git a/dali-scene-loader/internal/json-util.cpp b/dali-scene-loader/internal/json-util.cpp index 613a764..765568d 100644 --- a/dali-scene-loader/internal/json-util.cpp +++ b/dali-scene-loader/internal/json-util.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,16 @@ #include "dali-scene-loader/internal/json-util.h" // EXTERNAL INCLUDES +#include +#include "dali/devel-api/common/map-wrapper.h" #include "dali/public-api/common/extents.h" -#include "dali/public-api/math/matrix3.h" #include "dali/public-api/math/matrix.h" +#include "dali/public-api/math/matrix3.h" #include "dali/public-api/math/quaternion.h" #include "dali/public-api/math/radian.h" #include "dali/public-api/math/vector2.h" #include "dali/public-api/math/vector3.h" #include "dali/public-api/object/property-value.h" -#include "dali/devel-api/common/map-wrapper.h" -#include namespace Dali { @@ -36,24 +36,23 @@ namespace SceneLoader { namespace { - -template -Property::Value ReadPrimitiveHelper(const TreeNode* tn, bool(*reader)(const TreeNode*, T&)) +template +Property::Value ReadPrimitiveHelper(const TreeNode* tn, bool (*reader)(const TreeNode*, T&)) { T value; - if (reader(tn, value)) + if(reader(tn, value)) { return Property::Value(value); } return Property::Value(); } -template +template Property::Value ReadVectorHelper(const TreeNode* tn) { static_assert(sizeof(T) % sizeof(float) == 0, ""); T value; - if (ReadVector(tn, value.AsFloat(), sizeof(T) / sizeof(float))) + if(ReadVector(tn, value.AsFloat(), sizeof(T) / sizeof(float))) { return Property::Value(value); } @@ -63,7 +62,7 @@ Property::Value ReadVectorHelper(const TreeNode* tn) Property::Value ReadVectorSingleFloatHelper(const TreeNode* tn) { float value; - if (ReadVector(tn, &value, 1u)) + if(ReadVector(tn, &value, 1u)) { return Property::Value(value); } @@ -72,39 +71,39 @@ Property::Value ReadVectorSingleFloatHelper(const TreeNode* tn) Property::Value ReadRotationHelper(const TreeNode* tn) { - switch (tn->Size()) - { - case 3: - { - // degrees as per spec - Vector3 rotation; - ReadVector(tn, rotation.AsFloat(), 3u); - return Property::Value(Quaternion(Radian(Degree(rotation.x)), - Radian(Degree(rotation.y)), - Radian(Degree(rotation.z)))); - } - case 4: + switch(tn->Size()) { - Vector4 v; - ReadVector(tn, v.AsFloat(), 4u); - //Quaternion - return Property::Value(Quaternion(v)); - } - default: - return Property::Value(); + case 3: + { + // degrees as per spec + Vector3 rotation; + ReadVector(tn, rotation.AsFloat(), 3u); + return Property::Value(Quaternion(Radian(Degree(rotation.x)), + Radian(Degree(rotation.y)), + Radian(Degree(rotation.z)))); + } + case 4: + { + Vector4 v; + ReadVector(tn, v.AsFloat(), 4u); + //Quaternion + return Property::Value(Quaternion(v)); + } + default: + return Property::Value(); } } -template +template bool ReadQuadHelper(const TreeNode* tn, const std::array& quad) { - auto i = quad.begin(); - auto iEnd = quad.end(); + auto i = quad.begin(); + auto iEnd = quad.end(); auto iJson = tn->CBegin(); - while (iJson != tn->CEnd() && i != iEnd) + while(iJson != tn->CEnd() && i != iEnd) { int value; - if (ReadInt(&(*iJson).second, value) && value <= std::numeric_limits::max()) + if(ReadInt(&(*iJson).second, value) && value <= std::numeric_limits::max()) { **i = value; ++i; @@ -118,66 +117,65 @@ bool ReadQuadHelper(const TreeNode* tn, const std::array& quad) return true; } -const std::map kTypeIds { +const std::map kTypeIds{ // NONE - { "boolean", [](const TreeNode* tn) { - return ReadPrimitiveHelper(tn, ReadBool); - }}, - { "float", [](const TreeNode* tn) { - return ReadPrimitiveHelper(tn, ReadFloat); - }}, - { "integer", [](const TreeNode* tn) { - return ReadPrimitiveHelper(tn, ReadInt); - }}, - { "vector2", ReadVectorHelper }, - { "vector3", ReadVectorHelper }, - { "vector4", ReadVectorHelper }, - { "matrix3", ReadVectorHelper }, - { "matrix", ReadVectorHelper }, - { "rectangle", [](const TreeNode* tn) { - Rect value; - if (ReadQuadHelper(tn, { &value.x, &value.y, &value.width, &value.height })) - { - return Property::Value(value); - } - return Property::Value(); - }}, - { "rotation", ReadRotationHelper }, + {"boolean", [](const TreeNode* tn) { + return ReadPrimitiveHelper(tn, ReadBool); + }}, + {"float", [](const TreeNode* tn) { + return ReadPrimitiveHelper(tn, ReadFloat); + }}, + {"integer", [](const TreeNode* tn) { + return ReadPrimitiveHelper(tn, ReadInt); + }}, + {"vector2", ReadVectorHelper}, + {"vector3", ReadVectorHelper}, + {"vector4", ReadVectorHelper}, + {"matrix3", ReadVectorHelper}, + {"matrix", ReadVectorHelper}, + {"rectangle", [](const TreeNode* tn) { + Rect value; + if(ReadQuadHelper(tn, {&value.x, &value.y, &value.width, &value.height})) + { + return Property::Value(value); + } + return Property::Value(); + }}, + {"rotation", ReadRotationHelper}, // STRING - not particularly animatable // ARRAY - not particularly animatable // MAP - not particularly animatable - { "extents", [](const TreeNode* tn) { - Extents value; - if (ReadQuadHelper(tn, { &value.start, &value.end, &value.top, &value.bottom })) - { - return Property::Value(value); - } - return Property::Value(); - }}, + {"extents", [](const TreeNode* tn) { + Extents value; + if(ReadQuadHelper(tn, {&value.start, &value.end, &value.top, &value.bottom})) + { + return Property::Value(value); + } + return Property::Value(); + }}, }; -Property::Value(* const kArrayPropertyProcessors[])(const TreeNode*) { +Property::Value (*const kArrayPropertyProcessors[])(const TreeNode*){ ReadVectorHelper, ReadVectorHelper, ReadVectorHelper, ReadVectorHelper, ReadVectorHelper, - ReadVectorSingleFloatHelper -}; + ReadVectorSingleFloatHelper}; -} // nonamespace +} // namespace bool ReadBool(const TreeNode* node, bool& num) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if (node->GetType() == TreeNode::BOOLEAN) + if(node->GetType() == TreeNode::BOOLEAN) { - num = node->GetBoolean(); + num = node->GetBoolean(); returnValue = true; } @@ -186,20 +184,20 @@ bool ReadBool(const TreeNode* node, bool& num) bool ReadInt(const TreeNode* node, int& num) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if (node->GetType() == TreeNode::INTEGER) + if(node->GetType() == TreeNode::INTEGER) { - num = node->GetInteger(); + num = node->GetInteger(); returnValue = true; } - else if (node->GetType() == TreeNode::FLOAT) + else if(node->GetType() == TreeNode::FLOAT) { - num = static_cast(node->GetFloat()); + num = static_cast(node->GetFloat()); returnValue = true; } @@ -208,20 +206,20 @@ bool ReadInt(const TreeNode* node, int& num) bool ReadFloat(const TreeNode* node, float& num) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if (node->GetType() == TreeNode::FLOAT) + if(node->GetType() == TreeNode::FLOAT) { - num = node->GetFloat(); + num = node->GetFloat(); returnValue = true; } - else if (node->GetType() == TreeNode::INTEGER) + else if(node->GetType() == TreeNode::INTEGER) { - num = static_cast(node->GetInteger()); + num = static_cast(node->GetInteger()); returnValue = true; } @@ -231,7 +229,7 @@ bool ReadFloat(const TreeNode* node, float& num) bool ReadIndex(const Toolkit::TreeNode* node, Index& num) { bool returnValue = node && node->GetType() == TreeNode::INTEGER; - if (returnValue) + if(returnValue) { num = static_cast(node->GetInteger()); } @@ -241,19 +239,19 @@ bool ReadIndex(const Toolkit::TreeNode* node, Index& num) bool ReadBlob(const Toolkit::TreeNode* node, unsigned int& offset, unsigned int& length) { - if (!node) + if(!node) { return false; } - int iOffset, iLength; + int iOffset, iLength; bool success = ReadInt(node->GetChild("byteOffset"), iOffset) && - ReadInt(node->GetChild("byteLength"), iLength) && - iOffset >= 0 && iLength >= 0; // 0 length might not be sensible, but is not an error at this stage. - if (success) + ReadInt(node->GetChild("byteLength"), iLength) && + iOffset >= 0 && iLength >= 0; // 0 length might not be sensible, but is not an error at this stage. + if(success) { - offset = static_cast( iOffset ); - length = static_cast( iLength ); + offset = static_cast(iOffset); + length = static_cast(iLength); } return success; } @@ -261,11 +259,11 @@ bool ReadBlob(const Toolkit::TreeNode* node, unsigned int& offset, unsigned int& size_t GetNumericalArraySize(const TreeNode* node) { size_t size = 0; - if (node->GetType() == TreeNode::ARRAY) + if(node->GetType() == TreeNode::ARRAY) { - for (auto i0 = node->CBegin(), i1 = node->CEnd(); i0 != i1 && - ((*i0).second.GetType() == TreeNode::FLOAT || (*i0).second.GetType() == TreeNode::INTEGER); - ++i0) + for(auto i0 = node->CBegin(), i1 = node->CEnd(); i0 != i1 && + ((*i0).second.GetType() == TreeNode::FLOAT || (*i0).second.GetType() == TreeNode::INTEGER); + ++i0) { ++size; } @@ -275,19 +273,19 @@ size_t GetNumericalArraySize(const TreeNode* node) bool ReadVector(const TreeNode* node, float* num, unsigned int size) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if ((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY)) + if((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY)) { unsigned int offset = 0u; - for (TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset) + for(TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset) { const TreeNode& coord = (*it).second; - if (!ReadFloat(&coord, *(num + offset))) + if(!ReadFloat(&coord, *(num + offset))) { return false; } @@ -300,19 +298,19 @@ bool ReadVector(const TreeNode* node, float* num, unsigned int size) bool ReadVector(const Toolkit::TreeNode* node, int* num, unsigned int size) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if ((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY)) + if((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY)) { unsigned int offset = 0u; - for (TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset) + for(TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset) { const TreeNode& coord = (*it).second; - if (!ReadInt(&coord, *(num + offset))) + if(!ReadInt(&coord, *(num + offset))) { return false; } @@ -325,14 +323,14 @@ bool ReadVector(const Toolkit::TreeNode* node, int* num, unsigned int size) bool ReadColor(const TreeNode* node, Vector4& color) { - if (nullptr == node) + if(nullptr == node) { return false; } - if (!ReadVector(node, color.AsFloat(), 4)) + if(!ReadVector(node, color.AsFloat(), 4)) { - if (!ReadVector(node, color.AsFloat(), 3)) + if(!ReadVector(node, color.AsFloat(), 3)) { return false; } @@ -344,12 +342,12 @@ bool ReadColor(const TreeNode* node, Vector4& color) bool ReadTimePeriod(const TreeNode* node, TimePeriod& timePeriod) { - if (!node) + if(!node) { return false; } - if (!ReadFloat(node->GetChild("delay"), timePeriod.delaySeconds) || !ReadFloat(node->GetChild("duration"), timePeriod.durationSeconds)) + if(!ReadFloat(node->GetChild("delay"), timePeriod.delaySeconds) || !ReadFloat(node->GetChild("duration"), timePeriod.durationSeconds)) { return false; } @@ -358,15 +356,15 @@ bool ReadTimePeriod(const TreeNode* node, TimePeriod& timePeriod) bool ReadString(const TreeNode* node, std::string& strValue) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if (node->GetType() == TreeNode::STRING) + if(node->GetType() == TreeNode::STRING) { - strValue = node->GetString(); + strValue = node->GetString(); returnValue = true; } return returnValue; @@ -374,18 +372,18 @@ bool ReadString(const TreeNode* node, std::string& strValue) bool ReadStringVector(const TreeNode* node, std::vector& strvector) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if (node->GetType() == TreeNode::ARRAY) + if(node->GetType() == TreeNode::ARRAY) { - for (TreeNode::ConstIterator it = node->CBegin(); it != node->CEnd(); ++it) + for(TreeNode::ConstIterator it = node->CBegin(); it != node->CEnd(); ++it) { const TreeNode& strNode = (*it).second; - if (strNode.GetType() == TreeNode::STRING) + if(strNode.GetType() == TreeNode::STRING) { strvector.push_back(strNode.GetString()); } @@ -401,60 +399,60 @@ bool ReadStringVector(const TreeNode* node, std::vector& strvector) Property::Value ReadPropertyValue(const Property::Type& propType, const TreeNode& tn) { - switch (propType) + switch(propType) { - case Property::BOOLEAN: - return ReadPrimitiveHelper(&tn, ReadBool); + case Property::BOOLEAN: + return ReadPrimitiveHelper(&tn, ReadBool); - case Property::FLOAT: - return ReadPrimitiveHelper(&tn, ReadFloat); + case Property::FLOAT: + return ReadPrimitiveHelper(&tn, ReadFloat); - case Property::INTEGER: - return ReadPrimitiveHelper(&tn, ReadInt); + case Property::INTEGER: + return ReadPrimitiveHelper(&tn, ReadInt); - case Property::VECTOR2: - return ReadVectorHelper(&tn); + case Property::VECTOR2: + return ReadVectorHelper(&tn); - case Property::VECTOR3: - return ReadVectorHelper(&tn); + case Property::VECTOR3: + return ReadVectorHelper(&tn); - case Property::VECTOR4: - return ReadVectorHelper(&tn); + case Property::VECTOR4: + return ReadVectorHelper(&tn); - case Property::MATRIX3: - return ReadVectorHelper(&tn); + case Property::MATRIX3: + return ReadVectorHelper(&tn); - case Property::MATRIX: - return ReadVectorHelper(&tn); + case Property::MATRIX: + return ReadVectorHelper(&tn); - case Property::RECTANGLE: - { - Rect value; - if (ReadQuadHelper(&tn, { &value.x, &value.y, &value.width, &value.height })) + case Property::RECTANGLE: { - return Property::Value(value); + Rect value; + if(ReadQuadHelper(&tn, {&value.x, &value.y, &value.width, &value.height})) + { + return Property::Value(value); + } + break; } - break; - } - case Property::ROTATION: - return ReadRotationHelper(&tn); + case Property::ROTATION: + return ReadRotationHelper(&tn); - case Property::EXTENTS: - { - Extents value; - if (ReadQuadHelper(&tn, { &value.start, &value.end, &value.top, &value.bottom })) + case Property::EXTENTS: { - return Property::Value(value); + Extents value; + if(ReadQuadHelper(&tn, {&value.start, &value.end, &value.top, &value.bottom})) + { + return Property::Value(value); + } + break; } - break; - } - case Property::NONE: // fall - default: - { - DALI_ASSERT_ALWAYS(!"Property type incorrect"); - } + case Property::NONE: // fall + default: + { + DALI_ASSERT_ALWAYS(!"Property type incorrect"); + } } return Property::Value(); } @@ -462,45 +460,45 @@ Property::Value ReadPropertyValue(const Property::Type& propType, const TreeNode Property::Value ReadPropertyValue(const Toolkit::TreeNode& tn) { Property::Value propValue; - if (tn.GetType() == TreeNode::OBJECT) // attempt to disambiguate type. + if(tn.GetType() == TreeNode::OBJECT) // attempt to disambiguate type. { auto jsonType = tn.GetChild("type"); - if (jsonType && jsonType->GetType() == TreeNode::STRING) + if(jsonType && jsonType->GetType() == TreeNode::STRING) { auto iFind = kTypeIds.find(jsonType->GetString()); - if (iFind != kTypeIds.end()) + if(iFind != kTypeIds.end()) { propValue = iFind->second(tn.GetChild("value")); } } } - if (propValue.GetType() == Property::NONE) + if(propValue.GetType() == Property::NONE) { - if (tn.Size() == 0) + if(tn.Size() == 0) { - switch (tn.GetType()) + switch(tn.GetType()) { - case TreeNode::BOOLEAN: - propValue = ReadPrimitiveHelper(&tn, ReadBool); - break; + case TreeNode::BOOLEAN: + propValue = ReadPrimitiveHelper(&tn, ReadBool); + break; - case TreeNode::INTEGER: - propValue = ReadPrimitiveHelper(&tn, ReadInt); - break; + case TreeNode::INTEGER: + propValue = ReadPrimitiveHelper(&tn, ReadInt); + break; - case TreeNode::FLOAT: - propValue = ReadPrimitiveHelper(&tn, ReadFloat); - break; + case TreeNode::FLOAT: + propValue = ReadPrimitiveHelper(&tn, ReadFloat); + break; - default: - break; + default: + break; } } else { bool allNumbers = true; - for (auto i0 = tn.CBegin(), i1 = tn.CEnd(); i0 != i1; ++i0) + for(auto i0 = tn.CBegin(), i1 = tn.CEnd(); i0 != i1; ++i0) { auto type = (*i0).second.GetType(); if(!(type == TreeNode::FLOAT || type == TreeNode::INTEGER)) @@ -510,13 +508,13 @@ Property::Value ReadPropertyValue(const Toolkit::TreeNode& tn) } } - if (allNumbers) + if(allNumbers) { // NOTE: rotations / rectangles / extents must be disambiguated in all circumstances. - for (auto& r : kArrayPropertyProcessors) + for(auto& r : kArrayPropertyProcessors) { propValue = r(&tn); - if (propValue.GetType() != Property::NONE) + if(propValue.GetType() != Property::NONE) { break; } @@ -527,5 +525,5 @@ Property::Value ReadPropertyValue(const Toolkit::TreeNode& tn) return propValue; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/internal/json-util.h b/dali-scene-loader/internal/json-util.h index 64a99cd..9121bcd 100644 --- a/dali-scene-loader/internal/json-util.h +++ b/dali-scene-loader/internal/json-util.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_JSON_UTIL_H_ #define DALI_SCENE_LOADER_JSON_UTIL_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,17 +21,16 @@ #include "dali-scene-loader/public-api/index.h" // EXTERNAL INCLUDES -#include "dali/public-api/common/vector-wrapper.h" +#include "dali-toolkit/devel-api/builder/tree-node.h" #include "dali/public-api/animation/time-period.h" -#include "dali/public-api/object/property.h" +#include "dali/public-api/common/vector-wrapper.h" #include "dali/public-api/math/vector4.h" -#include "dali-toolkit/devel-api/builder/tree-node.h" +#include "dali/public-api/object/property.h" namespace Dali { namespace SceneLoader { - bool ReadBool(const Toolkit::TreeNode* node, bool& num); bool ReadInt(const Toolkit::TreeNode* node, int& num); @@ -89,7 +88,7 @@ Property::Value ReadPropertyValue(const Property::Type& propType, const Toolkit: */ Property::Value ReadPropertyValue(const Toolkit::TreeNode& tn); -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_JSON_UTIL_H_ diff --git a/dali-scene-loader/public-api/alpha-function-helper.cpp b/dali-scene-loader/public-api/alpha-function-helper.cpp index 33ad3db..b5168e0 100644 --- a/dali-scene-loader/public-api/alpha-function-helper.cpp +++ b/dali-scene-loader/public-api/alpha-function-helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,10 +23,11 @@ namespace SceneLoader { namespace { - +// clang-format off #define DALI_ALPHA_FUNCTION_ENTRY(x) { #x, AlphaFunction::x } +// clang-format on -std::unordered_map sFunctions { +std::unordered_map sFunctions{ DALI_ALPHA_FUNCTION_ENTRY(DEFAULT), DALI_ALPHA_FUNCTION_ENTRY(LINEAR), DALI_ALPHA_FUNCTION_ENTRY(REVERSE), @@ -45,24 +46,24 @@ std::unordered_map sFunctions { #undef DALI_ALPHA_FUNCTION_ENTRY -} // nonamespace +} // namespace AlphaFunction GetAlphaFunction(const std::string& name, bool* found) { - auto iFind = sFunctions.find(name); + auto iFind = sFunctions.find(name); bool success = iFind != sFunctions.end(); - if (found) + if(found) { *found = success; } return success ? iFind->second : AlphaFunction(AlphaFunction::DEFAULT); } -void RegisterAlphaFunction(const std::string & name, AlphaFunction alphaFn) +void RegisterAlphaFunction(const std::string& name, AlphaFunction alphaFn) { - DALI_ASSERT_ALWAYS(sFunctions.insert({ name, alphaFn }).second && - "Function with given key already exists."); + DALI_ASSERT_ALWAYS(sFunctions.insert({name, alphaFn}).second && + "Function with given key already exists."); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/alpha-function-helper.h b/dali-scene-loader/public-api/alpha-function-helper.h index 1a6c9ad..a524b81 100644 --- a/dali-scene-loader/public-api/alpha-function-helper.h +++ b/dali-scene-loader/public-api/alpha-function-helper.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_ALPHA_FUNCTION_HELPER_H_ #define DALI_SCENE_LOADER_ALPHA_FUNCTION_HELPER_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,14 +19,13 @@ #include "dali-scene-loader/public-api/api.h" -#include "dali/public-api/animation/alpha-function.h" #include +#include "dali/public-api/animation/alpha-function.h" namespace Dali { namespace SceneLoader { - /** * @return Given a name, provide a AlphaFunction; if the name was not * recognised, get the default one. @@ -39,7 +38,7 @@ AlphaFunction DALI_SCENE_LOADER_API GetAlphaFunction(const std::string& name, bo */ void DALI_SCENE_LOADER_API RegisterAlphaFunction(const std::string& name, AlphaFunction alphaFn) noexcept(false); -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_ALPHA_FUNCTION_HELPER_H_ diff --git a/dali-scene-loader/public-api/animated-property.cpp b/dali-scene-loader/public-api/animated-property.cpp index 1e8a592..3d1542d 100644 --- a/dali-scene-loader/public-api/animated-property.cpp +++ b/dali-scene-loader/public-api/animated-property.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,19 +20,18 @@ namespace Dali { namespace SceneLoader { - void AnimatedProperty::Animate(Animation& anim, GetActor getActor) { - if (Actor actor = getActor(mNodeName)) + if(Actor actor = getActor(mNodeName)) { Property prop = GetProperty(actor); - if (mKeyFrames) + if(mKeyFrames) { anim.AnimateBetween(prop, mKeyFrames, mAlphaFunction, mTimePeriod); } - else if (mValue) + else if(mValue) { - if (mValue->mIsRelative) + if(mValue->mIsRelative) { anim.AnimateBy(prop, mValue->mValue, mAlphaFunction, mTimePeriod); } @@ -44,5 +43,5 @@ void AnimatedProperty::Animate(Animation& anim, GetActor getActor) } } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/animated-property.h b/dali-scene-loader/public-api/animated-property.h index 026b68a..085b977 100644 --- a/dali-scene-loader/public-api/animated-property.h +++ b/dali-scene-loader/public-api/animated-property.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_ANIMATED_PROPERTY_H #define DALI_SCENE_LOADER_ANIMATED_PROPERTY_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,17 +21,16 @@ #include "dali-scene-loader/public-api/api.h" // EXTERNAL INCLUDES +#include +#include #include "dali/public-api/actors/actor.h" #include "dali/public-api/animation/animation.h" #include "dali/public-api/object/property.h" -#include -#include namespace Dali { namespace SceneLoader { - /** * @brief Intermediate representation for a property that's given to * a Animation to animate. Since there is no getting an @@ -78,20 +77,20 @@ public: // DATA struct Value { Property::Value mValue; - bool mIsRelative; + bool mIsRelative; }; std::string mNodeName; std::string mPropertyName; - KeyFrames mKeyFrames; + KeyFrames mKeyFrames; std::unique_ptr mValue; AlphaFunction mAlphaFunction = AlphaFunction::DEFAULT; - TimePeriod mTimePeriod = TimePeriod(0.f); + TimePeriod mTimePeriod = TimePeriod(0.f); }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_ANIMATED_PROPERTY_H diff --git a/dali-scene-loader/public-api/animation-definition.cpp b/dali-scene-loader/public-api/animation-definition.cpp index ee2b519..850dd00 100644 --- a/dali-scene-loader/public-api/animation-definition.cpp +++ b/dali-scene-loader/public-api/animation-definition.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,9 +20,8 @@ namespace Dali { namespace SceneLoader { - const float AnimationDefinition::DEFAULT_DURATION_SECONDS = 1.f; -const float AnimationDefinition::MIN_DURATION_SECONDS = 1e-2f; +const float AnimationDefinition::MIN_DURATION_SECONDS = 1e-2f; Animation::EndAction AnimationDefinition::StopForModification(Animation& anim) { @@ -43,12 +42,13 @@ AnimationDefinition::AnimationDefinition(AnimationDefinition&& other) mSpeedFactor(other.mSpeedFactor), mPlayRange(other.mPlayRange), mProperties(std::move(other.mProperties)) -{} +{ +} void AnimationDefinition::Animate(Animation& animation, AnimatedProperty::GetActor getActor) { DALI_ASSERT_ALWAYS(animation); - for (auto& ap : mProperties) + for(auto& ap : mProperties) { ap.Animate(animation, getActor); } @@ -72,16 +72,16 @@ Animation AnimationDefinition::ReAnimate(AnimatedProperty::GetActor getActor) AnimationDefinition& AnimationDefinition::operator=(AnimationDefinition&& other) { AnimationDefinition tmp(std::move(other)); - mName = std::move(tmp.mName); - mDuration = tmp.mDuration; - mLoopCount = tmp.mLoopCount; + mName = std::move(tmp.mName); + mDuration = tmp.mDuration; + mLoopCount = tmp.mLoopCount; mDisconnectAction = tmp.mDisconnectAction; - mEndAction = tmp.mEndAction; - mSpeedFactor = tmp.mSpeedFactor; - mPlayRange = tmp.mPlayRange; + mEndAction = tmp.mEndAction; + mSpeedFactor = tmp.mSpeedFactor; + mPlayRange = tmp.mPlayRange; mProperties.swap(tmp.mProperties); return *this; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/animation-definition.h b/dali-scene-loader/public-api/animation-definition.h index 41de471..ea0dcb9 100644 --- a/dali-scene-loader/public-api/animation-definition.h +++ b/dali-scene-loader/public-api/animation-definition.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_ANIMATION_DEFINITION_H #define DALI_SCENE_LOADER_ANIMATION_DEFINITION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,15 +17,14 @@ * */ -#include "dali-scene-loader/public-api/api.h" #include "dali-scene-loader/public-api/animated-property.h" +#include "dali-scene-loader/public-api/api.h" #include "dali/public-api/common/vector-wrapper.h" namespace Dali { namespace SceneLoader { - /** * @brief Animation handle + name + definition of properties. */ @@ -66,23 +65,23 @@ public: // METHODS public: // DATA std::string mName; - float mDuration = DEFAULT_DURATION_SECONDS; - int mLoopCount = 1; + float mDuration = DEFAULT_DURATION_SECONDS; + int mLoopCount = 1; Animation::EndAction mDisconnectAction = Animation::BAKE_FINAL; - Animation::EndAction mEndAction = Animation::BAKE; - float mSpeedFactor = 1.f; - Vector2 mPlayRange = Vector2{ 0.f, 1.f }; + Animation::EndAction mEndAction = Animation::BAKE; + float mSpeedFactor = 1.f; + Vector2 mPlayRange = Vector2{0.f, 1.f}; std::vector mProperties; }; struct AnimationGroupDefinition { - std::string mName; + std::string mName; std::vector mAnimations; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_ANIMATION_DEFINITION_H diff --git a/dali-scene-loader/public-api/api.h b/dali-scene-loader/public-api/api.h index f5ffea0..45f4a1c 100644 --- a/dali-scene-loader/public-api/api.h +++ b/dali-scene-loader/public-api/api.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_API_H #define DALI_SCENE_LOADER_API_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,10 +22,10 @@ #elif defined(WIN32) #ifdef BUILDING_DALI_SCENE_LOADER -#define DALI_SCENE_LOADER_API __declspec(dllexport) +#define DALI_SCENE_LOADER_API __declspec(dllexport) #else -#define DALI_SCENE_LOADER_API __declspec(dllimport) -#endif // BUILDING_DALI_SCENE_LOADER +#define DALI_SCENE_LOADER_API __declspec(dllimport) +#endif // BUILDING_DALI_SCENE_LOADER #endif diff --git a/dali-scene-loader/public-api/blend-shape-details.cpp b/dali-scene-loader/public-api/blend-shape-details.cpp index 3308d37..9e76924 100644 --- a/dali-scene-loader/public-api/blend-shape-details.cpp +++ b/dali-scene-loader/public-api/blend-shape-details.cpp @@ -1,6 +1,6 @@ /* -* Copyright (c) 2020 Samsung Electronics Co., Ltd. +* Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,6 @@ namespace Dali { namespace SceneLoader { - const std::string BlendShapes::NUMBER_OF_BLEND_SHAPES("uNumberOfBlendShapes"); const std::string BlendShapes::UNNORMALIZE_FACTOR("uBlendShapeUnnormalizeFactor"); const std::string BlendShapes::COMPONENT_SIZE("uBlendShapeComponentSize"); @@ -43,27 +42,27 @@ void BlendShapes::ConfigureProperties(const std::pair +#include "dali/public-api/actors/actor.h" +#include "dali/public-api/rendering/shader.h" namespace Dali { namespace SceneLoader { - struct MeshDefinition; struct MeshGeometry; @@ -47,21 +46,21 @@ struct DALI_SCENE_LOADER_API BlendShapes enum { POSITIONS = 0x1, - NORMALS = 0x2, - TANGENTS = 0x4 + NORMALS = 0x2, + TANGENTS = 0x4 }; }; // shader properties - animatable (uniforms) - static const std::string NUMBER_OF_BLEND_SHAPES; ///< Integer number of blend shapes loaded. - static const std::string UNNORMALIZE_FACTOR; ///< Scalar(s) for position components of blend shapes; Version 1.0: float array (1 per blend shape); Version 2.0: single float. - static const std::string COMPONENT_SIZE; ///< Integer offset from one component (positions / normals / tangents) of a blend shape to the next. + static const std::string NUMBER_OF_BLEND_SHAPES; ///< Integer number of blend shapes loaded. + static const std::string UNNORMALIZE_FACTOR; ///< Scalar(s) for position components of blend shapes; Version 1.0: float array (1 per blend shape); Version 2.0: single float. + static const std::string COMPONENT_SIZE; ///< Integer offset from one component (positions / normals / tangents) of a blend shape to the next. // shader properties - read-only (not available as uniforms) - static const std::string COMPONENTS; ///< Integer bitmask of the blend shape components that the shader uses; refer to the Components enum. + static const std::string COMPONENTS; ///< Integer bitmask of the blend shape components that the shader uses; refer to the Components enum. // actor property (instance) - animatable (uniforms) - static const std::string WEIGHTS_UNIFORM; ///< The weight of each blend shape in a float array + static const std::string WEIGHTS_UNIFORM; ///< The weight of each blend shape in a float array /** * @brief Registers properties based on the mesh definition (and geometry) and identified by the above string constants, @@ -72,7 +71,7 @@ struct DALI_SCENE_LOADER_API BlendShapes BlendShapes() = delete; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif // DALI_SCENE_LOADER_BLEND_SHAPE_DETAILS_H diff --git a/dali-scene-loader/public-api/camera-parameters.cpp b/dali-scene-loader/public-api/camera-parameters.cpp index 875c58b..d895255 100644 --- a/dali-scene-loader/public-api/camera-parameters.cpp +++ b/dali-scene-loader/public-api/camera-parameters.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,9 @@ */ #include "dali-scene-loader/public-api/camera-parameters.h" #include "dali-scene-loader/public-api/utils.h" +#include "dali/integration-api/debug.h" #include "dali/public-api/actors/camera-actor.h" #include "dali/public-api/math/quaternion.h" -#include "dali/integration-api/debug.h" namespace Dali { @@ -38,10 +38,10 @@ namespace * @param[in] far The distance to the far depth clipping plane. * @param[in] invertYAxis Whether to invert the 'Y' axis. */ -void Frustum( Matrix& result, float left, float right, float bottom, float top, float nearPlane, float farPlane, bool invertYAxis ) +void Frustum(Matrix& result, float left, float right, float bottom, float top, float nearPlane, float farPlane, bool invertYAxis) { float deltaZ = farPlane - nearPlane; - if ((nearPlane <= 0.0f) || (farPlane <= 0.0f) || Equals(right, left) || Equals(bottom, top) || (deltaZ <= 0.0f)) + if((nearPlane <= 0.0f) || (farPlane <= 0.0f) || Equals(right, left) || Equals(bottom, top) || (deltaZ <= 0.0f)) { DALI_LOG_ERROR("Invalid parameters passed into Frustum!\n"); DALI_ASSERT_DEBUG("Invalid parameters passed into Frustum!"); @@ -54,14 +54,14 @@ void Frustum( Matrix& result, float left, float right, float bottom, float top, result.SetIdentity(); float* m = result.AsFloat(); - m[0] = -2.0f * nearPlane / deltaX; + m[0] = -2.0f * nearPlane / deltaX; m[1] = m[2] = m[3] = 0.0f; m[5] = -2.0f * nearPlane / deltaY; m[4] = m[6] = m[7] = 0.0f; - m[8] = (right + left) / deltaX; - m[9] = (top + bottom) / deltaY; + m[8] = (right + left) / deltaX; + m[9] = (top + bottom) / deltaY; m[10] = (nearPlane + farPlane) / deltaZ; m[11] = 1.0f; @@ -81,12 +81,12 @@ void Frustum( Matrix& result, float left, float right, float bottom, float top, * @param[in] farPlane The distance to the far depth clipping plane. * @param[in] invertYAxis Whether to invert the 'Y' axis. */ -void Perspective( Matrix& result, float fovy, float aspect, float nearPlane, float farPlane, bool invertYAxis ) +void Perspective(Matrix& result, float fovy, float aspect, float nearPlane, float farPlane, bool invertYAxis) { - float frustumH = tanf( fovy * 0.5f ) * nearPlane; + float frustumH = tanf(fovy * 0.5f) * nearPlane; float frustumW = frustumH * aspect; - Frustum( result, -frustumW, frustumW, -frustumH, frustumH, nearPlane, farPlane, invertYAxis ); + Frustum(result, -frustumW, frustumW, -frustumH, frustumH, nearPlane, farPlane, invertYAxis); } /** @@ -103,7 +103,7 @@ void Perspective( Matrix& result, float fovy, float aspect, float nearPlane, flo */ void Orthographic(Matrix& result, float left, float right, float bottom, float top, float nearPlane, float farPlane, bool invertYAxis) { - if (Equals(right, left) || Equals(top, bottom) || Equals(farPlane, nearPlane)) + if(Equals(right, left) || Equals(top, bottom) || Equals(farPlane, nearPlane)) { DALI_LOG_ERROR("Cannot create orthographic projection matrix with a zero dimension.\n"); DALI_ASSERT_DEBUG("Cannot create orthographic projection matrix with a zero dimension."); @@ -114,19 +114,19 @@ void Orthographic(Matrix& result, float left, float right, float bottom, float t float deltaY = invertYAxis ? bottom - top : top - bottom; float deltaZ = farPlane - nearPlane; - float *m = result.AsFloat(); - m[0] = -2.0f / deltaX; - m[1] = 0.0f; - m[2] = 0.0f; - m[3] = 0.0f; + float* m = result.AsFloat(); + m[0] = -2.0f / deltaX; + m[1] = 0.0f; + m[2] = 0.0f; + m[3] = 0.0f; m[4] = 0.0f; m[5] = -2.0f / deltaY; m[6] = 0.0f; m[7] = 0.0f; - m[8] = 0.0f; - m[9] = 0.0f; + m[8] = 0.0f; + m[9] = 0.0f; m[10] = 2.0f / deltaZ; m[11] = 0.0f; m[12] = -(right + left) / deltaX; @@ -135,51 +135,50 @@ void Orthographic(Matrix& result, float left, float right, float bottom, float t m[15] = 1.0f; } -} // nonamespace +} // namespace ViewProjection CameraParameters::GetViewProjection() const { ViewProjection viewProjection; // The projection matrix. - if (isPerspective) + if(isPerspective) { Perspective(viewProjection.GetProjection(), - Radian(Degree(yFov)), - 1.f, - zNear, - zFar, - true); + Radian(Degree(yFov)), + 1.f, + zNear, + zFar, + true); } else { Orthographic(viewProjection.GetProjection(), - orthographicSize.x, - orthographicSize.y, - orthographicSize.z, - orthographicSize.w, - zNear, - zFar, - true); - + orthographicSize.x, + orthographicSize.y, + orthographicSize.z, + orthographicSize.w, + zNear, + zFar, + true); } // The view matrix. const Quaternion viewQuaternion(ANGLE_180, Vector3::YAXIS); - Vector3 translation; - Quaternion cameraOrientation; - Vector3 scale; + Vector3 translation; + Quaternion cameraOrientation; + Vector3 scale; matrix.GetTransformComponents(translation, cameraOrientation, scale); cameraOrientation *= viewQuaternion; viewProjection.GetView().SetInverseTransformComponents(scale, - cameraOrientation, - translation); + cameraOrientation, + translation); viewProjection.Update(); return viewProjection; } -void CameraParameters::CalculateTransformComponents(Vector3 & position, Quaternion & orientation, Vector3 & scale) const +void CameraParameters::CalculateTransformComponents(Vector3& position, Quaternion& orientation, Vector3& scale) const { matrix.GetTransformComponents(position, orientation, scale); @@ -193,7 +192,7 @@ void CameraParameters::ConfigureCamera(CameraActor& camera) const { SetActorCentered(camera); - if (isPerspective) + if(isPerspective) { camera.SetProjectionMode(Camera::PERSPECTIVE_PROJECTION); camera.SetNearClippingPlane(zNear); @@ -204,16 +203,16 @@ void CameraParameters::ConfigureCamera(CameraActor& camera) const { camera.SetProjectionMode(Camera::ORTHOGRAPHIC_PROJECTION); camera.SetOrthographicProjection(orthographicSize.x, - orthographicSize.y, - orthographicSize.z, - orthographicSize.w, - zNear, - zFar); + orthographicSize.y, + orthographicSize.z, + orthographicSize.w, + zNear, + zFar); } // model - Vector3 camTranslation; - Vector3 camScale; + Vector3 camTranslation; + Vector3 camScale; Quaternion camOrientation; CalculateTransformComponents(camTranslation, camOrientation, camScale); @@ -223,5 +222,5 @@ void CameraParameters::ConfigureCamera(CameraActor& camera) const camera.SetProperty(Actor::Property::SCALE, camScale); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/camera-parameters.h b/dali-scene-loader/public-api/camera-parameters.h index 044c7f4..06370fc 100644 --- a/dali-scene-loader/public-api/camera-parameters.h +++ b/dali-scene-loader/public-api/camera-parameters.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_CAMERA_PARAMETERS_H #define DALI_SCENE_LOADER_CAMERA_PARAMETERS_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * */ - // INTERNAL INCLUDES +// INTERNAL INCLUDES #include "dali-scene-loader/public-api/api.h" #include "dali-scene-loader/public-api/view-projection.h" @@ -27,20 +27,18 @@ namespace Dali { - class CameraActor; namespace SceneLoader { - struct DALI_SCENE_LOADER_API CameraParameters { - Matrix matrix = Matrix::IDENTITY; - Vector4 orthographicSize = Vector4{ -1.f, 1.f, 1.f, -1.f }; - float yFov = 60.f; - float zNear = 0.1f; - float zFar = 1000.f; - bool isPerspective = true; + Matrix matrix = Matrix::IDENTITY; + Vector4 orthographicSize = Vector4{-1.f, 1.f, 1.f, -1.f}; + float yFov = 60.f; + float zNear = 0.1f; + float zFar = 1000.f; + bool isPerspective = true; /** * @return The view-projection matrix of the camera. @@ -61,7 +59,7 @@ struct DALI_SCENE_LOADER_API CameraParameters void ConfigureCamera(CameraActor& camera) const; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif // DALI_SCENE_LOADER_CAMERA_PARAMETERS_H diff --git a/dali-scene-loader/public-api/customization.cpp b/dali-scene-loader/public-api/customization.cpp index 546d938..ebf59c0 100644 --- a/dali-scene-loader/public-api/customization.cpp +++ b/dali-scene-loader/public-api/customization.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,14 +21,15 @@ namespace Dali { namespace SceneLoader { - -struct Customization::Map::Impl { +struct Customization::Map::Impl +{ std::map mCustomizations; }; Customization::Map::Map() -: mImpl{ new Impl } -{} +: mImpl{new Impl} +{ +} Customization::Map::~Map() = default; @@ -41,8 +42,8 @@ Customization* Customization::Map::Set(Tag tag, Customization&& customization) const Customization* Customization::Map::Get(Tag tag) const { auto& customizations = mImpl->mCustomizations; - auto iFind = customizations.find(tag); - if (iFind != customizations.end()) + auto iFind = customizations.find(tag); + if(iFind != customizations.end()) { return &iFind->second; } @@ -52,8 +53,8 @@ const Customization* Customization::Map::Get(Tag tag) const Customization* Customization::Map::Get(Tag tag) { auto& customizations = mImpl->mCustomizations; - auto iFind = customizations.find(tag); - if (iFind != customizations.end()) + auto iFind = customizations.find(tag); + if(iFind != customizations.end()) { return &iFind->second; } @@ -76,8 +77,9 @@ struct Customization::Choices::Impl }; Customization::Choices::Choices() -: mImpl{ new Impl } -{} +: mImpl{new Impl} +{ +} Customization::Choices::~Choices() = default; @@ -89,8 +91,8 @@ void Customization::Choices::Set(Tag tag, OptionType option) Customization::OptionType Customization::Choices::Get(Tag tag) const { auto& options = mImpl->mOptions; - auto iFind = options.find(tag); - if (iFind != options.end()) + auto iFind = options.find(tag); + if(iFind != options.end()) { return iFind->second; } @@ -107,5 +109,5 @@ void Customization::Choices::Clear() mImpl->mOptions.clear(); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/customization.h b/dali-scene-loader/public-api/customization.h index ff29b95..cdac2fc 100644 --- a/dali-scene-loader/public-api/customization.h +++ b/dali-scene-loader/public-api/customization.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_CUSTOMIZATION_STATE_H_ #define DALI_SCENE_LOADER_CUSTOMIZATION_STATE_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,19 +17,18 @@ * */ - // INTERNAL INCLUDES +// INTERNAL INCLUDES #include "dali-scene-loader/public-api/api.h" // EXTERNAL INCLUDES -#include "dali/public-api/common/vector-wrapper.h" -#include #include +#include +#include "dali/public-api/common/vector-wrapper.h" namespace Dali { namespace SceneLoader { - /** * @brief Offers a description of an aspect of the scene that can be customized: * the number of options, and the name of the nodes that are registered @@ -37,7 +36,7 @@ namespace SceneLoader */ struct DALI_SCENE_LOADER_API Customization { - using Tag = std::string; + using Tag = std::string; using OptionType = uint32_t; /** @@ -114,11 +113,11 @@ struct DALI_SCENE_LOADER_API Customization static const OptionType NONE = OptionType(-1); - OptionType numOptions = 0; - std::vector nodes; // to apply option to. + OptionType numOptions = 0; + std::vector nodes; // to apply option to. }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_CUSTOMIZATION_STATE_H_ diff --git a/dali-scene-loader/public-api/dli-loader.cpp b/dali-scene-loader/public-api/dli-loader.cpp index 11dc036..18214dd 100644 --- a/dali-scene-loader/public-api/dli-loader.cpp +++ b/dali-scene-loader/public-api/dli-loader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,29 +19,29 @@ #include "dali-scene-loader/public-api/dli-loader.h" // EXTERNAL INCLUDES -#include "dali/public-api/object/property-array.h" -#include "dali/devel-api/common/map-wrapper.h" -#include "dali-toolkit/devel-api/builder/json-parser.h" -#include "dali/integration-api/debug.h" +#include +#include #include #include -#include #include -#include +#include "dali-toolkit/devel-api/builder/json-parser.h" +#include "dali/devel-api/common/map-wrapper.h" +#include "dali/integration-api/debug.h" +#include "dali/public-api/object/property-array.h" // INTERNAL INCLUDES -#include "dali-scene-loader/public-api/parse-renderer-state.h" -#include "dali-scene-loader/public-api/skinning-details.h" -#include "dali-scene-loader/public-api/load-result.h" -#include "dali-scene-loader/public-api/scene-definition.h" -#include "dali-scene-loader/public-api/animation-definition.h" +#include "dali-scene-loader/internal/json-util.h" #include "dali-scene-loader/public-api/alpha-function-helper.h" -#include "dali-scene-loader/public-api/camera-parameters.h" -#include "dali-scene-loader/public-api/light-parameters.h" +#include "dali-scene-loader/public-api/animation-definition.h" #include "dali-scene-loader/public-api/blend-shape-details.h" +#include "dali-scene-loader/public-api/camera-parameters.h" #include "dali-scene-loader/public-api/ktx-loader.h" +#include "dali-scene-loader/public-api/light-parameters.h" +#include "dali-scene-loader/public-api/load-result.h" +#include "dali-scene-loader/public-api/parse-renderer-state.h" +#include "dali-scene-loader/public-api/scene-definition.h" +#include "dali-scene-loader/public-api/skinning-details.h" #include "dali-scene-loader/public-api/utils.h" -#include "dali-scene-loader/internal/json-util.h" #define DLI_0_1_COMPATIBILITY @@ -51,18 +51,17 @@ using namespace Toolkit; namespace SceneLoader { - namespace rs = RendererState; namespace { -const std::string NODES = "nodes"; -const std::string SCENES = "scenes"; -const std::string NODE = "node"; -const std::string URI = "uri"; -const std::string URL = "url"; +const std::string NODES = "nodes"; +const std::string SCENES = "scenes"; +const std::string NODE = "node"; +const std::string URI = "uri"; +const std::string URL = "url"; const std::string CUSTOMIZATION = "customization"; -const std::string HINTS = "hints"; +const std::string HINTS = "hints"; const std::string NAME("name"); const std::string BLEND_SHAPE_HEADER("blendShapeHeader"); const std::string BLEND_SHAPES("blendShapes"); @@ -70,29 +69,29 @@ const std::string BLEND_SHAPE_VERSION_1_0("1.0"); const std::string BLEND_SHAPE_VERSION_2_0("2.0"); const std::string VERSION("version"); -const char* const SHADOW_MAP_SIZE = "shadowMapSize"; +const char* const SHADOW_MAP_SIZE = "shadowMapSize"; const char* const ORTHOGRAPHIC_SIZE = "orthographicSize"; -const char* const PIXEL_UNITS = "px"; +const char* const PIXEL_UNITS = "px"; const char SLASH = '/'; void ReadModelTransform(const TreeNode* node, Quaternion& orientation, Vector3& translation, Vector3& scale) { - float num[16u] = { .0f }; + float num[16u] = {.0f}; - if (ReadVector(node->GetChild("matrix"), num, 16u)) + if(ReadVector(node->GetChild("matrix"), num, 16u)) { Matrix mat(num); mat.GetTransformComponents(translation, orientation, scale); } else { - if (ReadVector(node->GetChild("angle"), num, 3u)) + if(ReadVector(node->GetChild("angle"), num, 3u)) { orientation = Quaternion(Radian(Degree(num[0u])), Radian(Degree(num[1u])), Radian(Degree(num[2u]))); } - if (ReadVector(node->GetChild("position"), num, 3u)) + if(ReadVector(node->GetChild("position"), num, 3u)) { translation = Vector3(num); } @@ -109,10 +108,9 @@ bool ReadAttribAccessor(const TreeNode* node, MeshDefinition::Accessor& accessor return ReadBlob(node, accessor.mBlob.mOffset, accessor.mBlob.mLength); } -bool ReadColorCode(const TreeNode* node, Vector4& color, - DliLoader::ConvertColorCode convertColorCode) +bool ReadColorCode(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode) { - if (!node || !convertColorCode) + if(!node || !convertColorCode) { return false; } @@ -122,20 +120,19 @@ bool ReadColorCode(const TreeNode* node, Vector4& color, return true; } -bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, - DliLoader::ConvertColorCode convertColorCode) +bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode) { return ReadColorCode(node->GetChild("colorCode"), color, convertColorCode) || - ReadColor(node->GetChild("color"), color); + ReadColor(node->GetChild("color"), color); } RendererState::Type ReadRendererState(const TreeNode& tnRendererState) { - if (tnRendererState.GetType() == TreeNode::INTEGER) + if(tnRendererState.GetType() == TreeNode::INTEGER) { return static_cast(tnRendererState.GetInteger()); } - else if (tnRendererState.GetType() == TreeNode::STRING) + else if(tnRendererState.GetType() == TreeNode::STRING) { return RendererState::Parse(tnRendererState.GetString()); } @@ -159,12 +156,12 @@ void ReadArcField(const TreeNode* eArc, ArcNode& arc) ReadFloat(eArc->GetChild("endAngle"), arc.mEndAngleDegrees); } -const TreeNode *GetNthChild(const TreeNode *node, uint32_t index) +const TreeNode* GetNthChild(const TreeNode* node, uint32_t index) { uint32_t i = 0; - for (TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i) + for(TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i) { - if (i == index) + if(i == index) { return &((*it).second); } @@ -175,11 +172,11 @@ const TreeNode *GetNthChild(const TreeNode *node, uint32_t index) const TreeNode* RequireChild(const TreeNode* node, const std::string& childName) { auto child = node->GetChild(childName); - if (!child) + if(!child) { ExceptionFlinger flinger(ASSERT_LOCATION); flinger << "Failed to find child node '" << childName << "'"; - if (auto nodeName = node->GetName()) + if(auto nodeName = node->GetName()) { flinger << " on '" << nodeName << "'"; } @@ -193,43 +190,55 @@ void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array); void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map) { DALI_ASSERT_DEBUG(node.GetType() == TreeNode::OBJECT); - for (auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0) + for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0) { auto kv = *i0; - switch (kv.second.GetType()) - { - case TreeNode::ARRAY: + switch(kv.second.GetType()) { - Property::Array array; - ParseProperties(kv.second, array); - map.Insert(kv.first, array); - } break; + case TreeNode::ARRAY: + { + Property::Array array; + ParseProperties(kv.second, array); + map.Insert(kv.first, array); + break; + } - case TreeNode::OBJECT: - { - Property::Map innerMap; - ParseProperties(kv.second, innerMap); - map.Insert(kv.first, innerMap); - } break; + case TreeNode::OBJECT: + { + Property::Map innerMap; + ParseProperties(kv.second, innerMap); + map.Insert(kv.first, innerMap); + break; + } - case TreeNode::STRING: - map.Insert(kv.first, kv.second.GetString()); - break; + case TreeNode::STRING: + { + map.Insert(kv.first, kv.second.GetString()); + break; + } - case TreeNode::INTEGER: - map.Insert(kv.first, kv.second.GetInteger()); - break; + case TreeNode::INTEGER: + { + map.Insert(kv.first, kv.second.GetInteger()); + break; + } - case TreeNode::BOOLEAN: - map.Insert(kv.first, kv.second.GetBoolean()); - break; + case TreeNode::BOOLEAN: + { + map.Insert(kv.first, kv.second.GetBoolean()); + break; + } - case TreeNode::FLOAT: - map.Insert(kv.first, kv.second.GetFloat()); - break; + case TreeNode::FLOAT: + { + map.Insert(kv.first, kv.second.GetFloat()); + break; + } - case TreeNode::IS_NULL: - break; + case TreeNode::IS_NULL: + { + break; + } } } } @@ -237,58 +246,70 @@ void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map) void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array) { DALI_ASSERT_DEBUG(node.GetType() == TreeNode::ARRAY); - for (auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0) + for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0) { auto kv = *i0; - switch (kv.second.GetType()) - { - case TreeNode::ARRAY: + switch(kv.second.GetType()) { - Property::Array innerArray; - ParseProperties(kv.second, innerArray); - array.PushBack(innerArray); - } break; + case TreeNode::ARRAY: + { + Property::Array innerArray; + ParseProperties(kv.second, innerArray); + array.PushBack(innerArray); + break; + } - case TreeNode::OBJECT: - { - Property::Map map; - ParseProperties(kv.second, map); - array.PushBack(map); - } break; + case TreeNode::OBJECT: + { + Property::Map map; + ParseProperties(kv.second, map); + array.PushBack(map); + break; + } - case TreeNode::STRING: - array.PushBack(kv.second.GetString()); - break; + case TreeNode::STRING: + { + array.PushBack(kv.second.GetString()); + break; + } - case TreeNode::INTEGER: - array.PushBack(kv.second.GetInteger()); - break; + case TreeNode::INTEGER: + { + array.PushBack(kv.second.GetInteger()); + break; + } - case TreeNode::BOOLEAN: - array.PushBack(kv.second.GetBoolean()); - break; + case TreeNode::BOOLEAN: + { + array.PushBack(kv.second.GetBoolean()); + break; + } - case TreeNode::FLOAT: - array.PushBack(kv.second.GetFloat()); - break; + case TreeNode::FLOAT: + { + array.PushBack(kv.second.GetFloat()); + break; + } - case TreeNode::IS_NULL: - break; + case TreeNode::IS_NULL: + { + break; + } } } } -}//namespace +} //namespace struct DliLoader::Impl { - StringCallback mOnError = DefaultErrorCallback; + StringCallback mOnError = DefaultErrorCallback; Toolkit::JsonParser mParser; void ParseScene(LoadParams& params); private: - std::map mInverseBindMatrices; + std::map mInverseBindMatrices; /** * @brief Due to .dli nodes being processed in depth-first traversal with orphans being @@ -306,29 +327,26 @@ private: * index. * @return Whether the operation was successful. */ - virtual bool Map(Index iDli, Index iScene) =0; + virtual bool Map(Index iDli, Index iScene) = 0; /** * @return The scene index for the node's @a dli index. */ - virtual Index Resolve(Index iDli) =0; + virtual Index Resolve(Index iDli) = 0; }; /** * @brief Traverses the DOM tree created by LoadDocument() in an attempt to create * an intermediate representation of resources and nodes. */ - void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, - const Toolkit::TreeNode* tnNodes, LoadParams& params); + void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params); void ParseSkeletons(const Toolkit::TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources); void ParseEnvironments(const Toolkit::TreeNode* environments, ResourceBundle& resources); - void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode, - ResourceBundle& resources); + void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources); void ParseNodes(const Toolkit::TreeNode* nodes, Index index, LoadParams& params); - void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index, - std::vector& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper); + void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index, std::vector& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper); void ParseAnimations(const Toolkit::TreeNode* animations, LoadParams& params); void ParseAnimationGroups(const Toolkit::TreeNode* animationGroups, LoadParams& params); @@ -341,8 +359,9 @@ private: }; DliLoader::DliLoader() -: mImpl{ new Impl } -{} +: mImpl{new Impl} +{ +} DliLoader::~DliLoader() = default; @@ -356,8 +375,8 @@ bool DliLoader::LoadScene(const std::string& uri, LoadParams& params) std::string daliBuffer = LoadTextFile(uri.c_str()); auto& parser = mImpl->mParser; - parser = JsonParser::New(); - if (!parser.Parse(daliBuffer)) + parser = JsonParser::New(); + if(!parser.Parse(daliBuffer)) { return false; } @@ -371,7 +390,7 @@ std::string DliLoader::GetParseError() const std::stringstream stream; auto& parser = mImpl->mParser; - if (parser.ParseError()) + if(parser.ParseError()) { stream << "position: " << parser.GetErrorPosition() << ", line: " << parser.GetErrorLineNumber() << ", column: " << parser.GetErrorColumn() << ", description: " << parser.GetErrorDescription() << "."; } @@ -381,36 +400,36 @@ std::string DliLoader::GetParseError() const void DliLoader::Impl::ParseScene(LoadParams& params) { - auto& input = params.input; + auto& input = params.input; auto& output = params.output; // get index of root node. auto docRoot = mParser.GetRoot(); // Process resources first - these are shared - if (auto environments = docRoot->GetChild("environment")) + if(auto environments = docRoot->GetChild("environment")) { - ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials + ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials } - if (auto meshes = docRoot->GetChild("meshes")) + if(auto meshes = docRoot->GetChild("meshes")) { ParseMeshes(meshes, output.mResources); } - if (auto shaders = docRoot->GetChild("shaders")) + if(auto shaders = docRoot->GetChild("shaders")) { ParseShaders(shaders, output.mResources); } - if (auto materials = docRoot->GetChild("materials")) + if(auto materials = docRoot->GetChild("materials")) { ParseMaterials(materials, input.mConvertColorCode, output.mResources); } - for (auto& c : input.mPreNodeCategoryProcessors) + for(auto& c : input.mPreNodeCategoryProcessors) { - if (auto node = docRoot->GetChild(c.first)) + if(auto node = docRoot->GetChild(c.first)) { Property::Array array; ParseProperties(*node, array); @@ -419,11 +438,11 @@ void DliLoader::Impl::ParseScene(LoadParams& params) } // Process scenes - Index iScene = 0; // default scene + Index iScene = 0; // default scene ReadIndex(docRoot->GetChild("scene"), iScene); auto tnScenes = RequireChild(docRoot, "scenes"); - auto tnNodes = RequireChild(docRoot, "nodes"); + auto tnNodes = RequireChild(docRoot, "nodes"); ParseSceneInternal(iScene, tnScenes, tnNodes, params); ParseSkeletons(docRoot->GetChild("skeletons"), output.mScene, output.mResources); @@ -436,9 +455,9 @@ void DliLoader::Impl::ParseScene(LoadParams& params) GetLightParameters(output.mLightParameters); // Post-node processors and animations last - for (auto& c : input.mPostNodeCategoryProcessors) + for(auto& c : input.mPostNodeCategoryProcessors) { - if (auto node = docRoot->GetChild(c.first)) + if(auto node = docRoot->GetChild(c.first)) { Property::Array array; ParseProperties(*node, array); @@ -446,58 +465,54 @@ void DliLoader::Impl::ParseScene(LoadParams& params) } } - if (auto animations = docRoot->GetChild("animations")) + if(auto animations = docRoot->GetChild("animations")) { ParseAnimations(animations, params); } - if (!output.mAnimationDefinitions.empty()) + if(!output.mAnimationDefinitions.empty()) { - if (auto animationGroups = docRoot->GetChild("animationGroups")) + if(auto animationGroups = docRoot->GetChild("animationGroups")) { ParseAnimationGroups(animationGroups, params); } } } -void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, - const Toolkit::TreeNode* tnNodes, LoadParams& params) +void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params) { auto getSceneRootIdx = [tnScenes, tnNodes](Index iScene) { - auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object - if (!tn) + auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object + if(!tn) { ExceptionFlinger(ASSERT_LOCATION) << iScene << " is out of bounds access into " << SCENES << "."; } - tn = RequireChild(tn, NODES); // now a "nodes" array - if (tn->GetType() != TreeNode::ARRAY) + tn = RequireChild(tn, NODES); // now a "nodes" array + if(tn->GetType() != TreeNode::ARRAY) { - ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << - " has an invalid type; array required."; + ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid type; array required."; } - if (tn->Size() < 1) + if(tn->Size() < 1) { - ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << - " must define a node id."; + ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " must define a node id."; } - tn = GetNthChild(tn, 0); // now the first element of the array + tn = GetNthChild(tn, 0); // now the first element of the array Index iRootNode; - if (!ReadIndex(tn, iRootNode)) + if(!ReadIndex(tn, iRootNode)) { - ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << - " has an invalid value for root node index: '" << iRootNode << "'."; + ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid value for root node index: '" << iRootNode << "'."; } - if (iRootNode >= tnNodes->Size()) + if(iRootNode >= tnNodes->Size()) { ExceptionFlinger(ASSERT_LOCATION) << "Root node index << " << iRootNode << " of scene " << iScene << " is out of bounds."; } - tn = GetNthChild(tnNodes, iRootNode); // now a "node" object - if (tn->GetType() != TreeNode::OBJECT) + tn = GetNthChild(tnNodes, iRootNode); // now a "node" object + if(tn->GetType() != TreeNode::OBJECT) { ExceptionFlinger(ASSERT_LOCATION) << "Root node of scene " << iScene << " is of invalid JSON type; object required"; } @@ -511,19 +526,19 @@ void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* auto& scene = params.output.mScene; scene.AddRootNode(0); - for (Index i = 0; i < iScene; ++i) + for(Index i = 0; i < iScene; ++i) { - Index iRootNode = getSceneRootIdx(i); - const Index iRoot = scene.GetNodeCount(); + Index iRootNode = getSceneRootIdx(i); + const Index iRoot = scene.GetNodeCount(); ParseNodes(tnNodes, iRootNode, params); scene.AddRootNode(iRoot); } auto numScenes = tnScenes->Size(); - for (Index i = iScene + 1; i < numScenes; ++i) + for(Index i = iScene + 1; i < numScenes; ++i) { - Index iRootNode = getSceneRootIdx(i); - const Index iRoot = scene.GetNodeCount(); + Index iRootNode = getSceneRootIdx(i); + const Index iRoot = scene.GetNodeCount(); ParseNodes(tnNodes, iRootNode, params); scene.AddRootNode(iRoot); } @@ -531,36 +546,36 @@ void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources) { - if (skeletons) + if(skeletons) { auto iStart = skeletons->CBegin(); - for (auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0) + for(auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0) { - auto& node = (*i0).second; + auto& node = (*i0).second; std::string skeletonRootName; - if (ReadString(node.GetChild(NODE), skeletonRootName)) + if(ReadString(node.GetChild(NODE), skeletonRootName)) { SkeletonDefinition skeleton; - if (!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx)) + if(!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx)) { ExceptionFlinger(ASSERT_LOCATION) << FormatString("Skeleton %d: node '%s' not defined.", resources.mSkeletons.size(), skeletonRootName.c_str()); } - uint32_t jointCount = 0; + uint32_t jointCount = 0; std::function visitFn; - auto& ibms = mInverseBindMatrices; - visitFn = [&](Index id) { + auto& ibms = mInverseBindMatrices; + visitFn = [&](Index id) { auto node = scene.GetNode(id); jointCount += ibms.find(id) != ibms.end(); - for (auto i : node->mChildren) + for(auto i : node->mChildren) { visitFn(i); } }; visitFn(skeleton.mRootNodeIdx); - if (jointCount > Skinning::MAX_JOINTS) + if(jointCount > Skinning::MAX_JOINTS) { mOnError(FormatString("Skeleton %d: joint count exceeds supported limit.", resources.mSkeletons.size())); jointCount = Skinning::MAX_JOINTS; @@ -570,13 +585,13 @@ void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& visitFn = [&](Index id) { auto iFind = ibms.find(id); - if (iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS) + if(iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS) { - skeleton.mJoints.push_back({ id, iFind->second }); + skeleton.mJoints.push_back({id, iFind->second}); } auto node = scene.GetNode(id); - for (auto i : node->mChildren) + for(auto i : node->mChildren) { visitFn(i); } @@ -587,8 +602,7 @@ void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& } else { - ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << - ": Missing required attribute '"<< NODE <<"'."; + ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << ": Missing required attribute '" << NODE << "'."; } } } @@ -598,7 +612,7 @@ void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBu { Matrix cubeOrientation(Matrix::IDENTITY); - for (auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0) + for(auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0) { auto& node = (*i0).second; @@ -609,7 +623,7 @@ void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBu ToUnixFileSeparators(envDef.mDiffuseMapPath); envDef.mIblIntensity = 1.0f; ReadFloat(node.GetChild("iblIntensity"), envDef.mIblIntensity); - if (ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u)) + if(ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u)) { envDef.mCubeOrientation = Quaternion(cubeOrientation); } @@ -618,7 +632,7 @@ void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBu } // NOTE: guarantees environmentMaps to have an empty environment. - if (resources.mEnvironmentMaps.empty()) + if(resources.mEnvironmentMaps.empty()) { resources.mEnvironmentMaps.emplace_back(EnvironmentDefinition(), EnvironmentDefinition::Textures()); } @@ -627,9 +641,9 @@ void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBu void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& resources) { uint32_t iShader = 0; - for (auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader) + for(auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader) { - auto& node = (*i0).second; + auto& node = (*i0).second; ShaderDefinition shaderDef; ReadStringVector(node.GetChild("defines"), shaderDef.mDefines); @@ -638,94 +652,96 @@ void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& reso // "OUTPUT_IS_TRANSPARENT" Might generate transparent alpha from opaque inputs. // "MODIFIES_GEOMETRY" Might change position of vertices, this option disables any culling optimizations. - ReadStringVector(node.GetChild( HINTS ), shaderDef.mHints); + ReadStringVector(node.GetChild(HINTS), shaderDef.mHints); - if (ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) && - ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath)) + if(ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) && + ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath)) { ToUnixFileSeparators(shaderDef.mVertexShaderPath); ToUnixFileSeparators(shaderDef.mFragmentShaderPath); - for (TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0) + for(TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0) { const TreeNode::KeyNodePair& keyValue = *j0; - const std::string& key = keyValue.first; - const TreeNode& value = keyValue.second; + const std::string& key = keyValue.first; + const TreeNode& value = keyValue.second; Property::Value uniformValue; - if (key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0) + if(key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0) { continue; } - else if (key.compare("rendererState") == 0) + else if(key.compare("rendererState") == 0) { shaderDef.mRendererState = ReadRendererState(keyValue.second); } - else if (value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT) + else if(value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT) { float f = 0.f; ReadFloat(&value, f); uniformValue = f; } - else if (value.GetType() == TreeNode::BOOLEAN) + else if(value.GetType() == TreeNode::BOOLEAN) { DALI_LOG_WARNING("\"bool\" uniforms are handled as floats in shader"); bool value = false; - if (ReadBool(&keyValue.second, value)) + if(ReadBool(&keyValue.second, value)) { uniformValue = value ? 1.0f : 0.0f; } } - else switch (auto size = GetNumericalArraySize(&value)) - { - case 16: - { - Matrix m; - ReadVector(&value, m.AsFloat(), size); - uniformValue = m; - break; - } + else + switch(auto size = GetNumericalArraySize(&value)) + { + case 16: + { + Matrix m; + ReadVector(&value, m.AsFloat(), size); + uniformValue = m; + break; + } - case 9: - { - Matrix3 m; - ReadVector(&value, m.AsFloat(), size); - uniformValue = m; - break; - } + case 9: + { + Matrix3 m; + ReadVector(&value, m.AsFloat(), size); + uniformValue = m; + break; + } - case 4: - { - Vector4 v; - ReadVector(&value, v.AsFloat(), size); - uniformValue = v; - break; - } + case 4: + { + Vector4 v; + ReadVector(&value, v.AsFloat(), size); + uniformValue = v; + break; + } - case 3: - { - Vector3 v; - ReadVector(&value, v.AsFloat(), size); - uniformValue = v; - break; - } + case 3: + { + Vector3 v; + ReadVector(&value, v.AsFloat(), size); + uniformValue = v; + break; + } - case 2: - { - Vector2 v; - ReadVector(&value, v.AsFloat(), size); - uniformValue = v; - break; - } + case 2: + { + Vector2 v; + ReadVector(&value, v.AsFloat(), size); + uniformValue = v; + break; + } - default: - mOnError(FormatString( - "shader %d: Ignoring uniform '%s': failed to infer type from %d elements.", - iShader, key.c_str())); - break; - } + default: + mOnError(FormatString( + "shader %d: Ignoring uniform '%s': failed to infer type from %d elements.", + iShader, + key.c_str())); + break; + } - if (Property::NONE != uniformValue.GetType()) + if(Property::NONE != uniformValue.GetType()) { shaderDef.mUniforms.Insert(key, uniformValue); } @@ -735,116 +751,114 @@ void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& reso } else { - ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << - ": Missing vertex / fragment shader definition."; + ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << ": Missing vertex / fragment shader definition."; } } } void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resources) { - for (auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0) + for(auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0) { auto& node = (*i0).second; - MeshDefinition meshDef; - if (!ReadString(node.GetChild(URI), meshDef.mUri)) + MeshDefinition meshDef; + if(!ReadString(node.GetChild(URI), meshDef.mUri)) { - ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << - ": Missing required attribute '" << URI << "'."; + ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << ": Missing required attribute '" << URI << "'."; } ToUnixFileSeparators(meshDef.mUri); std::string primitive; - if (ReadString(node.GetChild("primitive"), primitive)) + if(ReadString(node.GetChild("primitive"), primitive)) { - if (primitive == "LINES") + if(primitive == "LINES") { meshDef.mPrimitiveType = Geometry::LINES; } - else if (primitive == "POINTS") + else if(primitive == "POINTS") { meshDef.mPrimitiveType = Geometry::POINTS; } - else if (primitive != "TRIANGLES") + else if(primitive != "TRIANGLES") { mOnError(FormatString( "mesh %d: Using TRIANGLES instead of unsupported primitive type '%s'.", - resources.mMeshes.size(), primitive.c_str())); + resources.mMeshes.size(), + primitive.c_str())); } } int attributes; - if (ReadInt(node.GetChild("attributes"), attributes)) + if(ReadInt(node.GetChild("attributes"), attributes)) { - if (MaskMatch(attributes, MeshDefinition::INDICES) && - !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices)) + if(MaskMatch(attributes, MeshDefinition::INDICES) && + !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices)) { ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.", - resources.mMeshes.size(), "indices"); + resources.mMeshes.size(), + "indices"); } - if (MaskMatch(attributes, MeshDefinition::POSITIONS) && - !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions)) + if(MaskMatch(attributes, MeshDefinition::POSITIONS) && + !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions)) { ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.", - resources.mMeshes.size(), "positions"); + resources.mMeshes.size(), + "positions"); } - if (MaskMatch(attributes, MeshDefinition::NORMALS) && - !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals)) + if(MaskMatch(attributes, MeshDefinition::NORMALS) && + !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals)) { - mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), - "normals")); + mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "normals")); } - if (MaskMatch(attributes, MeshDefinition::TEX_COORDS) && - !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords)) + if(MaskMatch(attributes, MeshDefinition::TEX_COORDS) && + !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords)) { - mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), - "textures")); + mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "textures")); } - if (MaskMatch(attributes, MeshDefinition::TANGENTS) && - !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents)) + if(MaskMatch(attributes, MeshDefinition::TANGENTS) && + !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents)) { - mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), - "tangents")); + mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "tangents")); } // NOTE: we're no longer reading bitangents as these are calculated in the shaders. - if (ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx)) + if(ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx)) { - if (!MaskMatch(attributes, MeshDefinition::JOINTS_0) && - !MaskMatch(attributes, MeshDefinition::WEIGHTS_0)) + if(!MaskMatch(attributes, MeshDefinition::JOINTS_0) && + !MaskMatch(attributes, MeshDefinition::WEIGHTS_0)) { mOnError(FormatString("mesh %d: Expected joints0 / weights0 attribute(s) missing.", - resources.mMeshes.size())); + resources.mMeshes.size())); } - else if (!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) || - !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0)) + else if(!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) || + !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0)) { mOnError(FormatString("mesh %d: Failed to read skinning information.", - resources.mMeshes.size())); + resources.mMeshes.size())); } } - if (auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER)) + if(auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER)) { std::string blendShapeVersion; ReadString(blendshapeHeader->GetChild(VERSION), blendShapeVersion); - if (0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0)) + if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0)) { meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_1_0; } - else if (0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0)) + else if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0)) { meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0; } - switch (meshDef.mBlendShapeVersion) + switch(meshDef.mBlendShapeVersion) { case BlendShapes::Version::VERSION_1_0: case BlendShapes::Version::VERSION_2_0: // FALL THROUGH @@ -860,12 +874,12 @@ void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resour } } - if (auto blendShapes = node.GetChild(BLEND_SHAPES) ) + if(auto blendShapes = node.GetChild(BLEND_SHAPES)) { meshDef.mBlendShapes.resize(blendShapes->Size()); auto index = 0u; - for (auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index) + for(auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index) { // Each blend shape is stored as the difference with the original mesh. @@ -873,15 +887,15 @@ void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resour auto& blendShape = meshDef.mBlendShapes[index]; ReadString(blendShapeNode.GetChild("name"), blendShape.name); - if (auto position = blendShapeNode.GetChild("positions")) + if(auto position = blendShapeNode.GetChild("positions")) { ReadAttribAccessor(position, blendShape.deltas); } - if (auto normals = blendShapeNode.GetChild("normals")) + if(auto normals = blendShapeNode.GetChild("normals")) { ReadAttribAccessor(normals, blendShape.normals); } - if (auto tangents = blendShapeNode.GetChild("tangents")) + if(auto tangents = blendShapeNode.GetChild("tangents")) { ReadAttribAccessor(tangents, blendShape.tangents); } @@ -890,7 +904,7 @@ void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resour } bool flipV; - if (ReadBool(node.GetChild("flipV"), flipV)) + if(ReadBool(node.GetChild("flipV"), flipV)) { meshDef.mFlags |= flipV * MeshDefinition::FLIP_UVS_VERTICAL; } @@ -900,111 +914,108 @@ void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resour } } -void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode, - ResourceBundle& resources) +void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources) { - for (auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0) + for(auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0) { auto& node = (*i0).second; MaterialDefinition materialDef; - if (auto eEnvironment = node.GetChild("environment")) + if(auto eEnvironment = node.GetChild("environment")) { ReadIndex(eEnvironment, materialDef.mEnvironmentIdx); - if (static_cast(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size()) + if(static_cast(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size()) { - ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << - ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << - resources.mEnvironmentMaps.size() << ")."; + ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << resources.mEnvironmentMaps.size() << ")."; } } //TODO : need to consider AGIF std::vector texturePaths; - std::string texturePath; - if (ReadString(node.GetChild("albedoMap"), texturePath)) + std::string texturePath; + if(ReadString(node.GetChild("albedoMap"), texturePath)) { ToUnixFileSeparators(texturePath); const auto semantic = MaterialDefinition::ALBEDO; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); - materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY. + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); + materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY. } - if (ReadString(node.GetChild("albedoMetallicMap"), texturePath)) + if(ReadString(node.GetChild("albedoMetallicMap"), texturePath)) { ToUnixFileSeparators(texturePath); - if (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO)) { mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "albedo")); } const auto semantic = MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); materialDef.mFlags |= semantic; } - if (ReadString(node.GetChild("metallicRoughnessMap"), texturePath)) + if(ReadString(node.GetChild("metallicRoughnessMap"), texturePath)) { ToUnixFileSeparators(texturePath); - if (MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC)) { mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "metallic")); } const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); materialDef.mFlags |= semantic | - // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow. - (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY); + // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow. + (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY); } - if (ReadString(node.GetChild("normalMap"), texturePath)) + if(ReadString(node.GetChild("normalMap"), texturePath)) { ToUnixFileSeparators(texturePath); const auto semantic = MaterialDefinition::NORMAL; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); materialDef.mFlags |= semantic | - // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow. - (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY); + // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow. + (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY); } - if (ReadString(node.GetChild("normalRoughnessMap"), texturePath)) + if(ReadString(node.GetChild("normalRoughnessMap"), texturePath)) { ToUnixFileSeparators(texturePath); - if (MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL)) { mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "normal")); } - if (MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS)) { mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "roughness")); } - if (MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY)) { mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "transparency")); } const auto semantic = MaterialDefinition::NORMAL | MaterialDefinition::ROUGHNESS; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); materialDef.mFlags |= semantic; } - if (ReadString(node.GetChild("subsurfaceMap"), texturePath)) + if(ReadString(node.GetChild("subsurfaceMap"), texturePath)) { ToUnixFileSeparators(texturePath); const auto semantic = MaterialDefinition::SUBSURFACE; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); materialDef.mFlags |= semantic; } - if (ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) && - materialDef.mColor.a < 1.0f) + if(ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) && + materialDef.mColor.a < 1.0f) { materialDef.mFlags |= MaterialDefinition::TRANSPARENCY; } @@ -1013,9 +1024,9 @@ void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode ReadFloat(node.GetChild("roughness"), materialDef.mRoughness); bool mipmaps; - if (ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps) + if(ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps) { - for (auto& ts : materialDef.mTextureStages) + for(auto& ts : materialDef.mTextureStages) { ts.mTexture.mSamplerFlags |= SamplerFlags::FILTER_MIPMAP_LINEAR; } @@ -1039,13 +1050,13 @@ void DliLoader::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadP virtual bool Map(Index iDli, Index iScene) override { - Entry idx{ iDli, iScene }; - auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx); - if (iInsert == mIndices.end() || iInsert->iDli != iDli) + Entry idx{iDli, iScene}; + auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx); + if(iInsert == mIndices.end() || iInsert->iDli != iDli) { mIndices.insert(iInsert, idx); } - else if (iInsert->iScene != iScene) + else if(iInsert->iScene != iScene) { return false; } @@ -1054,10 +1065,9 @@ void DliLoader::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadP virtual unsigned int Resolve(Index iDli) override { - auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, - [](const Entry& idx, Index iDli) { - return idx.iDli < iDli; - }); + auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, [](const Entry& idx, Index iDli) { + return idx.iDli < iDli; + }); DALI_ASSERT_ALWAYS(iFind != mIndices.end()); return iFind->iScene; } @@ -1078,24 +1088,28 @@ void DliLoader::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadP ParseNodesInternal(nodes, index, parents, params, mapper); auto& scene = params.output.mScene; - for (size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0) + for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0) { - for (auto& c : scene.GetNode(i0)->mConstraints) + for(auto& c : scene.GetNode(i0)->mConstraints) { c.mSourceIdx = mapper.Resolve(c.mSourceIdx); } } } -void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, - std::vector& inOutParentStack, LoadParams& params, IIndexMapper& mapper) +void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, std::vector& inOutParentStack, LoadParams& params, IIndexMapper& mapper) { // Properties that may be resolved from a JSON value with ReadInt() -- or default to 0. - struct IndexProperty { ResourceType::Value type; const TreeNode* source; Index& target; }; + struct IndexProperty + { + ResourceType::Value type; + const TreeNode* source; + Index& target; + }; std::vector resourceIds; resourceIds.reserve(4); - if (auto node = GetNthChild(nodes, index)) + if(auto node = GetNthChild(nodes, index)) { NodeDefinition nodeDef; nodeDef.mParentIdx = inOutParentStack.empty() ? INVALID_INDEX : inOutParentStack.back(); @@ -1115,32 +1129,32 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde // not successful then reads it as a vector2. ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 3) || ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 2) || - ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) || - ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2); + ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) || + ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2); // visibility ReadBool(node->GetChild("visible"), nodeDef.mIsVisible); // type classification - if (auto eCustomization = node->GetChild("customization")) // customization + if(auto eCustomization = node->GetChild("customization")) // customization { std::string tag; - if (ReadString(eCustomization->GetChild("tag"), tag)) + if(ReadString(eCustomization->GetChild("tag"), tag)) { - nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{ tag }); + nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{tag}); } } else // something renderable maybe { std::unique_ptr renderable; - ModelNode* modelNode = nullptr; // no ownership, aliasing renderable for the right type. + ModelNode* modelNode = nullptr; // no ownership, aliasing renderable for the right type. - const TreeNode* eRenderable = nullptr; - if ((eRenderable = node->GetChild("model"))) + const TreeNode* eRenderable = nullptr; + if((eRenderable = node->GetChild("model"))) { // check for mesh before allocating - this can't be missing. auto eMesh = eRenderable->GetChild("mesh"); - if (!eMesh) + if(!eMesh) { ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition."; } @@ -1148,13 +1162,13 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde modelNode = new ModelNode(); renderable.reset(modelNode); - resourceIds.push_back({ ResourceType::Mesh, eMesh, modelNode->mMeshIdx }); + resourceIds.push_back({ResourceType::Mesh, eMesh, modelNode->mMeshIdx}); } - else if ((eRenderable = node->GetChild("arc"))) + else if((eRenderable = node->GetChild("arc"))) { // check for mesh before allocating - this can't be missing. auto eMesh = eRenderable->GetChild("mesh"); - if (!eMesh) + if(!eMesh) { ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition."; } @@ -1163,26 +1177,26 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde renderable.reset(arcNode); modelNode = arcNode; - resourceIds.push_back({ ResourceType::Mesh, eMesh, arcNode->mMeshIdx }); + resourceIds.push_back({ResourceType::Mesh, eMesh, arcNode->mMeshIdx}); ReadArcField(eRenderable, *arcNode); } - if (renderable) // process common properties of all renderables + register payload + if(renderable) // process common properties of all renderables + register payload { // shader renderable->mShaderIdx = 0; - auto eShader = eRenderable->GetChild("shader"); - resourceIds.push_back({ ResourceType::Shader, eShader, renderable->mShaderIdx }); + auto eShader = eRenderable->GetChild("shader"); + resourceIds.push_back({ResourceType::Shader, eShader, renderable->mShaderIdx}); // color - if (modelNode) + if(modelNode) { - modelNode->mMaterialIdx = 0; // must offer default of 0 - auto eMaterial = eRenderable->GetChild("material"); - resourceIds.push_back({ ResourceType::Material, eMaterial, modelNode->mMaterialIdx }); + modelNode->mMaterialIdx = 0; // must offer default of 0 + auto eMaterial = eRenderable->GetChild("material"); + resourceIds.push_back({ResourceType::Material, eMaterial, modelNode->mMaterialIdx}); - if (!ReadColorCodeOrColor(eRenderable, modelNode->mColor, params.input.mConvertColorCode)) + if(!ReadColorCodeOrColor(eRenderable, modelNode->mColor, params.input.mConvertColorCode)) { ReadColorCodeOrColor(node, modelNode->mColor, params.input.mConvertColorCode); } @@ -1194,82 +1208,83 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde // Resolve ints - default to 0 if undefined auto& output = params.output; - for (auto& idRes : resourceIds) + for(auto& idRes : resourceIds) { Index iCheck = 0; - switch (idRes.type) + switch(idRes.type) { - case ResourceType::Shader: - iCheck = output.mResources.mShaders.size(); - break; + case ResourceType::Shader: + iCheck = output.mResources.mShaders.size(); + break; - case ResourceType::Mesh: - iCheck = output.mResources.mMeshes.size(); - break; + case ResourceType::Mesh: + iCheck = output.mResources.mMeshes.size(); + break; - case ResourceType::Material: - iCheck = output.mResources.mMaterials.size(); - break; + case ResourceType::Material: + iCheck = output.mResources.mMaterials.size(); + break; - default: - ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << - idRes.type << " (Programmer error)"; + default: + ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << idRes.type << " (Programmer error)"; } - if (!idRes.source) + if(!idRes.source) { idRes.target = 0; } - else if (idRes.source->GetType() != TreeNode::INTEGER) + else if(idRes.source->GetType() != TreeNode::INTEGER) { - ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << - GetResourceTypeName(idRes.type) << " index type."; + ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << GetResourceTypeName(idRes.type) << " index type."; } else { idRes.target = idRes.source->GetInteger(); } - if (idRes.target >= iCheck) + if(idRes.target >= iCheck) { - ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << - GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << - iCheck << ")."; + ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << iCheck << ")."; } } resourceIds.clear(); // Extra properties - if (auto eExtras = node->GetChild("extras")) + if(auto eExtras = node->GetChild("extras")) { auto& extras = nodeDef.mExtras; extras.reserve(eExtras->Size()); NodeDefinition::Extra e; - for (auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0) + for(auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0) { auto eExtra = *i0; - e.mKey = eExtra.first; - if (e.mKey.empty()) + e.mKey = eExtra.first; + if(e.mKey.empty()) { mOnError(FormatString("node %d: empty string is invalid for name of extra %d; ignored.", - index, extras.size())); + index, + extras.size())); continue; } e.mValue = ReadPropertyValue(eExtra.second); - if (e.mValue.GetType() == Property::Type::NONE) + if(e.mValue.GetType() == Property::Type::NONE) { mOnError(FormatString("node %d: failed to interpret value of extra '%s' : %s; ignored.", - index, e.mKey.c_str(), eExtra.second.GetString())); + index, + e.mKey.c_str(), + eExtra.second.GetString())); } else { auto iInsert = std::lower_bound(extras.begin(), extras.end(), e); - if (iInsert != extras.end() && iInsert->mKey == e.mKey) + if(iInsert != extras.end() && iInsert->mKey == e.mKey) { mOnError(FormatString("node %d: extra '%s' already defined; overriding with %s.", - index, e.mKey.c_str(), eExtra.second.GetString())); + index, + e.mKey.c_str(), + eExtra.second.GetString())); *iInsert = std::move(e); } else @@ -1281,29 +1296,33 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde } // Constraints - if (auto eConstraints = node->GetChild("constraints")) + if(auto eConstraints = node->GetChild("constraints")) { auto& constraints = nodeDef.mConstraints; constraints.reserve(eConstraints->Size()); ConstraintDefinition cDef; - for (auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0) + for(auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0) { auto eConstraint = *i0; - if (!ReadIndex(&eConstraint.second, cDef.mSourceIdx)) + if(!ReadIndex(&eConstraint.second, cDef.mSourceIdx)) { mOnError(FormatString("node %d: node ID %s for constraint %d is invalid; ignored.", - index, eConstraint.second.GetString(), constraints.size())); + index, + eConstraint.second.GetString(), + constraints.size())); } else { cDef.mProperty = eConstraint.first; auto iInsert = std::lower_bound(constraints.begin(), constraints.end(), cDef); - if (iInsert != constraints.end() && *iInsert == cDef) + if(iInsert != constraints.end() && *iInsert == cDef) { mOnError(FormatString("node %d: constraint %s@%d already defined; ignoring.", - index, cDef.mProperty.c_str(), cDef.mSourceIdx)); + index, + cDef.mProperty.c_str(), + cDef.mSourceIdx)); } else { @@ -1315,53 +1334,52 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde // Determine index for mapping const unsigned int myIndex = output.mScene.GetNodeCount(); - if (!mapper.Map(index, myIndex)) + if(!mapper.Map(index, myIndex)) { mOnError(FormatString("node %d: error mapping dli index %d: node has multiple parents. Ignoring subtree.")); return; } // if the node is a bone in a skeletal animation, it will have the inverse bind pose matrix. - Matrix invBindMatrix{ false }; - if (ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking? + Matrix invBindMatrix{false}; + if(ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking? { mInverseBindMatrices[myIndex] = invBindMatrix; } // Register nodeDef auto rawDef = output.mScene.AddNode(std::make_unique(std::move(nodeDef))); - if (rawDef) // NOTE: no ownership. Guaranteed to stay in scope. + if(rawDef) // NOTE: no ownership. Guaranteed to stay in scope. { // ...And only then parse children. - if (auto children = node->GetChild("children")) + if(auto children = node->GetChild("children")) { inOutParentStack.push_back(myIndex); rawDef->mChildren.reserve(children->Size()); uint32_t iChild = 0; - for (auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild) + for(auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild) { auto& child = (*j0).second; - if (child.GetType() == TreeNode::INTEGER) + if(child.GetType() == TreeNode::INTEGER) { ParseNodesInternal(nodes, child.GetInteger(), inOutParentStack, params, mapper); // child object is created in scene definition. } else { - ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << - ": invalid index type."; + ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << ": invalid index type."; } } inOutParentStack.pop_back(); } - else if (rawDef->mCustomization) + else if(rawDef->mCustomization) { mOnError(FormatString("node %d: not an actual customization without children.", index)); } - if (auto proc = params.input.mNodePropertyProcessor) // optional processing + if(auto proc = params.input.mNodePropertyProcessor) // optional processing { // WARNING: constraint IDs are not resolved at this point. Property::Map nodeData; @@ -1381,19 +1399,19 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& auto& definitions = params.output.mAnimationDefinitions; definitions.reserve(definitions.size() + tnAnimations->Size()); - for (TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd(); - iAnim != iAnimEnd; ++iAnim) + for(TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd(); + iAnim != iAnimEnd; + ++iAnim) { - const TreeNode& tnAnim = (*iAnim).second; + const TreeNode& tnAnim = (*iAnim).second; AnimationDefinition animDef; ReadString(tnAnim.GetChild(NAME), animDef.mName); - auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef, - [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) { + auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef, [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) { return ad0.mName < ad1.mName; }); const bool overwrite = iFind != definitions.end() && iFind->mName == animDef.mName; - if (overwrite) + if(overwrite) { mOnError(FormatString("Pre-existing animation with name '%s' is being overwritten.", animDef.mName.c_str())); } @@ -1403,103 +1421,107 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& // than our frame delay) to not be restrictive WRT replaying. If anything needs // to occur more frequently, then Animations are likely not your solution anyway. animDef.mDuration = AnimationDefinition::MIN_DURATION_SECONDS; - if (!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration)) + if(!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration)) { mOnError(FormatString("Animation '%s' fails to define '%s', defaulting to %f.", - animDef.mName.c_str(), "duration", animDef.mDuration)); + animDef.mName.c_str(), + "duration", + animDef.mDuration)); } // Get loop count - # of playbacks. Default is once. 0 means repeat indefinitely. animDef.mLoopCount = 1; - if (ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) && - animDef.mLoopCount < 0) + if(ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) && + animDef.mLoopCount < 0) { animDef.mLoopCount = 0; } std::string endAction; - if (ReadString(tnAnim.GetChild("endAction"), endAction)) + if(ReadString(tnAnim.GetChild("endAction"), endAction)) { - if ("BAKE" == endAction) + if("BAKE" == endAction) { animDef.mEndAction = Animation::BAKE; } - else if ("DISCARD" == endAction) + else if("DISCARD" == endAction) { animDef.mEndAction = Animation::DISCARD; } - else if ("BAKE_FINAL" == endAction) + else if("BAKE_FINAL" == endAction) { animDef.mEndAction = Animation::BAKE_FINAL; } } - if (ReadString(tnAnim.GetChild("disconnectAction"), endAction)) + if(ReadString(tnAnim.GetChild("disconnectAction"), endAction)) { - if ("BAKE" == endAction) + if("BAKE" == endAction) { animDef.mDisconnectAction = Animation::BAKE; } - else if ("DISCARD" == endAction) + else if("DISCARD" == endAction) { animDef.mDisconnectAction = Animation::DISCARD; } - else if ("BAKE_FINAL" == endAction) + else if("BAKE_FINAL" == endAction) { animDef.mDisconnectAction = Animation::BAKE_FINAL; } } - if (const TreeNode* tnProperties = tnAnim.GetChild("properties")) + if(const TreeNode* tnProperties = tnAnim.GetChild("properties")) { animDef.mProperties.reserve(tnProperties->Size()); - for (TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd(); - iProperty != iPropertyEnd; ++iProperty) + for(TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd(); + iProperty != iPropertyEnd; + ++iProperty) { - const TreeNode &tnProperty = (*iProperty).second; + const TreeNode& tnProperty = (*iProperty).second; AnimatedProperty animProp; - if (!ReadString(tnProperty.GetChild("node"), animProp.mNodeName)) + if(!ReadString(tnProperty.GetChild("node"), animProp.mNodeName)) { mOnError(FormatString("Animation '%s': Failed to read the 'node' tag.", animDef.mName.c_str())); continue; } - if (!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName)) + if(!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName)) { mOnError(FormatString("Animation '%s': Failed to read the 'property' tag", animDef.mName.c_str())); continue; } // these are the defaults - animProp.mTimePeriod.delaySeconds = 0.f; + animProp.mTimePeriod.delaySeconds = 0.f; animProp.mTimePeriod.durationSeconds = animDef.mDuration; - if (!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod)) + if(!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod)) { mOnError(FormatString("Animation '%s': timePeriod missing in Property #%d: defaulting to %f.", - animDef.mName.c_str(), animDef.mProperties.size(), animProp.mTimePeriod.durationSeconds)); + animDef.mName.c_str(), + animDef.mProperties.size(), + animProp.mTimePeriod.durationSeconds)); } std::string alphaFunctionValue; - if (ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue)) + if(ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue)) { animProp.mAlphaFunction = GetAlphaFunction(alphaFunctionValue); } - if (const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin")) + if(const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin")) { DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name"); std::ifstream binAniFile; - std::string animationFilename; - if (ReadString(tnKeyFramesBin->GetChild(URL), animationFilename)) + std::string animationFilename; + if(ReadString(tnKeyFramesBin->GetChild(URL), animationFilename)) { std::string animationFullPath = params.input.mAnimationsPath + animationFilename; binAniFile.open(animationFullPath, std::ios::binary); - if (binAniFile.fail()) + if(binAniFile.fail()) { - ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << - animationFullPath << "'"; + ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << animationFullPath << "'"; } } @@ -1519,12 +1541,12 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& //so, if it is vector3 we assume is position or scale keys, if it is vector4 we assume is rotation, // otherwise are blend shape weight keys. // TODO support for binary header with size information - Property::Type propType = Property::FLOAT; // assume blend shape weights - if (animProp.mPropertyName == "orientation") + Property::Type propType = Property::FLOAT; // assume blend shape weights + if(animProp.mPropertyName == "orientation") { propType = Property::VECTOR4; } - else if ((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale")) + else if((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale")) { propType = Property::VECTOR3; } @@ -1533,18 +1555,18 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& // NOTE: right now we're just using AlphaFunction::LINEAR. unsigned char dummyAlphaFunction; - float progress; + float progress; Property::Value propValue; - for (int key = 0; key < numKeys; key++) + for(int key = 0; key < numKeys; key++) { binAniFile.read(reinterpret_cast(&progress), sizeof(float)); - if (propType == Property::VECTOR3) + if(propType == Property::VECTOR3) { Vector3 value; binAniFile.read(reinterpret_cast(value.AsFloat()), sizeof(float) * 3); propValue = Property::Value(value); } - else if (propType == Property::VECTOR4) + else if(propType == Property::VECTOR4) { Vector4 value; binAniFile.read(reinterpret_cast(value.AsFloat()), sizeof(float) * 4); @@ -1562,16 +1584,16 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& animProp.mKeyFrames.Add(progress, propValue, AlphaFunction::LINEAR); } } - else if (const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames")) + else if(const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames")) { DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name"); animProp.mKeyFrames = KeyFrames::New(); float progress = 0.0f; - for (auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0) + for(auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0) { const TreeNode::KeyNodePair& kfKeyChild = *i0; - bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress); + bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress); DALI_ASSERT_ALWAYS(readResult && "Key frame entry must have 'progress'"); const TreeNode* tnValue = kfKeyChild.second.GetChild("value"); @@ -1580,8 +1602,8 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& // For the "orientation" property, convert from Vector4 -> Rotation value // This work-around is preferable to a null-pointer exception in the DALi update thread Property::Value propValue(ReadPropertyValue(*tnValue)); - if (propValue.GetType() == Property::VECTOR4 && - animProp.mPropertyName == "orientation") + if(propValue.GetType() == Property::VECTOR4 && + animProp.mPropertyName == "orientation") { Vector4 v; propValue.Get(v); @@ -1589,8 +1611,8 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& } AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT); - std::string alphaFuncStr; - if (ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr)) + std::string alphaFuncStr; + if(ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr)) { kfAlphaFunction = GetAlphaFunction(alphaFuncStr); } @@ -1601,14 +1623,14 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& else { const TreeNode* tnValue = tnProperty.GetChild("value"); - if (tnValue) + if(tnValue) { - animProp.mValue.reset(new AnimatedProperty::Value{ ReadPropertyValue(*tnValue) }); + animProp.mValue.reset(new AnimatedProperty::Value{ReadPropertyValue(*tnValue)}); } else { mOnError(FormatString("Property '%s' fails to define target value.", - animProp.mPropertyName.c_str())); + animProp.mPropertyName.c_str())); } ReadBool(tnProperty.GetChild("relative"), animProp.mValue->mIsRelative); @@ -1618,7 +1640,7 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& } } - if (overwrite) + if(overwrite) { *iFind = std::move(animDef); } @@ -1627,7 +1649,7 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& iFind = definitions.insert(iFind, std::move(animDef)); } - if (auto proc = params.input.mAnimationPropertyProcessor) // optional processing + if(auto proc = params.input.mAnimationPropertyProcessor) // optional processing { Property::Map map; ParseProperties(tnAnim, map); @@ -1641,23 +1663,23 @@ void DliLoader::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationG auto& animGroups = params.output.mAnimationGroupDefinitions; int numGroups = 0; - for (auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd(); - iGroups != iGroupsEnd; ++iGroups, ++numGroups) + for(auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd(); + iGroups != iGroupsEnd; + ++iGroups, ++numGroups) { const auto& tnGroup = *iGroups; - auto tnName = tnGroup.second.GetChild(NAME); + auto tnName = tnGroup.second.GetChild(NAME); std::string groupName; - if (!tnName || !ReadString(tnName, groupName)) + if(!tnName || !ReadString(tnName, groupName)) { mOnError(FormatString("Failed to get the name for the Animation group %d; ignoring.", numGroups)); continue; } - auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, - [](const AnimationGroupDefinition& group, const std::string& name) { + auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, [](const AnimationGroupDefinition& group, const std::string& name) { return group.mName < name; }); - if (iFind != animGroups.end() && iFind->mName == groupName) + if(iFind != animGroups.end() && iFind->mName == groupName) { mOnError(FormatString("Animation group with name '%s' already exists; new entries will be merged.", groupName.c_str())); } @@ -1669,11 +1691,11 @@ void DliLoader::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationG iFind->mName = groupName; auto tnAnims = tnGroup.second.GetChild("animations"); - if (tnAnims && tnAnims->Size() > 0) + if(tnAnims && tnAnims->Size() > 0) { auto& anims = iFind->mAnimations; anims.reserve(anims.size() + tnAnims->Size()); - for (auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims) + for(auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims) { anims.push_back((*iAnims).second.GetString()); } @@ -1683,23 +1705,23 @@ void DliLoader::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationG void DliLoader::Impl::GetCameraParameters(std::vector& cameras) const { - if (const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras")) + if(const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras")) { cameras.resize(jsonCameras->Size()); auto iCamera = cameras.begin(); - for (auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0) + for(auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0) { auto& jsonCamera = (*i0).second; ReadFloat(jsonCamera.GetChild("fov"), iCamera->yFov); ReadFloat(jsonCamera.GetChild("near"), iCamera->zNear); ReadFloat(jsonCamera.GetChild("far"), iCamera->zFar); - if (ReadVector(jsonCamera.GetChild("orthographic"), iCamera->orthographicSize.AsFloat(), 4u)) + if(ReadVector(jsonCamera.GetChild("orthographic"), iCamera->orthographicSize.AsFloat(), 4u)) { iCamera->isPerspective = false; } - if (auto jsonMatrix = jsonCamera.GetChild("matrix")) + if(auto jsonMatrix = jsonCamera.GetChild("matrix")) { ReadVector(jsonMatrix, iCamera->matrix.AsFloat(), 16u); } @@ -1711,62 +1733,64 @@ void DliLoader::Impl::GetCameraParameters(std::vector& cameras void DliLoader::Impl::GetLightParameters(std::vector& lights) const { - if (const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights")) + if(const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights")) { lights.resize(jsonLights->Size()); auto iLight = lights.begin(); - for (auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0) + for(auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0) { auto& jsonLight = (*i0).second; - if (!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16)) + if(!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16)) { mOnError( FormatString("Failed to parse light %d - \"matrix\" child with 16 floats expected.\n", - std::distance(jsonLights->CBegin(), i0))); + std::distance(jsonLights->CBegin(), i0))); continue; } int shadowMapSize = 0; - if (ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0) + if(ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0) { mOnError( FormatString("Failed to parse light %d - %s has an invalid value.", - std::distance(jsonLights->CBegin(), i0), SHADOW_MAP_SIZE)); + std::distance(jsonLights->CBegin(), i0), + SHADOW_MAP_SIZE)); continue; } iLight->shadowMapSize = shadowMapSize; float orthoSize = 0.f; - if (ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) && - (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize))) + if(ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) && + (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize))) { mOnError( FormatString("Failed to parse light %d - %s has an invalid value.", - std::distance(jsonLights->CBegin(), i0), ORTHOGRAPHIC_SIZE)); + std::distance(jsonLights->CBegin(), i0), + ORTHOGRAPHIC_SIZE)); continue; } iLight->orthographicSize = orthoSize; - if ((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f)) + if((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f)) { mOnError(FormatString( "Light %d: Both shadow map size and orthographic size must be set for shadows to work.", - std::distance(jsonLights->CBegin(), i0))); + std::distance(jsonLights->CBegin(), i0))); } - if (!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional + if(!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional { - iLight->color = Vector3::ONE; // default to white + iLight->color = Vector3::ONE; // default to white } - if (!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional + if(!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional { - iLight->intensity = 1.0f; // default to 1.0 + iLight->intensity = 1.0f; // default to 1.0 } - if (!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional + if(!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional { - iLight->shadowIntensity = 1.0f; // default to 1.0 + iLight->shadowIntensity = 1.0f; // default to 1.0 } ++iLight; @@ -1774,5 +1798,5 @@ void DliLoader::Impl::GetLightParameters(std::vector& lights) c } } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/dli-loader.h b/dali-scene-loader/public-api/dli-loader.h index e09d4d0..b46a7bf 100644 --- a/dali-scene-loader/public-api/dli-loader.h +++ b/dali-scene-loader/public-api/dli-loader.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_DLI_LOADER_H #define DALI_SCENE_LOADER_DLI_LOADER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,12 @@ * */ - // INTERNAL INCLUDES -#include "dali-scene-loader/public-api/api.h" +// INTERNAL INCLUDES #include "dali-scene-loader/public-api/animation-definition.h" +#include "dali-scene-loader/public-api/api.h" #include "dali-scene-loader/public-api/customization.h" -#include "dali-scene-loader/public-api/string-callback.h" #include "dali-scene-loader/public-api/index.h" +#include "dali-scene-loader/public-api/string-callback.h" // EXTERNAL INCLUDES #include "dali/public-api/common/vector-wrapper.h" @@ -46,17 +46,19 @@ class SceneDefinition; class DALI_SCENE_LOADER_API DliLoader { public: - using ConvertFontCode = void(*)(const std::string& code, std::string& fontFamily, std::string& slant, std::string& weight, float& size); - using ConvertColorCode = Vector4(*)(const std::string& code); + using ConvertFontCode = void (*)(const std::string& code, std::string& fontFamily, std::string& slant, std::string& weight, float& size); + using ConvertColorCode = Vector4 (*)(const std::string& code); - using CategoryProcessor = std::function; + using CategoryProcessor = std::function; using CategoryProcessorVector = std::vector>; using NodeProcessor = std::function; + Property::Map&& nodeData, + StringCallback onError)>; using AnimationProcessor = std::function; + Property::Map&& animData, + StringCallback onError)>; struct InputParams { @@ -105,7 +107,7 @@ public: struct LoadParams { InputParams const& input; - LoadResult& output; + LoadResult& output; }; DliLoader(); @@ -133,7 +135,7 @@ private: const std::unique_ptr mImpl; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif // DALI_SCENE_LOADER_DLI_LOADER_H diff --git a/dali-scene-loader/public-api/environment-definition.cpp b/dali-scene-loader/public-api/environment-definition.cpp index 16c8e2c..c95883f 100644 --- a/dali-scene-loader/public-api/environment-definition.cpp +++ b/dali-scene-loader/public-api/environment-definition.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,24 +23,22 @@ namespace Dali { namespace SceneLoader { - EnvironmentDefinition::RawData - EnvironmentDefinition::LoadRaw(const std::string& environmentsPath) const +EnvironmentDefinition::LoadRaw(const std::string& environmentsPath) const { RawData raw; - auto loadFn = [&environmentsPath](const std::string& path, CubeData& cd) { - if (path.empty()) + auto loadFn = [&environmentsPath](const std::string& path, CubeData& cd) { + if(path.empty()) { cd.data.resize(6); - for (auto& face : cd.data) + for(auto& face : cd.data) { - face.push_back(PixelData::New(new uint8_t[3]{ 0xff, 0xff, 0xff }, 3, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY)); + face.push_back(PixelData::New(new uint8_t[3]{0xff, 0xff, 0xff}, 3, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY)); } } else if(!LoadCubeMapData(environmentsPath + path, cd)) { - ExceptionFlinger(ASSERT_LOCATION) << "Failed to load cubemap texture from '" << - path << "'."; + ExceptionFlinger(ASSERT_LOCATION) << "Failed to load cubemap texture from '" << path << "'."; } }; @@ -54,18 +52,18 @@ EnvironmentDefinition::Textures EnvironmentDefinition::Load(RawData&& raw) const Textures textures; // This texture should have 6 faces and only one mipmap - if (!raw.mDiffuse.data.empty()) + if(!raw.mDiffuse.data.empty()) { textures.mDiffuse = raw.mDiffuse.CreateTexture(); } // This texture should have 6 faces and 6 mipmaps - if (!raw.mSpecular.data.empty()) + if(!raw.mSpecular.data.empty()) { textures.mSpecular = raw.mSpecular.CreateTexture(); } return textures; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/environment-definition.h b/dali-scene-loader/public-api/environment-definition.h index 1b1906f..066f6fa 100644 --- a/dali-scene-loader/public-api/environment-definition.h +++ b/dali-scene-loader/public-api/environment-definition.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_ENVIRONMENT_DEFINITION_H #define DALI_SCENE_LOADER_ENVIRONMENT_DEFINITION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,19 +17,18 @@ * */ - // INTERNAL INCLUDES +// INTERNAL INCLUDES #include "dali-scene-loader/public-api/api.h" #include "dali-scene-loader/public-api/ktx-loader.h" // EXTERNAL INCLUDES -#include "dali/public-api/rendering/texture.h" #include "dali/public-api/math/quaternion.h" +#include "dali/public-api/rendering/texture.h" namespace Dali { namespace SceneLoader { - /** * @brief Defines an environment map with either or both of radiance * and irradiance maps. @@ -39,7 +38,7 @@ struct DALI_SCENE_LOADER_API EnvironmentDefinition struct Textures { Texture mDiffuse; // irradiance - Texture mSpecular; // radiance + Texture mSpecular; // radiance bool IsLoaded() const { @@ -54,7 +53,7 @@ struct DALI_SCENE_LOADER_API EnvironmentDefinition }; using EnvironmentData = std::pair; - using Vector = std::vector; + using Vector = std::vector; EnvironmentDefinition() = default; @@ -80,11 +79,11 @@ struct DALI_SCENE_LOADER_API EnvironmentDefinition public: // DATA std::string mDiffuseMapPath; std::string mSpecularMapPath; - Quaternion mCubeOrientation = Quaternion::IDENTITY; - float mIblIntensity = 1.0f; + Quaternion mCubeOrientation = Quaternion::IDENTITY; + float mIblIntensity = 1.0f; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_ENVIRONMENT_DEFINITION_H diff --git a/dali-scene-loader/public-api/gltf2-loader.cpp b/dali-scene-loader/public-api/gltf2-loader.cpp index 451060b..18923cf 100644 --- a/dali-scene-loader/public-api/gltf2-loader.cpp +++ b/dali-scene-loader/public-api/gltf2-loader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,17 +14,20 @@ * limitations under the License. * */ +#include "dali-scene-loader/public-api/gltf2-loader.h" +#include +#include "dali-scene-loader/internal/gltf2-asset.h" #include "dali-scene-loader/public-api/load-result.h" -#include "dali-scene-loader/public-api/scene-definition.h" #include "dali-scene-loader/public-api/resource-bundle.h" -#include "dali-scene-loader/public-api/gltf2-loader.h" -#include "dali-scene-loader/public-api/utils.h" +#include "dali-scene-loader/public-api/scene-definition.h" #include "dali-scene-loader/public-api/shader-definition-factory.h" -#include "dali-scene-loader/internal/gltf2-asset.h" +#include "dali-scene-loader/public-api/utils.h" #include "dali/public-api/math/quaternion.h" -#include -#define ENUM_STRING_MAPPING(t, x) { #x, t::x } +#define ENUM_STRING_MAPPING(t, x) \ + { \ +#x, t::x \ + } namespace gt = gltf2; namespace js = json; @@ -47,20 +50,19 @@ const Geometry::Type GLTF2_TO_DALI_PRIMITIVES[]{ Geometry::LINE_STRIP, Geometry::TRIANGLES, Geometry::TRIANGLE_STRIP, - Geometry::TRIANGLE_FAN -}; //...because Dali swaps the last two. + Geometry::TRIANGLE_FAN}; //...because Dali swaps the last two. struct AttributeMapping { - gt::Attribute::Type mType; - MeshDefinition::Accessor MeshDefinition::* mAccessor; - uint16_t mElementSizeRequired; + gt::Attribute::Type mType; + MeshDefinition::Accessor MeshDefinition::*mAccessor; + uint16_t mElementSizeRequired; } ATTRIBUTE_MAPPINGS[]{ - { gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3) }, - { gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3) }, - { gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2) }, - { gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4) }, - { gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4) }, + {gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3)}, + {gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3)}, + {gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2)}, + {gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4)}, + {gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4)}, }; std::vector ReadAnimationArray(const json_value_s& j) @@ -70,9 +72,9 @@ std::vector ReadAnimationArray(const json_value_s& j) auto results = js::Read::Array::Read>(j); - for (auto& animation : results) + for(auto& animation : results) { - for (auto& channel : animation.mChannels) + for(auto& channel : animation.mChannels) { channel.mSampler.UpdateVector(animation.mSamplers); } @@ -89,124 +91,110 @@ void ApplyAccessorMinMax(const gt::Accessor& acc, float* values) } const auto BUFFER_READER = std::move(js::Reader() - .Register(*js::MakeProperty("byteLength", js::Read::Number, >::Buffer::mByteLength)) - .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri)) -); + .Register(*js::MakeProperty("byteLength", js::Read::Number, >::Buffer::mByteLength)) + .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri))); const auto BUFFER_VIEW_READER = std::move(js::Reader() - .Register(*js::MakeProperty("buffer", gt::RefReader::Read, >::BufferView::mBuffer)) - .Register(*js::MakeProperty("byteOffset", js::Read::Number, >::BufferView::mByteOffset)) - .Register(*js::MakeProperty("byteLength", js::Read::Number, >::BufferView::mByteLength)) - .Register(*js::MakeProperty("byteStride", js::Read::Number, >::BufferView::mByteStride)) - .Register(*js::MakeProperty("target", js::Read::Number, >::BufferView::mTarget)) -); + .Register(*js::MakeProperty("buffer", gt::RefReader::Read, >::BufferView::mBuffer)) + .Register(*js::MakeProperty("byteOffset", js::Read::Number, >::BufferView::mByteOffset)) + .Register(*js::MakeProperty("byteLength", js::Read::Number, >::BufferView::mByteLength)) + .Register(*js::MakeProperty("byteStride", js::Read::Number, >::BufferView::mByteStride)) + .Register(*js::MakeProperty("target", js::Read::Number, >::BufferView::mTarget))); const auto BUFFER_VIEW_CLIENT_READER = std::move(js::Reader() - .Register(*js::MakeProperty("bufferView", gt::RefReader::Read, >::BufferViewClient::mBufferView)) - .Register(*js::MakeProperty("byteOffset", js::Read::Number, >::BufferViewClient::mByteOffset)) -); + .Register(*js::MakeProperty("bufferView", gt::RefReader::Read, >::BufferViewClient::mBufferView)) + .Register(*js::MakeProperty("byteOffset", js::Read::Number, >::BufferViewClient::mByteOffset))); const auto COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER = std::move(js::Reader() - .Register(*new js::Property>("bufferView", gt::RefReader::Read, >::ComponentTypedBufferViewClient::mBufferView)) - .Register(*new js::Property("byteOffset", js::Read::Number, >::ComponentTypedBufferViewClient::mByteOffset)) - .Register(*js::MakeProperty("componentType", js::Read::Enum, >::ComponentTypedBufferViewClient::mComponentType)) -); + .Register(*new js::Property>("bufferView", gt::RefReader::Read, >::ComponentTypedBufferViewClient::mBufferView)) + .Register(*new js::Property("byteOffset", js::Read::Number, >::ComponentTypedBufferViewClient::mByteOffset)) + .Register(*js::MakeProperty("componentType", js::Read::Enum, >::ComponentTypedBufferViewClient::mComponentType))); const auto ACCESSOR_SPARSE_READER = std::move(js::Reader() - .Register(*js::MakeProperty("count", js::Read::Number, >::Accessor::Sparse::mCount)) - .Register(*js::MakeProperty("indices", js::ObjectReader::Read, - >::Accessor::Sparse::mIndices)) - .Register(*js::MakeProperty("values", js::ObjectReader::Read, - >::Accessor::Sparse::mValues)) -); + .Register(*js::MakeProperty("count", js::Read::Number, >::Accessor::Sparse::mCount)) + .Register(*js::MakeProperty("indices", js::ObjectReader::Read, >::Accessor::Sparse::mIndices)) + .Register(*js::MakeProperty("values", js::ObjectReader::Read, >::Accessor::Sparse::mValues))); const auto ACCESSOR_READER = std::move(js::Reader() - .Register(*new js::Property>("bufferView", - gt::RefReader::Read, >::Accessor::mBufferView)) - .Register(*new js::Property("byteOffset", - js::Read::Number, >::Accessor::mByteOffset)) - .Register(*new js::Property("componentType", - js::Read::Enum, >::Accessor::mComponentType)) - .Register(*new js::Property("name", js::Read::StringView, >::Accessor::mName)) - .Register(*js::MakeProperty("count", js::Read::Number, >::Accessor::mCount)) - .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized)) - .Register(*js::MakeProperty("type", gt::ReadStringEnum, >::Accessor::mType)) - .Register(*js::MakeProperty("min", js::Read::Array, >::Accessor::mMin)) - .Register(*js::MakeProperty("max", js::Read::Array, >::Accessor::mMax)) - .Register(*new js::Property("sparse", js::ObjectReader::Read, - >::Accessor::SetSparse)) -); + .Register(*new js::Property>("bufferView", + gt::RefReader::Read, + >::Accessor::mBufferView)) + .Register(*new js::Property("byteOffset", + js::Read::Number, + >::Accessor::mByteOffset)) + .Register(*new js::Property("componentType", + js::Read::Enum, + >::Accessor::mComponentType)) + .Register(*new js::Property("name", js::Read::StringView, >::Accessor::mName)) + .Register(*js::MakeProperty("count", js::Read::Number, >::Accessor::mCount)) + .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized)) + .Register(*js::MakeProperty("type", gt::ReadStringEnum, >::Accessor::mType)) + .Register(*js::MakeProperty("min", js::Read::Array, >::Accessor::mMin)) + .Register(*js::MakeProperty("max", js::Read::Array, >::Accessor::mMax)) + .Register(*new js::Property("sparse", js::ObjectReader::Read, >::Accessor::SetSparse))); const auto IMAGE_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Material::mName)) - .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri)) - .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType)) - .Register(*js::MakeProperty("bufferView", gt::RefReader::Read, >::Image::mBufferView)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Material::mName)) + .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri)) + .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType)) + .Register(*js::MakeProperty("bufferView", gt::RefReader::Read, >::Image::mBufferView))); const auto SAMPLER_READER = std::move(js::Reader() - .Register(*js::MakeProperty("minFilter", js::Read::Enum, >::Sampler::mMinFilter)) - .Register(*js::MakeProperty("magFilter", js::Read::Enum, >::Sampler::mMagFilter)) - .Register(*js::MakeProperty("wrapS", js::Read::Enum, >::Sampler::mWrapS)) - .Register(*js::MakeProperty("wrapT", js::Read::Enum, >::Sampler::mWrapT)) -); + .Register(*js::MakeProperty("minFilter", js::Read::Enum, >::Sampler::mMinFilter)) + .Register(*js::MakeProperty("magFilter", js::Read::Enum, >::Sampler::mMagFilter)) + .Register(*js::MakeProperty("wrapS", js::Read::Enum, >::Sampler::mWrapS)) + .Register(*js::MakeProperty("wrapT", js::Read::Enum, >::Sampler::mWrapT))); const auto TEXURE_READER = std::move(js::Reader() - .Register(*js::MakeProperty("source", gt::RefReader::Read, >::Texture::mSource)) - .Register(*js::MakeProperty("sampler", gt::RefReader::Read, >::Texture::mSampler)) -); + .Register(*js::MakeProperty("source", gt::RefReader::Read, >::Texture::mSource)) + .Register(*js::MakeProperty("sampler", gt::RefReader::Read, >::Texture::mSampler))); const auto TEXURE_INFO_READER = std::move(js::Reader() - .Register(*js::MakeProperty("index", gt::RefReader::Read, >::TextureInfo::mTexture)) - .Register(*js::MakeProperty("texCoord", js::Read::Number, >::TextureInfo::mTexCoord)) - .Register(*js::MakeProperty("scale", js::Read::Number, >::TextureInfo::mScale)) -); + .Register(*js::MakeProperty("index", gt::RefReader::Read, >::TextureInfo::mTexture)) + .Register(*js::MakeProperty("texCoord", js::Read::Number, >::TextureInfo::mTexCoord)) + .Register(*js::MakeProperty("scale", js::Read::Number, >::TextureInfo::mScale))); const auto MATERIAL_PBR_READER = std::move(js::Reader() - .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector, >::Material::Pbr::mBaseColorFactor)) - .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader::Read, - >::Material::Pbr::mBaseColorTexture)) - .Register(*js::MakeProperty("metallicFactor", js::Read::Number, >::Material::Pbr::mMetallicFactor)) - .Register(*js::MakeProperty("roughnessFactor", js::Read::Number, >::Material::Pbr::mRoughnessFactor)) - .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader::Read, - >::Material::Pbr::mMetallicRoughnessTexture)) -); + .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector, >::Material::Pbr::mBaseColorFactor)) + .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader::Read, >::Material::Pbr::mBaseColorTexture)) + .Register(*js::MakeProperty("metallicFactor", js::Read::Number, >::Material::Pbr::mMetallicFactor)) + .Register(*js::MakeProperty("roughnessFactor", js::Read::Number, >::Material::Pbr::mRoughnessFactor)) + .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader::Read, >::Material::Pbr::mMetallicRoughnessTexture))); const auto MATERIAL_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Material::mName)) - .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader::Read, >::Material::mPbrMetallicRoughness)) - .Register(*js::MakeProperty("normalTexture", js::ObjectReader::Read, >::Material::mNormalTexture)) - .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader::Read, >::Material::mOcclusionTexture)) - .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader::Read, >::Material::mEmissiveTexture)) - .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector, >::Material::mEmissiveFactor)) - .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum, >::Material::mAlphaMode)) - .Register(*js::MakeProperty("alphaCutoff", js::Read::Number, >::Material::mAlphaCutoff)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Material::mName)) + .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader::Read, >::Material::mPbrMetallicRoughness)) + .Register(*js::MakeProperty("normalTexture", js::ObjectReader::Read, >::Material::mNormalTexture)) + .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader::Read, >::Material::mOcclusionTexture)) + .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader::Read, >::Material::mEmissiveTexture)) + .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector, >::Material::mEmissiveFactor)) + .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum, >::Material::mAlphaMode)) + .Register(*js::MakeProperty("alphaCutoff", js::Read::Number, >::Material::mAlphaCutoff))); std::map> ReadMeshPrimitiveAttributes(const json_value_s& j) { - auto& jo = js::Cast(j); + auto& jo = js::Cast(j); std::map> result; auto i = jo.start; - while (i) + while(i) { - auto jstr = *i->name; + auto jstr = *i->name; result[gt::Attribute::FromString(jstr.string, jstr.string_size)] = gt::RefReader::Read(*i->value); - i = i->next; + i = i->next; } return result; } std::vector>> ReadMeshPrimitiveTargets(const json_value_s& j) { - auto& jo = js::Cast(j); + auto& jo = js::Cast(j); std::vector>> result; result.reserve(jo.length); auto i = jo.start; - while (i) + while(i) { result.push_back(std::move(ReadMeshPrimitiveAttributes(*i->value))); i = i->next; @@ -216,128 +204,129 @@ std::vector>> ReadMeshPrimit } const auto MESH_PRIMITIVE_READER = std::move(js::Reader() - .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes)) - .Register(*js::MakeProperty("indices", gt::RefReader::Read, >::Mesh::Primitive::mIndices)) - .Register(*js::MakeProperty("material", gt::RefReader::Read, >::Mesh::Primitive::mMaterial)) - .Register(*js::MakeProperty("mode", js::Read::Enum, >::Mesh::Primitive::mMode)) - .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets)) -); + .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes)) + .Register(*js::MakeProperty("indices", gt::RefReader::Read, >::Mesh::Primitive::mIndices)) + .Register(*js::MakeProperty("material", gt::RefReader::Read, >::Mesh::Primitive::mMaterial)) + .Register(*js::MakeProperty("mode", js::Read::Enum, >::Mesh::Primitive::mMode)) + .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets))); const auto MESH_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Mesh::mName)) - .Register(*js::MakeProperty("primitives", - js::Read::Array::Read>, >::Mesh::mPrimitives)) - .Register(*js::MakeProperty("weights", js::Read::Array, >::Mesh::mWeights)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Mesh::mName)) + .Register(*js::MakeProperty("primitives", + js::Read::Array::Read>, + >::Mesh::mPrimitives)) + .Register(*js::MakeProperty("weights", js::Read::Array, >::Mesh::mWeights))); const auto SKIN_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Skin::mName)) - .Register(*js::MakeProperty("inverseBindMatrices", - gt::RefReader::Read, >::Skin::mInverseBindMatrices)) - .Register(*js::MakeProperty("skeleton", - gt::RefReader::Read, >::Skin::mSkeleton)) - .Register(*js::MakeProperty("joints", - js::Read::Array, gt::RefReader::Read>, >::Skin::mJoints)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Skin::mName)) + .Register(*js::MakeProperty("inverseBindMatrices", + gt::RefReader::Read, + >::Skin::mInverseBindMatrices)) + .Register(*js::MakeProperty("skeleton", + gt::RefReader::Read, + >::Skin::mSkeleton)) + .Register(*js::MakeProperty("joints", + js::Read::Array, gt::RefReader::Read>, + >::Skin::mJoints))); const auto CAMERA_PERSPECTIVE_READER = std::move(js::Reader() - .Register(*js::MakeProperty("aspectRatio", js::Read::Number, >::Camera::Perspective::mAspectRatio)) - .Register(*js::MakeProperty("yfov", js::Read::Number, >::Camera::Perspective::mYFov)) - .Register(*js::MakeProperty("zfar", js::Read::Number, >::Camera::Perspective::mZFar)) - .Register(*js::MakeProperty("znear", js::Read::Number, >::Camera::Perspective::mZNear)) -); // TODO: infinite perspective projection, where znear is omitted + .Register(*js::MakeProperty("aspectRatio", js::Read::Number, >::Camera::Perspective::mAspectRatio)) + .Register(*js::MakeProperty("yfov", js::Read::Number, >::Camera::Perspective::mYFov)) + .Register(*js::MakeProperty("zfar", js::Read::Number, >::Camera::Perspective::mZFar)) + .Register(*js::MakeProperty("znear", js::Read::Number, >::Camera::Perspective::mZNear))); // TODO: infinite perspective projection, where znear is omitted const auto CAMERA_ORTHOGRAPHIC_READER = std::move(js::Reader() - .Register(*js::MakeProperty("xmag", js::Read::Number, >::Camera::Orthographic::mXMag)) - .Register(*js::MakeProperty("ymag", js::Read::Number, >::Camera::Orthographic::mXMag)) - .Register(*js::MakeProperty("zfar", js::Read::Number, >::Camera::Orthographic::mZFar)) - .Register(*js::MakeProperty("znear", js::Read::Number, >::Camera::Orthographic::mZNear)) -); + .Register(*js::MakeProperty("xmag", js::Read::Number, >::Camera::Orthographic::mXMag)) + .Register(*js::MakeProperty("ymag", js::Read::Number, >::Camera::Orthographic::mXMag)) + .Register(*js::MakeProperty("zfar", js::Read::Number, >::Camera::Orthographic::mZFar)) + .Register(*js::MakeProperty("znear", js::Read::Number, >::Camera::Orthographic::mZNear))); const auto CAMERA_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Camera::mName)) - .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType)) - .Register(*js::MakeProperty("perspective", js::ObjectReader::Read, >::Camera::mPerspective)) - .Register(*js::MakeProperty("orthographic", js::ObjectReader::Read, >::Camera::mOrthographic)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Camera::mName)) + .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType)) + .Register(*js::MakeProperty("perspective", js::ObjectReader::Read, >::Camera::mPerspective)) + .Register(*js::MakeProperty("orthographic", js::ObjectReader::Read, >::Camera::mOrthographic))); const auto NODE_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Node::mName)) - .Register(*js::MakeProperty("translation", gt::ReadDaliVector, >::Node::mTranslation)) - .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation)) - .Register(*js::MakeProperty("scale", gt::ReadDaliVector, >::Node::mScale)) - .Register(*new js::Property("matrix", gt::ReadDaliVector, >::Node::SetMatrix)) - .Register(*js::MakeProperty("camera", gt::RefReader::Read, - >::Node::mCamera)) - .Register(*js::MakeProperty("children", js::Read::Array, gt::RefReader::Read>, - >::Node::mChildren)) - .Register(*js::MakeProperty("mesh", gt::RefReader::Read, >::Node::mMesh)) - .Register(*js::MakeProperty("skin", gt::RefReader::Read, >::Node::mSkin)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Node::mName)) + .Register(*js::MakeProperty("translation", gt::ReadDaliVector, >::Node::mTranslation)) + .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation)) + .Register(*js::MakeProperty("scale", gt::ReadDaliVector, >::Node::mScale)) + .Register(*new js::Property("matrix", gt::ReadDaliVector, >::Node::SetMatrix)) + .Register(*js::MakeProperty("camera", gt::RefReader::Read, >::Node::mCamera)) + .Register(*js::MakeProperty("children", js::Read::Array, gt::RefReader::Read>, >::Node::mChildren)) + .Register(*js::MakeProperty("mesh", gt::RefReader::Read, >::Node::mMesh)) + .Register(*js::MakeProperty("skin", gt::RefReader::Read, >::Node::mSkin))); const auto ANIMATION_SAMPLER_READER = std::move(js::Reader() - .Register(*js::MakeProperty("input", gt::RefReader::Read, - >::Animation::Sampler::mInput)) - .Register(*js::MakeProperty("output", gt::RefReader::Read, - >::Animation::Sampler::mOutput)) - .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum, >::Animation::Sampler::mInterpolation)) -); + .Register(*js::MakeProperty("input", gt::RefReader::Read, >::Animation::Sampler::mInput)) + .Register(*js::MakeProperty("output", gt::RefReader::Read, >::Animation::Sampler::mOutput)) + .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum, >::Animation::Sampler::mInterpolation))); const auto ANIMATION_TARGET_READER = std::move(js::Reader() - .Register(*js::MakeProperty("node", gt::RefReader::Read, - >::Animation::Channel::Target::mNode)) - .Register(*js::MakeProperty("path", gt::ReadStringEnum, - >::Animation::Channel::Target::mPath)) -); + .Register(*js::MakeProperty("node", gt::RefReader::Read, >::Animation::Channel::Target::mNode)) + .Register(*js::MakeProperty("path", gt::ReadStringEnum, >::Animation::Channel::Target::mPath))); const auto ANIMATION_CHANNEL_READER = std::move(js::Reader() - .Register(*js::MakeProperty("target", js::ObjectReader::Read, >::Animation::Channel::mTarget)) - .Register(*js::MakeProperty("sampler", gt::RefReader::Read, >::Animation::Channel::mSampler)) -); + .Register(*js::MakeProperty("target", js::ObjectReader::Read, >::Animation::Channel::mTarget)) + .Register(*js::MakeProperty("sampler", gt::RefReader::Read, >::Animation::Channel::mSampler))); const auto ANIMATION_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Animation::mName)) - .Register(*js::MakeProperty("samplers", - js::Read::Array::Read>, >::Animation::mSamplers)) - .Register(*js::MakeProperty("channels", - js::Read::Array::Read>, >::Animation::mChannels)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Animation::mName)) + .Register(*js::MakeProperty("samplers", + js::Read::Array::Read>, + >::Animation::mSamplers)) + .Register(*js::MakeProperty("channels", + js::Read::Array::Read>, + >::Animation::mChannels))); const auto SCENE_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Scene::mName)) - .Register(*js::MakeProperty("nodes", - js::Read::Array, gt::RefReader::Read>, >::Scene::mNodes)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Scene::mName)) + .Register(*js::MakeProperty("nodes", + js::Read::Array, gt::RefReader::Read>, + >::Scene::mNodes))); const auto DOCUMENT_READER = std::move(js::Reader() - .Register(*js::MakeProperty("buffers", - js::Read::Array::Read>, >::Document::mBuffers)) - .Register(*js::MakeProperty("bufferViews", - js::Read::Array::Read>, >::Document::mBufferViews)) - .Register(*js::MakeProperty("accessors", - js::Read::Array::Read>, >::Document::mAccessors)) - .Register(*js::MakeProperty("images", - js::Read::Array::Read>, >::Document::mImages)) - .Register(*js::MakeProperty("samplers", - js::Read::Array::Read>, >::Document::mSamplers)) - .Register(*js::MakeProperty("textures", - js::Read::Array::Read>, >::Document::mTextures)) - .Register(*js::MakeProperty("materials", - js::Read::Array::Read>, >::Document::mMaterials)) - .Register(*js::MakeProperty("meshes", - js::Read::Array::Read>, >::Document::mMeshes)) - .Register(*js::MakeProperty("skins", - js::Read::Array::Read>, >::Document::mSkins)) - .Register(*js::MakeProperty("cameras", - js::Read::Array::Read>, >::Document::mCameras)) - .Register(*js::MakeProperty("nodes", - js::Read::Array::Read>, >::Document::mNodes)) - .Register(*js::MakeProperty("animations", - ReadAnimationArray, >::Document::mAnimations)) - .Register(*js::MakeProperty("scenes", - js::Read::Array::Read>, >::Document::mScenes)) - .Register(*js::MakeProperty("scene", gt::RefReader::Read, >::Document::mScene)) -); + .Register(*js::MakeProperty("buffers", + js::Read::Array::Read>, + >::Document::mBuffers)) + .Register(*js::MakeProperty("bufferViews", + js::Read::Array::Read>, + >::Document::mBufferViews)) + .Register(*js::MakeProperty("accessors", + js::Read::Array::Read>, + >::Document::mAccessors)) + .Register(*js::MakeProperty("images", + js::Read::Array::Read>, + >::Document::mImages)) + .Register(*js::MakeProperty("samplers", + js::Read::Array::Read>, + >::Document::mSamplers)) + .Register(*js::MakeProperty("textures", + js::Read::Array::Read>, + >::Document::mTextures)) + .Register(*js::MakeProperty("materials", + js::Read::Array::Read>, + >::Document::mMaterials)) + .Register(*js::MakeProperty("meshes", + js::Read::Array::Read>, + >::Document::mMeshes)) + .Register(*js::MakeProperty("skins", + js::Read::Array::Read>, + >::Document::mSkins)) + .Register(*js::MakeProperty("cameras", + js::Read::Array::Read>, + >::Document::mCameras)) + .Register(*js::MakeProperty("nodes", + js::Read::Array::Read>, + >::Document::mNodes)) + .Register(*js::MakeProperty("animations", + ReadAnimationArray, + >::Document::mAnimations)) + .Register(*js::MakeProperty("scenes", + js::Read::Array::Read>, + >::Document::mScenes)) + .Register(*js::MakeProperty("scene", gt::RefReader::Read, >::Document::mScene))); struct NodeMapping { @@ -353,7 +342,7 @@ bool operator<(const NodeMapping& mapping, Index gltfIdx) class NodeIndexMapper { public: - NodeIndexMapper() = default; + NodeIndexMapper() = default; NodeIndexMapper(const NodeIndexMapper&) = delete; NodeIndexMapper& operator=(const NodeIndexMapper&) = delete; @@ -362,18 +351,18 @@ public: /// save growing a vector. void RegisterMapping(Index gltfIdx, Index runtimeIdx) { - if (gltfIdx != runtimeIdx) + if(gltfIdx != runtimeIdx) { auto iInsert = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); DALI_ASSERT_DEBUG(iInsert == mNodes.end() || iInsert->gltfIdx != gltfIdx); - mNodes.insert(iInsert, NodeMapping{ gltfIdx, runtimeIdx }); + mNodes.insert(iInsert, NodeMapping{gltfIdx, runtimeIdx}); } } ///@brief Retrieves the runtime index of a Node, mapped to the given @a gltfIdx. Index GetRuntimeId(Index gltfIdx) const { - auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator< + auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator< return (iFind != mNodes.end() && iFind->gltfIdx == gltfIdx) ? iFind->runtimeIdx : gltfIdx; } @@ -383,39 +372,35 @@ private: struct ConversionContext { - LoadResult& mOutput; + LoadResult& mOutput; std::string mPath; - Index mDefaultMaterial; + Index mDefaultMaterial; - std::vector mMeshIds; - NodeIndexMapper mNodeIndices; + std::vector mMeshIds; + NodeIndexMapper mNodeIndices; }; SamplerFlags::Type ConvertWrapMode(gt::Wrap::Type w) { - switch (w) + switch(w) { - case gt::Wrap::REPEAT: - return SamplerFlags::WRAP_REPEAT; - case gt::Wrap::CLAMP_TO_EDGE: - return SamplerFlags::WRAP_CLAMP; - case gt::Wrap::MIRRORED_REPEAT: - return SamplerFlags::WRAP_MIRROR; - default: - throw std::runtime_error("Invalid wrap type."); + case gt::Wrap::REPEAT: + return SamplerFlags::WRAP_REPEAT; + case gt::Wrap::CLAMP_TO_EDGE: + return SamplerFlags::WRAP_CLAMP; + case gt::Wrap::MIRRORED_REPEAT: + return SamplerFlags::WRAP_MIRROR; + default: + throw std::runtime_error("Invalid wrap type."); } } SamplerFlags::Type ConvertSampler(const gt::Ref& s) { - if (s) + if(s) { - return (s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) : - ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2) | - ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) | - (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) | - (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT); + return (s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) : ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2) | ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) | (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) | (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT); } else { @@ -424,13 +409,13 @@ SamplerFlags::Type ConvertSampler(const gt::Ref& s) // "What is an auto filtering", I hear you ask. Since there's nothing else to determine mipmapping from - including glTF image // properties, if not in some extension -, we will simply assume linear filtering. return SamplerFlags::FILTER_LINEAR | (SamplerFlags::FILTER_LINEAR << SamplerFlags::FILTER_MAG_SHIFT) | - (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT); + (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT); } } TextureDefinition ConvertTextureInfo(const gt::TextureInfo& mm) { - return TextureDefinition{ std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler) }; + return TextureDefinition{std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler)}; } void ConvertMaterial(const gt::Material& m, decltype(ResourceBundle::mMaterials)& outMaterials) @@ -438,12 +423,12 @@ void ConvertMaterial(const gt::Material& m, decltype(ResourceBundle::mMaterials) MaterialDefinition matDef; auto& pbr = m.mPbrMetallicRoughness; - if (m.mAlphaMode != gt::AlphaMode::OPAQUE || pbr.mBaseColorFactor.a < 1.f) + if(m.mAlphaMode != gt::AlphaMode::OPAQUE || pbr.mBaseColorFactor.a < 1.f) { matDef.mFlags |= MaterialDefinition::TRANSPARENCY; } - if (m.mAlphaMode == gt::AlphaMode::MASK) + if(m.mAlphaMode == gt::AlphaMode::MASK) { matDef.SetAlphaCutoff(std::min(1.f, std::max(0.f, m.mAlphaCutoff))); } @@ -451,30 +436,30 @@ void ConvertMaterial(const gt::Material& m, decltype(ResourceBundle::mMaterials) matDef.mColor = pbr.mBaseColorFactor; matDef.mTextureStages.reserve(!!pbr.mBaseColorTexture + !!pbr.mMetallicRoughnessTexture + !!m.mNormalTexture); - if (pbr.mBaseColorTexture) + if(pbr.mBaseColorTexture) { const auto semantic = MaterialDefinition::ALBEDO; - matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(pbr.mBaseColorTexture) }); + matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mBaseColorTexture)}); // TODO: and there had better be one matDef.mFlags |= semantic; } - matDef.mMetallic = pbr.mMetallicFactor; + matDef.mMetallic = pbr.mMetallicFactor; matDef.mRoughness = pbr.mRoughnessFactor; - if (pbr.mMetallicRoughnessTexture) + if(pbr.mMetallicRoughnessTexture) { const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS | - MaterialDefinition::GLTF_CHANNELS; - matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture) }); + MaterialDefinition::GLTF_CHANNELS; + matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture)}); // TODO: and there had better be one matDef.mFlags |= semantic; } - if (m.mNormalTexture) + if(m.mNormalTexture) { const auto semantic = MaterialDefinition::NORMAL; - matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(m.mNormalTexture) }); + matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(m.mNormalTexture)}); // TODO: and there had better be one matDef.mFlags |= semantic; } @@ -489,7 +474,7 @@ void ConvertMaterials(const gt::Document& doc, ConversionContext& cctx) auto& outMaterials = cctx.mOutput.mResources.mMaterials; outMaterials.reserve(doc.mMaterials.size()); - for (auto& m : doc.mMaterials) + for(auto& m : doc.mMaterials) { ConvertMaterial(m, outMaterials); } @@ -498,42 +483,41 @@ void ConvertMaterials(const gt::Document& doc, ConversionContext& cctx) MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gt::Accessor& acc) { DALI_ASSERT_ALWAYS((acc.mBufferView && - (acc.mBufferView->mByteStride < std::numeric_limits::max())) || - (acc.mSparse && !acc.mBufferView)); + (acc.mBufferView->mByteStride < std::numeric_limits::max())) || + (acc.mSparse && !acc.mBufferView)); DALI_ASSERT_ALWAYS(!acc.mSparse || - ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits::max())) && - (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits::max())))); - + ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits::max())) && + (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits::max())))); MeshDefinition::SparseBlob sparseBlob; - if (acc.mSparse) + if(acc.mSparse) { - const gt::Accessor::Sparse& sparse = *acc.mSparse; + const gt::Accessor::Sparse& sparse = *acc.mSparse; const gt::ComponentTypedBufferViewClient& indices = sparse.mIndices; - const gt::BufferViewClient& values = sparse.mValues; + const gt::BufferViewClient& values = sparse.mValues; MeshDefinition::Blob indicesBlob( indices.mBufferView->mByteOffset + indices.mByteOffset, sparse.mCount * indices.GetBytesPerComponent(), static_cast(indices.mBufferView->mByteStride), static_cast(indices.GetBytesPerComponent()), - {}, {} - ); + {}, + {}); MeshDefinition::Blob valuesBlob( values.mBufferView->mByteOffset + values.mByteOffset, sparse.mCount * acc.GetElementSizeBytes(), static_cast(values.mBufferView->mByteStride), static_cast(acc.GetElementSizeBytes()), - {}, {} - ); + {}, + {}); sparseBlob = std::move(MeshDefinition::SparseBlob(std::move(indicesBlob), std::move(valuesBlob), acc.mSparse->mCount)); } uint32_t bufferViewOffset = 0u; uint32_t bufferViewStride = 0u; - if (acc.mBufferView) + if(acc.mBufferView) { bufferViewOffset = acc.mBufferView->mByteOffset; bufferViewStride = acc.mBufferView->mByteStride; @@ -541,19 +525,19 @@ MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gt::Accessor& acc) return MeshDefinition::Accessor{ std::move(MeshDefinition::Blob{bufferViewOffset + acc.mByteOffset, - acc.GetBytesLength(), - static_cast(bufferViewStride), - static_cast(acc.GetElementSizeBytes()), - acc.mMin, - acc.mMax}), - std::move(sparseBlob) }; + acc.GetBytesLength(), + static_cast(bufferViewStride), + static_cast(acc.GetElementSizeBytes()), + acc.mMin, + acc.mMax}), + std::move(sparseBlob)}; } void ConvertMeshes(const gt::Document& doc, ConversionContext& cctx) { uint32_t meshCount = 0; cctx.mMeshIds.reserve(doc.mMeshes.size()); - for (auto& m : doc.mMeshes) + for(auto& m : doc.mMeshes) { cctx.mMeshIds.push_back(meshCount); meshCount += m.mPrimitives.size(); @@ -561,94 +545,94 @@ void ConvertMeshes(const gt::Document& doc, ConversionContext& cctx) auto& outMeshes = cctx.mOutput.mResources.mMeshes; outMeshes.reserve(meshCount); - for (auto& m : doc.mMeshes) + for(auto& m : doc.mMeshes) { - for (auto& p : m.mPrimitives) + for(auto& p : m.mPrimitives) { MeshDefinition meshDef; - auto& attribs = p.mAttributes; - meshDef.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri; + auto& attribs = p.mAttributes; + meshDef.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri; meshDef.mPrimitiveType = GLTF2_TO_DALI_PRIMITIVES[p.mMode]; auto& accPositions = *attribs.find(gt::Attribute::POSITION)->second; meshDef.mPositions = ConvertMeshPrimitiveAccessor(accPositions); const bool needNormalsTangents = accPositions.mType == gt::AccessorType::VEC3; - for (auto& am : ATTRIBUTE_MAPPINGS) + for(auto& am : ATTRIBUTE_MAPPINGS) { auto iFind = attribs.find(am.mType); - if (iFind != attribs.end()) + if(iFind != attribs.end()) { DALI_ASSERT_DEBUG(iFind->second->mBufferView->mBuffer->mUri.compare(meshDef.mUri) == 0); auto& accessor = meshDef.*(am.mAccessor); - accessor = ConvertMeshPrimitiveAccessor(*iFind->second); + accessor = ConvertMeshPrimitiveAccessor(*iFind->second); // Fixing up -- a few of glTF2 sample models have VEC4 tangents; we need VEC3s. - if (iFind->first == gt::Attribute::TANGENT && (accessor.mBlob.mElementSizeHint > am.mElementSizeRequired)) + if(iFind->first == gt::Attribute::TANGENT && (accessor.mBlob.mElementSizeHint > am.mElementSizeRequired)) { - accessor.mBlob.mStride = std::max(static_cast(accessor.mBlob.mStride + accessor.mBlob.mElementSizeHint - am.mElementSizeRequired), - accessor.mBlob.mElementSizeHint); + accessor.mBlob.mStride = std::max(static_cast(accessor.mBlob.mStride + accessor.mBlob.mElementSizeHint - am.mElementSizeRequired), + accessor.mBlob.mElementSizeHint); accessor.mBlob.mElementSizeHint = am.mElementSizeRequired; } - if (iFind->first == gt::Attribute::JOINTS_0) + if(iFind->first == gt::Attribute::JOINTS_0) { meshDef.mFlags |= (iFind->second->mComponentType == gt::Component::UNSIGNED_SHORT) * MeshDefinition::U16_JOINT_IDS; DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U16_JOINT_IDS) || iFind->second->mComponentType == gt::Component::FLOAT); } } - else if (needNormalsTangents) + else if(needNormalsTangents) { - switch (am.mType) + switch(am.mType) { - case gt::Attribute::NORMAL: - meshDef.RequestNormals(); - break; + case gt::Attribute::NORMAL: + meshDef.RequestNormals(); + break; - case gt::Attribute::TANGENT: - meshDef.RequestTangents(); - break; + case gt::Attribute::TANGENT: + meshDef.RequestTangents(); + break; - default: - break; + default: + break; } } } - if (p.mIndices) + if(p.mIndices) { meshDef.mIndices = ConvertMeshPrimitiveAccessor(*p.mIndices); meshDef.mFlags |= (p.mIndices->mComponentType == gt::Component::UNSIGNED_INT) * MeshDefinition::U32_INDICES; DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U32_INDICES) || p.mIndices->mComponentType == gt::Component::UNSIGNED_SHORT); } - if (!p.mTargets.empty()) + if(!p.mTargets.empty()) { meshDef.mBlendShapes.reserve(p.mTargets.size()); meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0; - for (const auto& target : p.mTargets) + for(const auto& target : p.mTargets) { MeshDefinition::BlendShape blendShape; auto endIt = target.end(); - auto it = target.find(gt::Attribute::POSITION); - if (it != endIt) + auto it = target.find(gt::Attribute::POSITION); + if(it != endIt) { blendShape.deltas = ConvertMeshPrimitiveAccessor(*it->second); } it = target.find(gt::Attribute::NORMAL); - if (it != endIt) + if(it != endIt) { blendShape.normals = ConvertMeshPrimitiveAccessor(*it->second); } it = target.find(gt::Attribute::TANGENT); - if (it != endIt) + if(it != endIt) { blendShape.tangents = ConvertMeshPrimitiveAccessor(*it->second); } - if (!m.mWeights.empty()) + if(!m.mWeights.empty()) { blendShape.weight = m.mWeights[meshDef.mBlendShapes.size()]; } @@ -657,7 +641,7 @@ void ConvertMeshes(const gt::Document& doc, ConversionContext& cctx) } } - outMeshes.push_back({ std::move(meshDef), MeshGeometry{} }); + outMeshes.push_back({std::move(meshDef), MeshGeometry{}}); } } } @@ -666,15 +650,15 @@ ModelNode* MakeModelNode(const gt::Mesh::Primitive& prim, ConversionContext& cct { auto modelNode = new ModelNode(); - modelNode->mShaderIdx = 0; // TODO: further thought + modelNode->mShaderIdx = 0; // TODO: further thought auto materialIdx = prim.mMaterial.GetIndex(); - if (INVALID_INDEX == materialIdx) + if(INVALID_INDEX == materialIdx) { // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#default-material - if (INVALID_INDEX == cctx.mDefaultMaterial) + if(INVALID_INDEX == cctx.mDefaultMaterial) { - auto& outMaterials = cctx.mOutput.mResources.mMaterials; + auto& outMaterials = cctx.mOutput.mResources.mMaterials; cctx.mDefaultMaterial = outMaterials.size(); ConvertMaterial(gt::Material{}, outMaterials); @@ -691,51 +675,51 @@ ModelNode* MakeModelNode(const gt::Mesh::Primitive& prim, ConversionContext& cct void ConvertCamera(const gt::Camera& camera, CameraParameters& camParams) { camParams.isPerspective = camera.mType.compare("perspective") == 0; - if (camParams.isPerspective) + if(camParams.isPerspective) { auto& perspective = camera.mPerspective; - camParams.yFov = Degree(Radian(perspective.mYFov)).degree; - camParams.zNear = perspective.mZNear; - camParams.zFar = perspective.mZFar; + camParams.yFov = Degree(Radian(perspective.mYFov)).degree; + camParams.zNear = perspective.mZNear; + camParams.zFar = perspective.mZFar; // TODO: yes, we seem to ignore aspectRatio in CameraParameters. } else { - auto& ortho = camera.mOrthographic; + auto& ortho = camera.mOrthographic; camParams.orthographicSize = Vector4(-ortho.mXMag, ortho.mXMag, ortho.mYMag, -ortho.mYMag) * .5f; - camParams.zNear = ortho.mZNear; - camParams.zFar = ortho.mZFar; + camParams.zNear = ortho.mZNear; + camParams.zFar = ortho.mZFar; } } void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, ConversionContext& cctx) { - auto& output = cctx.mOutput; - auto& scene = output.mScene; + auto& output = cctx.mOutput; + auto& scene = output.mScene; auto& resources = output.mResources; - const auto idx = scene.GetNodeCount(); - auto weakNode = scene.AddNode([&]() { - std::unique_ptr nodeDef{ new NodeDefinition() }; + const auto idx = scene.GetNodeCount(); + auto weakNode = scene.AddNode([&]() { + std::unique_ptr nodeDef{new NodeDefinition()}; nodeDef->mParentIdx = parentIdx; - nodeDef->mName = node.mName; - if (nodeDef->mName.empty()) + nodeDef->mName = node.mName; + if(nodeDef->mName.empty()) { // TODO: Production quality generation of unique names. nodeDef->mName = std::to_string(reinterpret_cast(nodeDef.get())); } - if (!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms. + if(!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms. { - nodeDef->mPosition = node.mTranslation; + nodeDef->mPosition = node.mTranslation; nodeDef->mOrientation = node.mRotation; - nodeDef->mScale = node.mScale; + nodeDef->mScale = node.mScale; } return nodeDef; }()); - if (!weakNode) + if(!weakNode) { ExceptionFlinger(ASSERT_LOCATION) << "Node name '" << node.mName << "' is not unique; scene is invalid."; } @@ -743,25 +727,25 @@ void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, Con cctx.mNodeIndices.RegisterMapping(gltfIdx, idx); Index skeletonIdx = node.mSkin ? node.mSkin.GetIndex() : INVALID_INDEX; - if (node.mMesh && !node.mMesh->mPrimitives.empty()) + if(node.mMesh && !node.mMesh->mPrimitives.empty()) { auto& mesh = *node.mMesh; - auto iPrim = mesh.mPrimitives.begin(); - auto modelNode = MakeModelNode(*iPrim, cctx); - auto meshIdx = cctx.mMeshIds[node.mMesh.GetIndex()]; + auto iPrim = mesh.mPrimitives.begin(); + auto modelNode = MakeModelNode(*iPrim, cctx); + auto meshIdx = cctx.mMeshIds[node.mMesh.GetIndex()]; modelNode->mMeshIdx = meshIdx; weakNode->mRenderable.reset(modelNode); DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX || - resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx); + resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx); resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx; // As does model-exporter, we'll create anonymous child nodes for additional mesh( primitiv)es. - while (++iPrim != mesh.mPrimitives.end()) + while(++iPrim != mesh.mPrimitives.end()) { - std::unique_ptr child{ new NodeDefinition }; + std::unique_ptr child{new NodeDefinition}; child->mParentIdx = idx; auto childModel = MakeModelNode(*iPrim, cctx); @@ -774,12 +758,12 @@ void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, Con scene.AddNode(std::move(child)); DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX || - resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx); + resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx); resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx; } } - if (node.mCamera) + if(node.mCamera) { CameraParameters camParams; ConvertCamera(*node.mCamera, camParams); @@ -788,7 +772,7 @@ void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, Con output.mCameraParameters.push_back(camParams); } - for (auto& n : node.mChildren) + for(auto& n : node.mChildren) { ConvertNode(*n, n.GetIndex(), idx, cctx); } @@ -797,26 +781,26 @@ void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, Con void ConvertSceneNodes(const gt::Scene& scene, ConversionContext& cctx) { auto& outScene = cctx.mOutput.mScene; - Index rootIdx = outScene.GetNodeCount(); - switch (scene.mNodes.size()) + Index rootIdx = outScene.GetNodeCount(); + switch(scene.mNodes.size()) { - case 0: - break; + case 0: + break; - case 1: - ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, cctx); - outScene.AddRootNode(rootIdx); - break; + case 1: + ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, cctx); + outScene.AddRootNode(rootIdx); + break; - default: + default: { - std::unique_ptr sceneRoot{ new NodeDefinition() }; + std::unique_ptr sceneRoot{new NodeDefinition()}; sceneRoot->mName = "GLTF_LOADER_SCENE_ROOT_" + std::to_string(outScene.GetRoots().size()); outScene.AddNode(std::move(sceneRoot)); outScene.AddRootNode(rootIdx); - for (auto& n : scene.mNodes) + for(auto& n : scene.mNodes) { ConvertNode(*n, n.GetIndex(), rootIdx, cctx); } @@ -829,23 +813,23 @@ void ConvertNodes(const gt::Document& doc, ConversionContext& cctx) { ConvertSceneNodes(*doc.mScene, cctx); - for (uint32_t i = 0, i1 = doc.mScene.GetIndex(); i < i1; ++i) + for(uint32_t i = 0, i1 = doc.mScene.GetIndex(); i < i1; ++i) { ConvertSceneNodes(doc.mScenes[i], cctx); } - for (uint32_t i = doc.mScene.GetIndex() + 1; i < doc.mScenes.size(); ++i) + for(uint32_t i = doc.mScene.GetIndex() + 1; i < doc.mScenes.size(); ++i) { ConvertSceneNodes(doc.mScenes[i], cctx); } } -template +template void LoadDataFromAccessor(const std::string& path, Vector& dataBuffer, uint32_t offset, uint32_t size) { std::ifstream animationBinaryFile(path, std::ifstream::binary); - if (!animationBinaryFile.is_open()) + if(!animationBinaryFile.is_open()) { throw std::runtime_error("Failed to load " + path); } @@ -855,19 +839,17 @@ void LoadDataFromAccessor(const std::string& path, Vector& dataBuffer, uint32 animationBinaryFile.close(); } -template +template float LoadDataFromAccessors(const std::string& path, const gltf2::Accessor& input, const gltf2::Accessor& output, Vector& inputDataBuffer, Vector& outputDataBuffer) { inputDataBuffer.Resize(input.mCount); outputDataBuffer.Resize(output.mCount); - const uint32_t inputDataBufferSize = input.GetBytesLength(); + const uint32_t inputDataBufferSize = input.GetBytesLength(); const uint32_t outputDataBufferSize = output.GetBytesLength(); - LoadDataFromAccessor(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer, - input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize); - LoadDataFromAccessor(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer, - output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize); + LoadDataFromAccessor(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer, input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize); + LoadDataFromAccessor(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer, output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize); ApplyAccessorMinMax(output, reinterpret_cast(outputDataBuffer.begin())); return inputDataBuffer[input.mCount - 1u]; @@ -876,15 +858,15 @@ float LoadDataFromAccessors(const std::string& path, const gltf2::Accessor& inpu template float LoadKeyFrames(const std::string& path, const gt::Animation::Channel& channel, KeyFrames& keyFrames, gt::Animation::Channel::Target::Type type) { - const gltf2::Accessor& input = *channel.mSampler->mInput; + const gltf2::Accessor& input = *channel.mSampler->mInput; const gltf2::Accessor& output = *channel.mSampler->mOutput; Vector inputDataBuffer; - Vector outputDataBuffer; + Vector outputDataBuffer; const float duration = LoadDataFromAccessors(path, input, output, inputDataBuffer, outputDataBuffer); - for (uint32_t i = 0; i < input.mCount; ++i) + for(uint32_t i = 0; i < input.mCount; ++i) { keyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i]); } @@ -894,7 +876,7 @@ float LoadKeyFrames(const std::string& path, const gt::Animation::Channel& chann float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Channel& channel, const std::string& nodeName, uint32_t& propertyIndex, std::vector& properties) { - const gltf2::Accessor& input = *channel.mSampler->mInput; + const gltf2::Accessor& input = *channel.mSampler->mInput; const gltf2::Accessor& output = *channel.mSampler->mOutput; Vector inputDataBuffer; @@ -902,11 +884,11 @@ float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Chan const float duration = LoadDataFromAccessors(path, input, output, inputDataBuffer, outputDataBuffer); - char weightNameBuffer[32]; - auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str()); - char* const pWeightName = weightNameBuffer + prefixSize; - const auto remainingSize = sizeof(weightNameBuffer) - prefixSize; - for (uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex) + char weightNameBuffer[32]; + auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str()); + char* const pWeightName = weightNameBuffer + prefixSize; + const auto remainingSize = sizeof(weightNameBuffer) - prefixSize; + for(uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex) { AnimatedProperty& animatedProperty = properties[propertyIndex++]; @@ -915,12 +897,12 @@ float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Chan animatedProperty.mPropertyName = std::string(weightNameBuffer); animatedProperty.mKeyFrames = KeyFrames::New(); - for (uint32_t i = 0; i < input.mCount; ++i) + for(uint32_t i = 0; i < input.mCount; ++i) { - animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i*endWeightIndex + weightIndex]); + animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i * endWeightIndex + weightIndex]); } - animatedProperty.mTimePeriod = { 0.f, duration }; + animatedProperty.mTimePeriod = {0.f, duration}; } return duration; @@ -932,78 +914,78 @@ void ConvertAnimations(const gt::Document& doc, ConversionContext& cctx) output.mAnimationDefinitions.reserve(output.mAnimationDefinitions.size() + doc.mAnimations.size()); - for (const auto& animation : doc.mAnimations) + for(const auto& animation : doc.mAnimations) { AnimationDefinition animationDef; - if (!animation.mName.empty()) + if(!animation.mName.empty()) { animationDef.mName = animation.mName; } uint32_t numberOfProperties = 0u; - for (const auto& channel : animation.mChannels) + for(const auto& channel : animation.mChannels) { numberOfProperties += channel.mSampler->mOutput->mCount; } animationDef.mProperties.resize(numberOfProperties); Index propertyIndex = 0u; - for (const auto& channel : animation.mChannels) + for(const auto& channel : animation.mChannels) { std::string nodeName; - if (!channel.mTarget.mNode->mName.empty()) + if(!channel.mTarget.mNode->mName.empty()) { nodeName = channel.mTarget.mNode->mName; } else { Index index = cctx.mNodeIndices.GetRuntimeId(channel.mTarget.mNode.GetIndex()); - nodeName = cctx.mOutput.mScene.GetNode(index)->mName; + nodeName = cctx.mOutput.mScene.GetNode(index)->mName; } float duration = 0.f; - switch (channel.mTarget.mPath) + switch(channel.mTarget.mPath) { case gt::Animation::Channel::Target::TRANSLATION: { AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex]; - animatedProperty.mNodeName = nodeName; + animatedProperty.mNodeName = nodeName; animatedProperty.mPropertyName = POSITION_PROPERTY; animatedProperty.mKeyFrames = KeyFrames::New(); - duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); + duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); - animatedProperty.mTimePeriod = { 0.f, duration }; + animatedProperty.mTimePeriod = {0.f, duration}; break; } case gt::Animation::Channel::Target::ROTATION: { AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex]; - animatedProperty.mNodeName = nodeName; + animatedProperty.mNodeName = nodeName; animatedProperty.mPropertyName = ORIENTATION_PROPERTY; animatedProperty.mKeyFrames = KeyFrames::New(); - duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); + duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); - animatedProperty.mTimePeriod = { 0.f, duration }; + animatedProperty.mTimePeriod = {0.f, duration}; break; } case gt::Animation::Channel::Target::SCALE: { AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex]; - animatedProperty.mNodeName = nodeName; + animatedProperty.mNodeName = nodeName; animatedProperty.mPropertyName = SCALE_PROPERTY; animatedProperty.mKeyFrames = KeyFrames::New(); - duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); + duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); - animatedProperty.mTimePeriod = { 0.f, duration }; + animatedProperty.mTimePeriod = {0.f, duration}; break; } case gt::Animation::Channel::Target::WEIGHTS: @@ -1035,13 +1017,15 @@ void ProcessSkins(const gt::Document& doc, ConversionContext& cctx) // otherwise we'll set identity matrices for inverse bind pose. struct IInverseBindMatrixProvider { - virtual ~IInverseBindMatrixProvider() {} + virtual ~IInverseBindMatrixProvider() + { + } virtual void Provide(Matrix& ibm) = 0; }; struct InverseBindMatrixAccessor : public IInverseBindMatrixProvider { - std::ifstream mStream; + std::ifstream mStream; const uint32_t mElementSizeBytes; InverseBindMatrixAccessor(const gt::Accessor& accessor, const std::string& path) @@ -1071,10 +1055,10 @@ void ProcessSkins(const gt::Document& doc, ConversionContext& cctx) auto& resources = cctx.mOutput.mResources; resources.mSkeletons.reserve(doc.mSkins.size()); - for (auto& s : doc.mSkins) + for(auto& s : doc.mSkins) { std::unique_ptr ibmProvider; - if (s.mInverseBindMatrices) + if(s.mInverseBindMatrices) { ibmProvider.reset(new InverseBindMatrixAccessor(*s.mInverseBindMatrices, cctx.mPath)); } @@ -1084,14 +1068,14 @@ void ProcessSkins(const gt::Document& doc, ConversionContext& cctx) } SkeletonDefinition skeleton; - if (s.mSkeleton.GetIndex() != INVALID_INDEX) + if(s.mSkeleton.GetIndex() != INVALID_INDEX) { skeleton.mRootNodeIdx = cctx.mNodeIndices.GetRuntimeId(s.mSkeleton.GetIndex()); } skeleton.mJoints.resize(s.mJoints.size()); auto iJoint = skeleton.mJoints.begin(); - for (auto& j : s.mJoints) + for(auto& j : s.mJoints) { iJoint->mNodeIdx = cctx.mNodeIndices.GetRuntimeId(j.GetIndex()); @@ -1106,10 +1090,10 @@ void ProcessSkins(const gt::Document& doc, ConversionContext& cctx) void ProduceShaders(ShaderDefinitionFactory& shaderFactory, SceneDefinition& scene) { - for (size_t i0 = 0, i1 = scene.GetNodeCount(); i0 != i1; ++i0) + for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 != i1; ++i0) { auto nodeDef = scene.GetNode(i0); - if (auto renderable = nodeDef->mRenderable.get()) + if(auto renderable = nodeDef->mRenderable.get()) { renderable->mShaderIdx = shaderFactory.ProduceShader(*nodeDef); } @@ -1144,25 +1128,25 @@ void SetObjectReaders() js::SetObjectReader(SCENE_READER); } -} // nonamespace +} // namespace void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactory, LoadResult& params) { bool failed = false; - auto js = LoadTextFile(url.c_str(), &failed); - if (failed) + auto js = LoadTextFile(url.c_str(), &failed); + if(failed) { throw std::runtime_error("Failed to load " + url); } json::unique_ptr root(json_parse(js.c_str(), js.size())); - if (!root) + if(!root) { throw std::runtime_error("Failed to parse " + url); } static bool setObjectReaders = true; - if (setObjectReaders) + if(setObjectReaders) { // NOTE: only referencing own, anonymous namespace, const objects; the pointers will never need to change. SetObjectReaders(); @@ -1171,16 +1155,16 @@ void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactor gt::Document doc; - auto& rootObj = js::Cast(*root); - auto jsAsset = js::FindObjectChild("asset", rootObj); - auto jsAssetVersion = js::FindObjectChild("version", js::Cast(*jsAsset)); - doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion); + auto& rootObj = js::Cast(*root); + auto jsAsset = js::FindObjectChild("asset", rootObj); + auto jsAssetVersion = js::FindObjectChild("version", js::Cast(*jsAsset)); + doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion); gt::SetRefReaderObject(doc); DOCUMENT_READER.Read(rootObj, doc); - auto path = url.substr(0, url.rfind('/') + 1); - ConversionContext cctx{ params, path, INVALID_INDEX }; + auto path = url.substr(0, url.rfind('/') + 1); + ConversionContext cctx{params, path, INVALID_INDEX}; ConvertMaterials(doc, cctx); ConvertMeshes(doc, cctx); @@ -1193,5 +1177,5 @@ void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactor params.mScene.EnsureUniqueSkinningShaderInstances(params.mResources); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/gltf2-loader.h b/dali-scene-loader/public-api/gltf2-loader.h index ce3ec79..9871ec0 100644 --- a/dali-scene-loader/public-api/gltf2-loader.h +++ b/dali-scene-loader/public-api/gltf2-loader.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_GLTF2_LOADER_H #define DALI_SCENE_LOADER_GLTF2_LOADER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * */ - // INTERNAL INCLUDES +// INTERNAL INCLUDES #include "dali-scene-loader/public-api/api.h" // EXTERNAL INCLUDES @@ -38,7 +38,7 @@ class ShaderDefinitionFactory; */ DALI_SCENE_LOADER_API void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactory, LoadResult& params); -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_GLTF2_LOADER_H diff --git a/dali-scene-loader/public-api/index.h b/dali-scene-loader/public-api/index.h index 278f19a..9ad5fc2 100644 --- a/dali-scene-loader/public-api/index.h +++ b/dali-scene-loader/public-api/index.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_INDEX_H_ #define DALI_SCENE_LOADER_INDEX_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,12 +27,11 @@ namespace Dali { namespace SceneLoader { - using Index = uint32_t; constexpr Index INVALID_INDEX = static_cast(-1); -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_INDEX_H_ diff --git a/dali-scene-loader/public-api/ktx-loader.cpp b/dali-scene-loader/public-api/ktx-loader.cpp index 839c03c..147b3fd 100644 --- a/dali-scene-loader/public-api/ktx-loader.cpp +++ b/dali-scene-loader/public-api/ktx-loader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,26 +15,24 @@ * */ - // FILE HEADER +// FILE HEADER #include "dali-scene-loader/public-api/ktx-loader.h" - // EXTERNAL INCLUDES -#include "dali/public-api/rendering/texture.h" +// EXTERNAL INCLUDES #include #include +#include "dali/public-api/rendering/texture.h" namespace Dali { - namespace { - // http://github.khronos.org/KTX-Specification/ -const uint8_t KTX_ID_HEAD[] = { 0xAB, 0x4B, 0x54, 0x58, 0x20 }; -const uint8_t KTX_ID_TAIL[] = { 0xBB, 0x0D, 0x0A, 0x1A, 0x0A }; +const uint8_t KTX_ID_HEAD[] = {0xAB, 0x4B, 0x54, 0x58, 0x20}; +const uint8_t KTX_ID_TAIL[] = {0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; -const uint8_t KTX_VERSION_1_1[] = { 0x31, 0x31 }; -const uint8_t KTX_VERSION_2_0[] = { 0x32, 0x30 }; +const uint8_t KTX_VERSION_1_1[] = {0x31, 0x31}; +const uint8_t KTX_VERSION_2_0[] = {0x32, 0x30}; static_assert(sizeof(KTX_ID_HEAD) + sizeof(KTX_ID_TAIL) == 10); static_assert(sizeof(KTX_VERSION_1_1) == 2); @@ -50,27 +48,27 @@ namespace SceneLoader { struct KtxFileHeader { - uint8_t identifier[12]; - uint32_t endianness; - uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.) - uint32_t glTypeSize; - uint32_t glFormat; //(RGB, RGBA, BGRA, etc.) - uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D - uint32_t glBaseInternalFormat; - uint32_t pixelWidth; - uint32_t pixelHeight; - uint32_t pixelDepth; - uint32_t numberOfArrayElements; - uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z. - uint32_t numberOfMipmapLevels; - uint32_t bytesOfKeyValueData; + uint8_t identifier[12]; + uint32_t endianness; + uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.) + uint32_t glTypeSize; + uint32_t glFormat; //(RGB, RGBA, BGRA, etc.) + uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D + uint32_t glBaseInternalFormat; + uint32_t pixelWidth; + uint32_t pixelHeight; + uint32_t pixelDepth; + uint32_t numberOfArrayElements; + uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z. + uint32_t numberOfMipmapLevels; + uint32_t bytesOfKeyValueData; bool IsIdentifierValid() const { return std::equal(KTX_ID_HEAD, std::end(KTX_ID_HEAD), identifier) && - (std::equal(KTX_VERSION_1_1, std::end(KTX_VERSION_1_1), identifier + sizeof(KTX_ID_HEAD)) || - std::equal(KTX_VERSION_2_0, std::end(KTX_VERSION_2_0), identifier + sizeof(KTX_ID_HEAD))) && - std::equal(KTX_ID_TAIL, std::end(KTX_ID_TAIL), identifier + (sizeof(KTX_ID_HEAD) + sizeof(KTX_VERSION_1_1))); + (std::equal(KTX_VERSION_1_1, std::end(KTX_VERSION_1_1), identifier + sizeof(KTX_ID_HEAD)) || + std::equal(KTX_VERSION_2_0, std::end(KTX_VERSION_2_0), identifier + sizeof(KTX_ID_HEAD))) && + std::equal(KTX_ID_TAIL, std::end(KTX_ID_TAIL), identifier + (sizeof(KTX_ID_HEAD) + sizeof(KTX_VERSION_1_1))); } }; @@ -79,107 +77,107 @@ struct KtxFileHeader */ bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Pixel::Format& format) { - switch (ktxPixelFormat) - { - case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4 - { - format = Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR; - break; - } - case 0x93B1: // GL_COMPRESSED_RGBA_ASTC_5x4 - { - format = Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR; - break; - } - case 0x93B2: // GL_COMPRESSED_RGBA_ASTC_5x5 - { - format = Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR; - break; - } - case 0x93B3: // GL_COMPRESSED_RGBA_ASTC_6x5 - { - format = Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR; - break; - } - case 0x93B4: // GL_COMPRESSED_RGBA_ASTC_6x6 - { - format = Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR; - break; - } - case 0x93B5: // GL_COMPRESSED_RGBA_ASTC_8x5 - { - format = Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR; - break; - } - case 0x93B6: // GL_COMPRESSED_RGBA_ASTC_8x6 - { - format = Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR; - break; - } - case 0x93B7: // GL_COMPRESSED_RGBA_ASTC_8x8 - { - format = Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR; - break; - } - case 0x93B8: // GL_COMPRESSED_RGBA_ASTC_10x5 - { - format = Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR; - break; - } - case 0x93B9: // GL_COMPRESSED_RGBA_ASTC_10x6 - { - format = Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR; - break; - } - case 0x93BA: // GL_COMPRESSED_RGBA_ASTC_10x8 - { - format = Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR; - break; - } - case 0x93BB: // GL_COMPRESSED_RGBA_ASTC_10x10 - { - format = Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR; - break; - } - case 0x93BC: // GL_COMPRESSED_RGBA_ASTC_12x10 - { - format = Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR; - break; - } - case 0x93BD: // GL_COMPRESSED_RGBA_ASTC_12x12 - { - format = Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR; - break; - } - case 0x881B: // GL_RGB16F + switch(ktxPixelFormat) { - format = Pixel::RGB16F; - break; - } - case 0x8815: // GL_RGB32F - { - format = Pixel::RGB32F; - break; - } - case 0x8C3A: // GL_R11F_G11F_B10F - { - format = Pixel::RGB32F; - break; - } - case 0x8D7C: // GL_RGBA8UI - { - format = Pixel::RGBA8888; - break; - } - case 0x8D7D: // GL_RGB8UI - { - format = Pixel::RGB888; - break; - } - default: - { - return false; - } + case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4 + { + format = Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR; + break; + } + case 0x93B1: // GL_COMPRESSED_RGBA_ASTC_5x4 + { + format = Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR; + break; + } + case 0x93B2: // GL_COMPRESSED_RGBA_ASTC_5x5 + { + format = Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR; + break; + } + case 0x93B3: // GL_COMPRESSED_RGBA_ASTC_6x5 + { + format = Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR; + break; + } + case 0x93B4: // GL_COMPRESSED_RGBA_ASTC_6x6 + { + format = Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR; + break; + } + case 0x93B5: // GL_COMPRESSED_RGBA_ASTC_8x5 + { + format = Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR; + break; + } + case 0x93B6: // GL_COMPRESSED_RGBA_ASTC_8x6 + { + format = Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR; + break; + } + case 0x93B7: // GL_COMPRESSED_RGBA_ASTC_8x8 + { + format = Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR; + break; + } + case 0x93B8: // GL_COMPRESSED_RGBA_ASTC_10x5 + { + format = Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR; + break; + } + case 0x93B9: // GL_COMPRESSED_RGBA_ASTC_10x6 + { + format = Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR; + break; + } + case 0x93BA: // GL_COMPRESSED_RGBA_ASTC_10x8 + { + format = Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR; + break; + } + case 0x93BB: // GL_COMPRESSED_RGBA_ASTC_10x10 + { + format = Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR; + break; + } + case 0x93BC: // GL_COMPRESSED_RGBA_ASTC_12x10 + { + format = Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR; + break; + } + case 0x93BD: // GL_COMPRESSED_RGBA_ASTC_12x12 + { + format = Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR; + break; + } + case 0x881B: // GL_RGB16F + { + format = Pixel::RGB16F; + break; + } + case 0x8815: // GL_RGB32F + { + format = Pixel::RGB32F; + break; + } + case 0x8C3A: // GL_R11F_G11F_B10F + { + format = Pixel::RGB32F; + break; + } + case 0x8D7C: // GL_RGBA8UI + { + format = Pixel::RGBA8888; + break; + } + case 0x8D7D: // GL_RGB8UI + { + format = Pixel::RGB888; + break; + } + default: + { + return false; + } } return true; @@ -187,15 +185,13 @@ bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Pixel::Format& format) Texture CubeData::CreateTexture() const { - Texture texture = Texture::New(TextureType::TEXTURE_CUBE, data[0][0].GetPixelFormat(), - data[0][0].GetWidth(), data[0][0].GetHeight()); - for (size_t iSide = 0u, iEndSize = data.size(); iSide < iEndSize; ++iSide) + Texture texture = Texture::New(TextureType::TEXTURE_CUBE, data[0][0].GetPixelFormat(), data[0][0].GetWidth(), data[0][0].GetHeight()); + for(size_t iSide = 0u, iEndSize = data.size(); iSide < iEndSize; ++iSide) { auto& side = data[iSide]; - for (size_t iMipLevel = 0u, iEndMipLevel = data[0].size(); iMipLevel < iEndMipLevel; ++iMipLevel) + for(size_t iMipLevel = 0u, iEndMipLevel = data[0].size(); iMipLevel < iEndMipLevel; ++iMipLevel) { - texture.Upload(side[iMipLevel], CubeMapLayer::POSITIVE_X + iSide, iMipLevel, - 0u, 0u, side[iMipLevel].GetWidth(), side[iMipLevel].GetHeight()); + texture.Upload(side[iMipLevel], CubeMapLayer::POSITIVE_X + iSide, iMipLevel, 0u, 0u, side[iMipLevel].GetWidth(), side[iMipLevel].GetHeight()); } } @@ -205,35 +201,35 @@ Texture CubeData::CreateTexture() const bool LoadCubeMapData(const std::string& path, CubeData& cubedata) { std::fstream fp(path, std::ios::in | std::ios::binary); - if (fp.is_open() == false) + if(fp.is_open() == false) { return false; } KtxFileHeader header; - if (fp.read(reinterpret_cast(&header), sizeof(KtxFileHeader)).good() == false) + if(fp.read(reinterpret_cast(&header), sizeof(KtxFileHeader)).good() == false) { return false; } - if (!header.IsIdentifierValid()) + if(!header.IsIdentifierValid()) { return false; } // Skip the key-values: - if (fp.seekg(header.bytesOfKeyValueData, fp.cur).good() == false) + if(fp.seekg(header.bytesOfKeyValueData, fp.cur).good() == false) { return false; } - header.numberOfMipmapLevels = std::max(header.numberOfMipmapLevels, 1u); + header.numberOfMipmapLevels = std::max(header.numberOfMipmapLevels, 1u); header.numberOfArrayElements = std::max(header.numberOfArrayElements, 1u); - header.pixelDepth = std::max(header.pixelDepth, 1u); - header.pixelHeight = std::max(header.pixelHeight, 1u); + header.pixelDepth = std::max(header.pixelDepth, 1u); + header.pixelHeight = std::max(header.pixelHeight, 1u); cubedata.data.resize(header.numberOfFaces); - for (uint32_t face = 0u; face < header.numberOfFaces; ++face) + for(uint32_t face = 0u; face < header.numberOfFaces; ++face) { cubedata.data[face].resize(header.numberOfMipmapLevels); } @@ -242,25 +238,25 @@ bool LoadCubeMapData(const std::string& path, CubeData& cubedata) ConvertPixelFormat(header.glInternalFormat, daliformat); - for (uint32_t mipmapLevel = 0u; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel) + for(uint32_t mipmapLevel = 0u; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel) { uint32_t byteSize = 0u; - if (fp.read(reinterpret_cast(&byteSize), sizeof(byteSize)).good() == false) + if(fp.read(reinterpret_cast(&byteSize), sizeof(byteSize)).good() == false) { return false; } - if (0u != byteSize % 4u) + if(0u != byteSize % 4u) { byteSize += 4u - byteSize % 4u; } - for (uint32_t arrayElement = 0u; arrayElement < header.numberOfArrayElements; ++arrayElement) //arrayElement must be 0 or 1 + for(uint32_t arrayElement = 0u; arrayElement < header.numberOfArrayElements; ++arrayElement) //arrayElement must be 0 or 1 { - for (uint32_t face = 0u; face < header.numberOfFaces; ++face) + for(uint32_t face = 0u; face < header.numberOfFaces; ++face) { - std::unique_ptrimg(new uint8_t[byteSize], FreeBuffer); - if (fp.read(reinterpret_cast(img.get()), byteSize).good() == false) + std::unique_ptr img(new uint8_t[byteSize], FreeBuffer); + if(fp.read(reinterpret_cast(img.get()), byteSize).good() == false) { return false; } @@ -275,5 +271,5 @@ bool LoadCubeMapData(const std::string& path, CubeData& cubedata) return true; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/ktx-loader.h b/dali-scene-loader/public-api/ktx-loader.h index 6167fef..d94f4ca 100644 --- a/dali-scene-loader/public-api/ktx-loader.h +++ b/dali-scene-loader/public-api/ktx-loader.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_KTX_LOADER_H #define DALI_SCENE_LOADER_KTX_LOADER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,13 +29,12 @@ namespace Dali { namespace SceneLoader { - /** * @brief Stores the pixel data objects for each face of the cube texture and their mipmaps. */ struct DALI_SCENE_LOADER_API CubeData { - std::vector< std::vector > data; + std::vector > data; Texture CreateTexture() const; }; @@ -48,7 +47,7 @@ struct DALI_SCENE_LOADER_API CubeData */ DALI_SCENE_LOADER_API bool LoadCubeMapData(const std::string& path, CubeData& cubedata); -} -} +} // namespace SceneLoader +} // namespace Dali #endif // DALI_SCENE_LOADER_KTX_LOADER_H diff --git a/dali-scene-loader/public-api/light-parameters.h b/dali-scene-loader/public-api/light-parameters.h index 0d8d514..11b014b 100644 --- a/dali-scene-loader/public-api/light-parameters.h +++ b/dali-scene-loader/public-api/light-parameters.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_LIGHT_PARAMETERS_H #define DALI_SCENE_LOADER_LIGHT_PARAMETERS_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,27 +21,26 @@ #include "dali-scene-loader/public-api/api.h" // EXTERNAL INCLUDES +#include #include "dali/public-api/math/matrix.h" #include "dali/public-api/math/vector3.h" -#include namespace Dali { namespace SceneLoader { - struct DALI_SCENE_LOADER_API LightParameters { Matrix transform; - Vector3 color; - float intensity; - float shadowIntensity; + Vector3 color; + float intensity; + float shadowIntensity; uint32_t shadowMapSize; - float orthographicSize; + float orthographicSize; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif // DALI_SCENE_LOADER_LIGHT_PARAMETERS_H diff --git a/dali-scene-loader/public-api/load-result.h b/dali-scene-loader/public-api/load-result.h index ca05bfd..4ed3ff5 100644 --- a/dali-scene-loader/public-api/load-result.h +++ b/dali-scene-loader/public-api/load-result.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_OUTPUT_H #define DALI_SCENE_LOADER_OUTPUT_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,16 +18,15 @@ */ // INTERNAL INCLUDES -#include "dali-scene-loader/public-api/api.h" #include "dali-scene-loader/public-api/animation-definition.h" -#include "dali-scene-loader/public-api/light-parameters.h" +#include "dali-scene-loader/public-api/api.h" #include "dali-scene-loader/public-api/camera-parameters.h" +#include "dali-scene-loader/public-api/light-parameters.h" namespace Dali { namespace SceneLoader { - class ResourceBundle; class SceneDefinition; @@ -67,7 +66,7 @@ struct DALI_SCENE_LOADER_API LoadResult std::vector& mLightParameters; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_OUTPUT_H diff --git a/dali-scene-loader/public-api/material-definition.cpp b/dali-scene-loader/public-api/material-definition.cpp index 952a824..c0e816c 100644 --- a/dali-scene-loader/public-api/material-definition.cpp +++ b/dali-scene-loader/public-api/material-definition.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,6 @@ namespace SceneLoader { namespace { - constexpr SamplerFlags::Type FILTER_MODES_FROM_DALI[]{ SamplerFlags::FILTER_LINEAR | SamplerFlags::FILTER_MIPMAP_NEAREST, SamplerFlags::FILTER_LINEAR, @@ -48,7 +47,7 @@ constexpr SamplerFlags::Type WRAP_MODES_FROM_DALI[]{ SamplerFlags::WRAP_MIRROR, }; -constexpr FilterMode::Type FILTER_MODES_TO_DALI[]{ +constexpr FilterMode::Type FILTER_MODES_TO_DALI[]{ FilterMode::NEAREST, FilterMode::LINEAR, FilterMode::NEAREST_MIPMAP_NEAREST, @@ -60,16 +59,15 @@ constexpr FilterMode::Type FILTER_MODES_TO_DALI[]{ constexpr WrapMode::Type WRAP_MODES_TO_DALI[]{ WrapMode::REPEAT, WrapMode::CLAMP_TO_EDGE, - WrapMode::MIRRORED_REPEAT -}; + WrapMode::MIRRORED_REPEAT}; const SamplerFlags::Type SINGLE_VALUE_SAMPLER = SamplerFlags::Encode(FilterMode::NEAREST, FilterMode::NEAREST, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE); -} +} // namespace SamplerFlags::Type SamplerFlags::Encode(FilterMode::Type minFilter, FilterMode::Type magFilter, WrapMode::Type wrapS, WrapMode::Type wrapT) { return FILTER_MODES_FROM_DALI[minFilter] | ((FILTER_MODES_FROM_DALI[magFilter] & FILTER_MAG_BITS) << FILTER_MAG_SHIFT) | - (WRAP_MODES_FROM_DALI[wrapS] << WRAP_S_SHIFT) | (WRAP_MODES_FROM_DALI[wrapT] << WRAP_T_SHIFT); + (WRAP_MODES_FROM_DALI[wrapS] << WRAP_S_SHIFT) | (WRAP_MODES_FROM_DALI[wrapT] << WRAP_T_SHIFT); } FilterMode::Type SamplerFlags::GetMinFilter(Type flags) @@ -103,120 +101,119 @@ Sampler SamplerFlags::MakeSampler(Type flags) TextureDefinition::TextureDefinition(const std::string& imageUri, SamplerFlags::Type samplerFlags) : mImageUri(imageUri), mSamplerFlags(samplerFlags) -{} +{ +} MaterialDefinition::RawData - MaterialDefinition::LoadRaw(const std::string& imagesPath) const +MaterialDefinition::LoadRaw(const std::string& imagesPath) const { RawData raw; const bool hasTransparency = MaskMatch(mFlags, TRANSPARENCY); - uint32_t numBuffers = mTextureStages.size() + (hasTransparency ? - !CheckTextures(ALBEDO) + !CheckTextures(METALLIC | ROUGHNESS) + !CheckTextures(NORMAL) : - !CheckTextures(ALBEDO | METALLIC) + !CheckTextures(NORMAL | ROUGHNESS)); - if (numBuffers == 0) + uint32_t numBuffers = mTextureStages.size() + (hasTransparency ? !CheckTextures(ALBEDO) + !CheckTextures(METALLIC | ROUGHNESS) + !CheckTextures(NORMAL) : !CheckTextures(ALBEDO | METALLIC) + !CheckTextures(NORMAL | ROUGHNESS)); + if(numBuffers == 0) { return raw; } raw.mTextures.reserve(numBuffers); // Load textures - auto iTexture = mTextureStages.cbegin(); + auto iTexture = mTextureStages.cbegin(); auto checkStage = [&](uint32_t flags) { return iTexture != mTextureStages.end() && MaskMatch(iTexture->mSemantic, flags); }; // Check for compulsory textures: Albedo, Metallic, Roughness, Normal - if (checkStage(ALBEDO | METALLIC)) + if(checkStage(ALBEDO | METALLIC)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; - if (checkStage(NORMAL | ROUGHNESS)) + if(checkStage(NORMAL | ROUGHNESS)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; } else // single value normal-roughness { const auto bufferSize = 4; - uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff, 0xff }; // normal of (0, 0, 1), roughness of 1 - raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER }); + uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff, 0xff}; // normal of (0, 0, 1), roughness of 1 + raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER}); } } else { - if (checkStage(ALBEDO)) + if(checkStage(ALBEDO)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; } else // single value albedo, albedo-alpha or albedo-metallic { uint32_t bufferSize = 4; - uint8_t* buffer = nullptr; - auto format = Pixel::Format::RGBA8888; - if (hasTransparency) // albedo-alpha + uint8_t* buffer = nullptr; + auto format = Pixel::Format::RGBA8888; + if(hasTransparency) // albedo-alpha { - buffer = new uint8_t[bufferSize]; + buffer = new uint8_t[bufferSize]; buffer[3] = static_cast(mColor.a * 255.f); } - else if (!checkStage(METALLIC | ROUGHNESS)) // albedo-metallic + else if(!checkStage(METALLIC | ROUGHNESS)) // albedo-metallic { - buffer = new uint8_t[bufferSize]; - buffer[3] = 0xff; // metallic of 1.0 + buffer = new uint8_t[bufferSize]; + buffer[3] = 0xff; // metallic of 1.0 } - else // albedo + else // albedo { bufferSize = 3; - buffer = new uint8_t[bufferSize]; - format = Pixel::Format::RGB888; + buffer = new uint8_t[bufferSize]; + format = Pixel::Format::RGB888; } buffer[0] = static_cast(mColor.r * 255.f); buffer[1] = static_cast(mColor.g * 255.f); buffer[2] = static_cast(mColor.b * 255.f); - raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, format, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER }); + raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, format, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER}); } // If we have transparency, or an image based albedo map, we will have to continue with separate metallicRoughness + normal. const bool createMetallicRoughnessAndNormal = hasTransparency || std::distance(mTextureStages.begin(), iTexture) > 0; - if (checkStage(METALLIC | ROUGHNESS)) + if(checkStage(METALLIC | ROUGHNESS)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; } - else if (createMetallicRoughnessAndNormal) + else if(createMetallicRoughnessAndNormal) { // NOTE: we want to set both metallic and roughness to 1.0; dli uses the R & A channels, // glTF2 uses B & G, so we might as well just set all components to 1.0. const auto bufferSize = 4; - uint8_t* buffer = new uint8_t[bufferSize]{ 0xff, 0xff, 0xff, 0xff }; - raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER }); + uint8_t* buffer = new uint8_t[bufferSize]{0xff, 0xff, 0xff, 0xff}; + raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER}); } - if (checkStage(NORMAL)) + if(checkStage(NORMAL)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; } - else if (createMetallicRoughnessAndNormal) + else if(createMetallicRoughnessAndNormal) { const auto bufferSize = 3; - uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff }; // normal of (0, 0, 1) - raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER }); + uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff}; // normal of (0, 0, 1) + raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER}); } else // single-value normal-roughness { const auto bufferSize = 4; - uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff, 0xff }; // normal of (0, 0, 1), roughness of 1.0 - raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER }); + uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff, 0xff}; // normal of (0, 0, 1), roughness of 1.0 + raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER}); } } // Extra textures. TODO: emissive, occlusion etc. - if (checkStage(SUBSURFACE)) + if(checkStage(SUBSURFACE)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; } @@ -228,12 +225,12 @@ TextureSet MaterialDefinition::Load(const EnvironmentDefinition::Vector& environ auto textureSet = TextureSet::New(); uint32_t n = 0; - for (auto& tData : raw.mTextures) + for(auto& tData : raw.mTextures) { - auto& pixels = tData.mPixels; - auto texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight()); + auto& pixels = tData.mPixels; + auto texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight()); texture.Upload(tData.mPixels, 0, 0, 0, 0, pixels.GetWidth(), pixels.GetHeight()); - if (tData.mSamplerFlags & SamplerFlags::MIPMAP_MASK) + if(tData.mSamplerFlags & SamplerFlags::MIPMAP_MASK) { texture.GenerateMipmaps(); } @@ -245,16 +242,16 @@ TextureSet MaterialDefinition::Load(const EnvironmentDefinition::Vector& environ } // Assign textures to slots -- starting with 2D ones, then cubemaps, if any. - if (mEnvironmentIdx < environments.size()) + if(mEnvironmentIdx < environments.size()) { auto& envTextures = environments[mEnvironmentIdx].second; - if (envTextures.mDiffuse) + if(envTextures.mDiffuse) { textureSet.SetTexture(n, envTextures.mDiffuse); ++n; } - if (envTextures.mSpecular) + if(envTextures.mSpecular) { auto specularSampler = Sampler::New(); specularSampler.SetWrapMode(WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE); @@ -266,8 +263,7 @@ TextureSet MaterialDefinition::Load(const EnvironmentDefinition::Vector& environ } else { - ExceptionFlinger(ASSERT_LOCATION) << "Environment index (" << mEnvironmentIdx << ") out of bounds (" << - environments.size() << ")."; + ExceptionFlinger(ASSERT_LOCATION) << "Environment index (" << mEnvironmentIdx << ") out of bounds (" << environments.size() << ")."; } return textureSet; @@ -276,9 +272,9 @@ TextureSet MaterialDefinition::Load(const EnvironmentDefinition::Vector& environ bool MaterialDefinition::CheckTextures(uint32_t flags) const { return std::find_if(mTextureStages.begin(), mTextureStages.end(), [flags](const TextureStage& ts) { - return MaskMatch(ts.mSemantic, flags); - }) != mTextureStages.end(); + return MaskMatch(ts.mSemantic, flags); + }) != mTextureStages.end(); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/material-definition.h b/dali-scene-loader/public-api/material-definition.h index d360c88..80e93e7 100644 --- a/dali-scene-loader/public-api/material-definition.h +++ b/dali-scene-loader/public-api/material-definition.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_MATERIAL_DEFINITION_H #define DALI_SCENE_LOADER_MATERIAL_DEFINITION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,15 +24,14 @@ #include "dali-scene-loader/public-api/utils.h" // EXTERNAL INCLUDES -#include "dali/public-api/math/vector4.h" -#include "dali/public-api/common/vector-wrapper.h" #include +#include "dali/public-api/common/vector-wrapper.h" +#include "dali/public-api/math/vector4.h" namespace Dali { namespace SceneLoader { - /** * @brief Helper enum for encoding and decoding sampler states. */ @@ -43,54 +42,53 @@ struct DALI_SCENE_LOADER_API SamplerFlags enum Values : Type { // Filter - 3 bits - FILTER_NEAREST = 0, - FILTER_LINEAR = NthBit(0), + FILTER_NEAREST = 0, + FILTER_LINEAR = NthBit(0), FILTER_MIPMAP_NEAREST = NthBit(1), - FILTER_MIPMAP_LINEAR = NthBit(2), + FILTER_MIPMAP_LINEAR = NthBit(2), // Wrap - 2 bits WRAP_REPEAT = 0, - WRAP_CLAMP = NthBit(0), + WRAP_CLAMP = NthBit(0), WRAP_MIRROR = NthBit(1), // Layout - apply shift, then mask FILTER_MIN_BITS = 3, FILTER_MIN_MASK = NthBit(FILTER_MIN_BITS) - 1, - FILTER_MAG_BITS = 1, + FILTER_MAG_BITS = 1, FILTER_MAG_SHIFT = FILTER_MIN_BITS, - FILTER_MAG_MASK = NthBit(FILTER_MAG_BITS) - 1, + FILTER_MAG_MASK = NthBit(FILTER_MAG_BITS) - 1, - WRAP_S_BITS = 2, + WRAP_S_BITS = 2, WRAP_S_SHIFT = FILTER_MAG_SHIFT + FILTER_MAG_BITS, - WRAP_S_MASK = NthBit(WRAP_S_BITS) - 1, + WRAP_S_MASK = NthBit(WRAP_S_BITS) - 1, - WRAP_T_BITS = 2, + WRAP_T_BITS = 2, WRAP_T_SHIFT = WRAP_S_SHIFT + WRAP_S_BITS, - WRAP_T_MASK = NthBit(WRAP_T_BITS) - 1, + WRAP_T_MASK = NthBit(WRAP_T_BITS) - 1, // Diagnostics MIPMAP_MASK = FILTER_MIPMAP_LINEAR | FILTER_MIPMAP_NEAREST, // Default - DEFAULT = FILTER_LINEAR | (FILTER_LINEAR << FILTER_MAG_SHIFT) | (WRAP_REPEAT << WRAP_S_SHIFT) | (WRAP_REPEAT << WRAP_T_SHIFT), // LINEAR filters, REPEAT wraps + DEFAULT = FILTER_LINEAR | (FILTER_LINEAR << FILTER_MAG_SHIFT) | (WRAP_REPEAT << WRAP_S_SHIFT) | (WRAP_REPEAT << WRAP_T_SHIFT), // LINEAR filters, REPEAT wraps }; /** * @return SamplerFlags bit pattern calculated from the given Dali Sampler settings. */ - static Type Encode(FilterMode::Type minFilter, FilterMode::Type magFilter, - WrapMode::Type wrapS, WrapMode::Type wrapT); + static Type Encode(FilterMode::Type minFilter, FilterMode::Type magFilter, WrapMode::Type wrapS, WrapMode::Type wrapT); /** * @brief Decodes the minification filter patter of @a flags into the corresponding FilterMode. */ - static FilterMode::Type GetMinFilter(Type flags); + static FilterMode::Type GetMinFilter(Type flags); /** * @brief Decodes the magnification filter patter of @a flags into the corresponding FilterMode. */ - static FilterMode::Type GetMagFilter(Type flags); + static FilterMode::Type GetMagFilter(Type flags); /** * @brief Decodes the horizontal wrap pattern of @a flags into the corresponding WrapMode. @@ -113,7 +111,7 @@ struct DALI_SCENE_LOADER_API SamplerFlags */ struct DALI_SCENE_LOADER_API TextureDefinition { - std::string mImageUri; + std::string mImageUri; SamplerFlags::Type mSamplerFlags; TextureDefinition(const std::string& imageUri = "", SamplerFlags::Type samplerFlags = SamplerFlags::DEFAULT); @@ -130,22 +128,22 @@ struct DALI_SCENE_LOADER_API MaterialDefinition enum Flags : uint32_t { // Texture semantics - ALBEDO = NthBit(0), - METALLIC = NthBit(1), - ROUGHNESS = NthBit(2), - NORMAL = NthBit(3), - EMISSIVE = NthBit(4), // TODO: support - OCCLUSION = NthBit(5), // TODO: support - SUBSURFACE = NthBit(6), // Note: dli-only + ALBEDO = NthBit(0), + METALLIC = NthBit(1), + ROUGHNESS = NthBit(2), + NORMAL = NthBit(3), + EMISSIVE = NthBit(4), // TODO: support + OCCLUSION = NthBit(5), // TODO: support + SUBSURFACE = NthBit(6), // Note: dli-only // Other binary options - TRANSPARENCY = NthBit(20), - GLTF_CHANNELS = NthBit(21), // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#pbrmetallicroughnessmetallicroughnesstexture + TRANSPARENCY = NthBit(20), + GLTF_CHANNELS = NthBit(21), // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#pbrmetallicroughnessmetallicroughnesstexture // Alpha cutoff - reserved from the 24th bit - ALPHA_CUTOFF_BITS = 8, + ALPHA_CUTOFF_BITS = 8, ALPHA_CUTOFF_SHIFT = sizeof(uint32_t) * 8 - ALPHA_CUTOFF_BITS, - ALPHA_CUTOFF_MASK = (1 << ALPHA_CUTOFF_BITS) - 1, + ALPHA_CUTOFF_MASK = (1 << ALPHA_CUTOFF_BITS) - 1, }; /** @@ -153,7 +151,7 @@ struct DALI_SCENE_LOADER_API MaterialDefinition */ struct TextureStage { - uint32_t mSemantic; + uint32_t mSemantic; TextureDefinition mTexture; }; @@ -163,7 +161,7 @@ struct DALI_SCENE_LOADER_API MaterialDefinition { struct TextureData { - PixelData mPixels; + PixelData mPixels; SamplerFlags::Type mSamplerFlags; }; @@ -221,14 +219,14 @@ struct DALI_SCENE_LOADER_API MaterialDefinition public: // DATA uint32_t mFlags = 0x0; - Index mEnvironmentIdx = 0; - Vector4 mColor = Color::WHITE; - float mMetallic = 1.f; - float mRoughness = 1.f; + Index mEnvironmentIdx = 0; + Vector4 mColor = Color::WHITE; + float mMetallic = 1.f; + float mRoughness = 1.f; std::vector mTextureStages; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_MATERIAL_DEFINITION_H diff --git a/dali-scene-loader/public-api/matrix-stack.cpp b/dali-scene-loader/public-api/matrix-stack.cpp index 9d4454f..eb2316e 100644 --- a/dali-scene-loader/public-api/matrix-stack.cpp +++ b/dali-scene-loader/public-api/matrix-stack.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2020 Samsung Electronics Co., Ltd. +* Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ namespace Dali { namespace SceneLoader { - MatrixStack::MatrixStack() { mStack.reserve(16); @@ -34,13 +33,13 @@ bool MatrixStack::IsEmpty() const void MatrixStack::Push(const Matrix& model) { - if (mStack.empty()) + if(mStack.empty()) { mStack.push_back(model); } else { - Matrix m{ false }; + Matrix m{false}; Matrix::Multiply(m, model, mStack.back()); mStack.push_back(m); } @@ -62,5 +61,5 @@ void MatrixStack::PopAll() mStack.clear(); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/matrix-stack.h b/dali-scene-loader/public-api/matrix-stack.h index f764da1..5c5c923 100644 --- a/dali-scene-loader/public-api/matrix-stack.h +++ b/dali-scene-loader/public-api/matrix-stack.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_MATRIX_STACK_H_ #define DALI_SCENE_LOADER_MATRIX_STACK_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,14 +21,13 @@ #include "dali-scene-loader/public-api/api.h" // EXTERNAL INCLUDES -#include "dali/public-api/math/matrix.h" #include "dali/public-api/common/vector-wrapper.h" +#include "dali/public-api/math/matrix.h" namespace Dali { namespace SceneLoader { - /** * @brief A stack of matrices whereby each newly pushed matrix is stored * after being multiplied by the previous one (if any). @@ -39,17 +38,17 @@ class DALI_SCENE_LOADER_API MatrixStack public: MatrixStack(); - bool IsEmpty() const; - void Push(const Matrix& model); + bool IsEmpty() const; + void Push(const Matrix& model); const Matrix& Top() const; - void Pop(); - void PopAll(); // clears the stack, but retains the storage. + void Pop(); + void PopAll(); // clears the stack, but retains the storage. private: std::vector mStack; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_MATRIX_STACK_H_ diff --git a/dali-scene-loader/public-api/mesh-definition.cpp b/dali-scene-loader/public-api/mesh-definition.cpp index 2cea908..69292e2 100644 --- a/dali-scene-loader/public-api/mesh-definition.cpp +++ b/dali-scene-loader/public-api/mesh-definition.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ #include "dali-scene-loader/public-api/mesh-definition.h" // EXTERNAL INCLUDES -#include "dali/devel-api/adaptor-framework/pixel-buffer.h" -#include #include +#include +#include "dali/devel-api/adaptor-framework/pixel-buffer.h" namespace Dali { @@ -29,7 +29,6 @@ namespace SceneLoader { namespace { - using Uint16Vector4 = uint16_t[4]; class IndexProvider @@ -38,7 +37,8 @@ public: IndexProvider(const uint16_t* indices) : mData(reinterpret_cast(indices)), mFunc(indices ? IncrementPointer : Increment) - {} + { + } uint16_t operator()() { @@ -53,40 +53,39 @@ private: static uint16_t IncrementPointer(uintptr_t& data) { - auto iPtr = reinterpret_cast(data); + auto iPtr = reinterpret_cast(data); auto result = *iPtr; - data = reinterpret_cast(++iPtr); + data = reinterpret_cast(++iPtr); return result; } uintptr_t mData; - uint16_t(*mFunc)(uintptr_t&); + uint16_t (*mFunc)(uintptr_t&); }; - const std::string QUAD("quad"); ///@brief Reads a blob from the given stream @a source into @a target, which must have /// at least @a descriptor.length bytes. bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint8_t* target) { - if (!source.seekg(descriptor.mOffset, std::istream::beg)) + if(!source.seekg(descriptor.mOffset, std::istream::beg)) { return false; } - if (descriptor.IsConsecutive()) + if(descriptor.IsConsecutive()) { return !!source.read(reinterpret_cast(target), descriptor.mLength); } else { DALI_ASSERT_DEBUG(descriptor.mStride > descriptor.mElementSizeHint); - const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint; - uint32_t readSize = 0; - while (readSize < descriptor.mLength && - source.read(reinterpret_cast(target), descriptor.mElementSizeHint) && - source.seekg(diff, std::istream::cur)) + const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint; + uint32_t readSize = 0; + while(readSize < descriptor.mLength && + source.read(reinterpret_cast(target), descriptor.mElementSizeHint) && + source.seekg(diff, std::istream::cur)) { readSize += descriptor.mStride; target += descriptor.mElementSizeHint; @@ -95,11 +94,11 @@ bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint } } -template +template void ReadValues(const std::vector& valuesBuffer, const std::vector& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint) { const T* const indicesPtr = reinterpret_cast(indicesBuffer.data()); - for (uint32_t index = 0u; index < count; ++index) + for(uint32_t index = 0u; index < count; ++index) { uint32_t valuesIndex = indicesPtr[index] * elementSizeHint; memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint); @@ -110,60 +109,60 @@ bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source { bool success = false; - if (accessor.mBlob.IsDefined()) + if(accessor.mBlob.IsDefined()) { success = ReadBlob(accessor.mBlob, source, target); - if (!success) + if(!success) { return false; } } - if (accessor.mSparse) + if(accessor.mSparse) { const MeshDefinition::Blob& indices = accessor.mSparse->mIndices; - const MeshDefinition::Blob& values = accessor.mSparse->mValues; + const MeshDefinition::Blob& values = accessor.mSparse->mValues; - if (!indices.IsDefined() || !values.IsDefined()) + if(!indices.IsDefined() || !values.IsDefined()) { return false; } - const auto indicesBufferSize = indices.GetBufferSize(); + const auto indicesBufferSize = indices.GetBufferSize(); std::vector indicesBuffer(indicesBufferSize); success = ReadBlob(indices, source, indicesBuffer.data()); - if (!success) + if(!success) { return false; } - const auto valuesBufferSize = values.GetBufferSize(); + const auto valuesBufferSize = values.GetBufferSize(); std::vector valuesBuffer(valuesBufferSize); success = ReadBlob(values, source, valuesBuffer.data()); - if (!success) + if(!success) { return false; } - switch (indices.mElementSizeHint) + switch(indices.mElementSizeHint) { - case 1u: - { - ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); - break; - } - case 2u: - { - ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); - break; - } - case 4u: - { - ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); - break; - } - default: - DALI_ASSERT_DEBUG(!"Unsupported type for an index"); + case 1u: + { + ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); + break; + } + case 2u: + { + ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); + break; + } + case 4u: + { + ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); + break; + } + default: + DALI_ASSERT_DEBUG(!"Unsupported type for an index"); } } @@ -173,7 +172,7 @@ bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source void GenerateNormals(MeshDefinition::RawData& raw) { auto& attribs = raw.mAttribs; - DALI_ASSERT_DEBUG(attribs.size() > 0); // positions + DALI_ASSERT_DEBUG(attribs.size() > 0); // positions IndexProvider getIndex(raw.mIndices.data()); const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size(); @@ -181,12 +180,12 @@ void GenerateNormals(MeshDefinition::RawData& raw) auto* positions = reinterpret_cast(attribs[0].mData.data()); std::vector buffer(attribs[0].mNumElements * sizeof(Vector3)); - auto normals = reinterpret_cast(buffer.data()); + auto normals = reinterpret_cast(buffer.data()); - for (uint32_t i = 0; i < numIndices; i += 3) + for(uint32_t i = 0; i < numIndices; i += 3) { - uint16_t indices[]{ getIndex(), getIndex(), getIndex() }; - Vector3 pos[]{ positions[indices[0]], positions[indices[1]], positions[indices[2]] }; + uint16_t indices[]{getIndex(), getIndex(), getIndex()}; + Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]}; Vector3 a = pos[1] - pos[0]; Vector3 b = pos[2] - pos[0]; @@ -198,34 +197,34 @@ void GenerateNormals(MeshDefinition::RawData& raw) } auto iEnd = normals + attribs[0].mNumElements; - while (normals != iEnd) + while(normals != iEnd) { normals->Normalize(); ++normals; } - attribs.push_back({ "aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) }); + attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)}); } void GenerateTangentsWithUvs(MeshDefinition::RawData& raw) { auto& attribs = raw.mAttribs; - DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs + DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs IndexProvider getIndex(raw.mIndices.data()); const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size(); auto* positions = reinterpret_cast(attribs[0].mData.data()); - auto* uvs = reinterpret_cast(attribs[2].mData.data()); + auto* uvs = reinterpret_cast(attribs[2].mData.data()); std::vector buffer(attribs[0].mNumElements * sizeof(Vector3)); - auto tangents = reinterpret_cast(buffer.data()); + auto tangents = reinterpret_cast(buffer.data()); - for (uint32_t i = 0; i < numIndices; i += 3) + for(uint32_t i = 0; i < numIndices; i += 3) { - uint16_t indices[]{ getIndex(), getIndex(), getIndex() }; - Vector3 pos[]{ positions[indices[0]], positions[indices[1]], positions[indices[2]] }; - Vector2 uv[]{ uvs[indices[0]], uvs[indices[1]], uvs[indices[2]] }; + uint16_t indices[]{getIndex(), getIndex(), getIndex()}; + Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]}; + Vector2 uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]}; float x0 = pos[1].x - pos[0].x; float y0 = pos[1].y - pos[0].y; @@ -241,7 +240,7 @@ void GenerateTangentsWithUvs(MeshDefinition::RawData& raw) float s1 = uv[2].x - uv[0].x; float t1 = uv[2].y - uv[0].y; - float r = 1.f / (s0 * t1 - t0 * s1); + float r = 1.f / (s0 * t1 - t0 * s1); Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r); tangents[indices[0]] += tangent; tangents[indices[1]] += tangent; @@ -249,8 +248,8 @@ void GenerateTangentsWithUvs(MeshDefinition::RawData& raw) } auto* normals = reinterpret_cast(attribs[1].mData.data()); - auto iEnd = normals + attribs[1].mNumElements; - while (normals != iEnd) + auto iEnd = normals + attribs[1].mNumElements; + while(normals != iEnd) { *tangents -= *normals * normals->Dot(*tangents); tangents->Normalize(); @@ -258,23 +257,23 @@ void GenerateTangentsWithUvs(MeshDefinition::RawData& raw) ++tangents; ++normals; } - attribs.push_back({ "aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) }); + attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)}); } void GenerateTangents(MeshDefinition::RawData& raw) { auto& attribs = raw.mAttribs; - DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals + DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals auto* normals = reinterpret_cast(attribs[1].mData.data()); std::vector buffer(attribs[0].mNumElements * sizeof(Vector3)); - auto tangents = reinterpret_cast(buffer.data()); + auto tangents = reinterpret_cast(buffer.data()); auto iEnd = normals + attribs[1].mNumElements; - while (normals != iEnd) + while(normals != iEnd) { - Vector3 t[]{ normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS) }; + Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)}; *tangents = t[t[1].LengthSquared() > t[0].LengthSquared()]; *tangents -= *normals * normals->Dot(*tangents); @@ -283,7 +282,7 @@ void GenerateTangents(MeshDefinition::RawData& raw) ++tangents; ++normals; } - attribs.push_back({ "aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) }); + attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)}); } void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight) @@ -293,74 +292,74 @@ void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uin // Calculate the dimensions of the texture. // The total size of the texture is the length of the blend shapes blob. - textureWidth = 0u; + textureWidth = 0u; textureHeight = 0u; - if (0u == totalTextureSize) + if(0u == totalTextureSize) { // nothing to do. return; } - const uint32_t pow2 = static_cast(ceil(log2(totalTextureSize))); - const uint32_t powWidth = pow2 >> 1u; + const uint32_t pow2 = static_cast(ceil(log2(totalTextureSize))); + const uint32_t powWidth = pow2 >> 1u; const uint32_t powHeight = pow2 - powWidth; - textureWidth = 1u << powWidth; + textureWidth = 1u << powWidth; textureHeight = 1u << powHeight; } void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, const std::vector& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor) { uint32_t geometryBufferIndex = 0u; - float maxDistance = 0.f; - Vector3* geometryBufferV3 = reinterpret_cast(geometryBuffer); - for (const auto& blendShape : blendShapes) + float maxDistance = 0.f; + Vector3* geometryBufferV3 = reinterpret_cast(geometryBuffer); + for(const auto& blendShape : blendShapes) { - if (blendShape.deltas.IsDefined()) + if(blendShape.deltas.IsDefined()) { DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) || - blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) && - "Blend Shape position buffer length not a multiple of element size"); + blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) && + "Blend Shape position buffer length not a multiple of element size"); - const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize(); + const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (ReadAccessor(blendShape.deltas, binFile, buffer.data())) + if(ReadAccessor(blendShape.deltas, binFile, buffer.data())) { blendShape.deltas.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast(buffer.data())); // Calculate the difference with the original mesh. // Find the max distance to normalize the deltas. const Vector3* const deltasBuffer = reinterpret_cast(buffer.data()); - for (uint32_t index = 0u; index < numberOfVertices; ++index) + for(uint32_t index = 0u; index < numberOfVertices; ++index) { Vector3& delta = geometryBufferV3[geometryBufferIndex++]; - delta = deltasBuffer[index]; + delta = deltasBuffer[index]; maxDistance = std::max(maxDistance, delta.LengthSquared()); } } } - if (blendShape.normals.IsDefined()) + if(blendShape.normals.IsDefined()) { DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) || - blendShape.normals.mBlob.mStride >= sizeof(Vector3)) && - "Blend Shape normals buffer length not a multiple of element size"); + blendShape.normals.mBlob.mStride >= sizeof(Vector3)) && + "Blend Shape normals buffer length not a multiple of element size"); - const auto bufferSize = blendShape.normals.mBlob.GetBufferSize(); + const auto bufferSize = blendShape.normals.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (ReadAccessor(blendShape.normals, binFile, buffer.data())) + if(ReadAccessor(blendShape.normals, binFile, buffer.data())) { blendShape.normals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast(buffer.data())); // Calculate the difference with the original mesh, and translate to make all values positive. const Vector3* const deltasBuffer = reinterpret_cast(buffer.data()); - for (uint32_t index = 0u; index < numberOfVertices; ++index) + for(uint32_t index = 0u; index < numberOfVertices; ++index) { Vector3& delta = geometryBufferV3[geometryBufferIndex++]; - delta = deltasBuffer[index]; + delta = deltasBuffer[index]; delta.x *= 0.5f; delta.y *= 0.5f; @@ -373,25 +372,25 @@ void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, } } - if (blendShape.tangents.IsDefined()) + if(blendShape.tangents.IsDefined()) { DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) || - blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) && - "Blend Shape tangents buffer length not a multiple of element size"); + blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) && + "Blend Shape tangents buffer length not a multiple of element size"); - const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize(); + const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (ReadAccessor(blendShape.tangents, binFile, buffer.data())) + if(ReadAccessor(blendShape.tangents, binFile, buffer.data())) { blendShape.tangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast(buffer.data())); // Calculate the difference with the original mesh, and translate to make all values positive. const Vector3* const deltasBuffer = reinterpret_cast(buffer.data()); - for (uint32_t index = 0u; index < numberOfVertices; ++index) + for(uint32_t index = 0u; index < numberOfVertices; ++index) { Vector3& delta = geometryBufferV3[geometryBufferIndex++]; - delta = deltasBuffer[index]; + delta = deltasBuffer[index]; delta.x *= 0.5f; delta.y *= 0.5f; @@ -406,81 +405,77 @@ void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, } geometryBufferIndex = 0u; - for (const auto& blendShape : blendShapes) + for(const auto& blendShape : blendShapes) { // Normalize all the deltas and translate to a possitive value. // Deltas are going to be passed to the shader in a color texture // whose values that are less than zero are clamped. - if (blendShape.deltas.IsDefined()) + if(blendShape.deltas.IsDefined()) { - const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance)); - for (uint32_t index = 0u; index < numberOfVertices; ++index) + for(uint32_t index = 0u; index < numberOfVertices; ++index) { Vector3& delta = geometryBufferV3[geometryBufferIndex++]; - delta.x = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f); - delta.y = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f); - delta.z = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f); + delta.x = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f); + delta.y = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f); + delta.z = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f); } // Calculate and store the unnormalize factor. blendShapeUnnormalizeFactor = 1.f / normalizeFactor; } - if (blendShape.normals.IsDefined()) + if(blendShape.normals.IsDefined()) { geometryBufferIndex += numberOfVertices; } - if (blendShape.tangents.IsDefined()) + if(blendShape.tangents.IsDefined()) { geometryBufferIndex += numberOfVertices; } } } -} +} // namespace MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count) : mIndices{indices}, mValues{values}, mCount{count} -{} +{ +} -MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob, - const MeshDefinition::SparseBlob& sparse) +MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob, + const MeshDefinition::SparseBlob& sparse) : mBlob{blob}, mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr} -{} +{ +} -void MeshDefinition::Blob::ApplyMinMax(const std::vector& min, const std::vector& max, - uint32_t count, float* values) +void MeshDefinition::Blob::ApplyMinMax(const std::vector& min, const std::vector& max, uint32_t count, float* values) { DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0); const auto numComponents = std::max(min.size(), max.size()); - using ClampFn = void(*)(const float*, const float*, uint32_t, float&); - ClampFn clampFn = min.empty() ? - (max.empty() ? - static_cast(nullptr) : - [](const float* min, const float* max, uint32_t i, float& value) { - value = std::min(max[i], value); - }) : - (max.empty() ? - [](const float* min, const float* max, uint32_t i, float& value) { - value = std::max(min[i], value); - } : - [](const float* min, const float* max, uint32_t i, float& value) { - value = std::min(std::max(min[i], value), max[i]); - }); + using ClampFn = void (*)(const float*, const float*, uint32_t, float&); + ClampFn clampFn = min.empty() ? (max.empty() ? static_cast(nullptr) : [](const float* min, const float* max, uint32_t i, float& value) { + value = std::min(max[i], value); + }) + : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) { + value = std::max(min[i], value); + } + : [](const float* min, const float* max, uint32_t i, float& value) { + value = std::min(std::max(min[i], value), max[i]); + }); auto end = values + count * numComponents; - while (values != end) + while(values != end) { - auto nextElement = values + numComponents; - uint32_t i = 0; - while (values != nextElement) + auto nextElement = values + numComponents; + uint32_t i = 0; + while(values != nextElement) { clampFn(min.data(), max.data(), i, *values); ++values; @@ -496,7 +491,8 @@ MeshDefinition::Blob::Blob(uint32_t offset, uint32_t length, uint16_t stride, ui mElementSizeHint(elementSizeHint), mMin(min), mMax(max) -{} +{ +} uint32_t MeshDefinition::Blob::GetBufferSize() const { @@ -511,7 +507,7 @@ void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const { Property::Map attribMap; - attribMap[mName] = mType; + attribMap[mName] = mType; VertexBuffer attribBuffer = VertexBuffer::New(attribMap); attribBuffer.SetData(mData.data(), mNumElements); @@ -544,39 +540,39 @@ void MeshDefinition::RequestTangents() } MeshDefinition::RawData - MeshDefinition::LoadRaw(const std::string& modelsPath) const +MeshDefinition::LoadRaw(const std::string& modelsPath) const { RawData raw; - if (IsQuad()) + if(IsQuad()) { return raw; } const std::string meshPath = modelsPath + mUri; - std::ifstream binFile(meshPath, std::ios::binary); - if (!binFile) + std::ifstream binFile(meshPath, std::ios::binary); + if(!binFile) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read geometry data from '" << meshPath << "'"; } - if (mIndices.IsDefined()) + if(mIndices.IsDefined()) { - if (MaskMatch(mFlags, U32_INDICES)) + if(MaskMatch(mFlags, U32_INDICES)) { DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) || - mIndices.mBlob.mStride >= sizeof(uint32_t)) && - "Index buffer length not a multiple of element size"); + mIndices.mBlob.mStride >= sizeof(uint32_t)) && + "Index buffer length not a multiple of element size"); const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t); - raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially. - if (!ReadAccessor(mIndices, binFile, reinterpret_cast(raw.mIndices.data()))) + raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially. + if(!ReadAccessor(mIndices, binFile, reinterpret_cast(raw.mIndices.data()))) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'."; } auto u16s = raw.mIndices.data(); auto u32s = reinterpret_cast(raw.mIndices.data()); - auto end = u32s + indexCount; - while (u32s != end) + auto end = u32s + indexCount; + while(u32s != end) { *u16s = static_cast(*u32s); ++u16s; @@ -588,10 +584,10 @@ MeshDefinition::RawData else { DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) || - mIndices.mBlob.mStride >= sizeof(unsigned short)) && - "Index buffer length not a multiple of element size"); + mIndices.mBlob.mStride >= sizeof(unsigned short)) && + "Index buffer length not a multiple of element size"); raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short)); - if (!ReadAccessor(mIndices, binFile, reinterpret_cast(raw.mIndices.data()))) + if(!ReadAccessor(mIndices, binFile, reinterpret_cast(raw.mIndices.data()))) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'."; } @@ -599,14 +595,14 @@ MeshDefinition::RawData } std::vector positions; - if (mPositions.IsDefined()) + if(mPositions.IsDefined()) { DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) || - mPositions.mBlob.mStride >= sizeof(Vector3)) && - "Position buffer length not a multiple of element size"); - const auto bufferSize = mPositions.mBlob.GetBufferSize(); + mPositions.mBlob.mStride >= sizeof(Vector3)) && + "Position buffer length not a multiple of element size"); + const auto bufferSize = mPositions.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mPositions, binFile, buffer.data())) + if(!ReadAccessor(mPositions, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << meshPath << "'."; } @@ -614,35 +610,34 @@ MeshDefinition::RawData uint32_t numVector3 = bufferSize / sizeof(Vector3); mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast(buffer.data())); - if (HasBlendShapes()) + if(HasBlendShapes()) { positions.resize(numVector3); std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast(positions.data())); } - raw.mAttribs.push_back({ "aPosition", Property::VECTOR3, numVector3, std::move(buffer) }); + raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)}); } const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES; - auto hasNormals = mNormals.IsDefined(); - if (hasNormals) + auto hasNormals = mNormals.IsDefined(); + if(hasNormals) { DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) || - mNormals.mBlob.mStride >= sizeof(Vector3)) && - "Normal buffer length not a multiple of element size"); - const auto bufferSize = mNormals.mBlob.GetBufferSize(); + mNormals.mBlob.mStride >= sizeof(Vector3)) && + "Normal buffer length not a multiple of element size"); + const auto bufferSize = mNormals.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mNormals, binFile, buffer.data())) + if(!ReadAccessor(mNormals, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << meshPath << "'."; } mNormals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast(buffer.data())); - raw.mAttribs.push_back({ "aNormal", Property::VECTOR3, - static_cast(bufferSize / sizeof(Vector3)), std::move(buffer) }); + raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast(bufferSize / sizeof(Vector3)), std::move(buffer)}); } - else if (mNormals.mBlob.mLength != 0 && isTriangles) + else if(mNormals.mBlob.mLength != 0 && isTriangles) { DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize()); GenerateNormals(raw); @@ -650,24 +645,24 @@ MeshDefinition::RawData } const auto hasUvs = mTexCoords.IsDefined(); - if (hasUvs) + if(hasUvs) { DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) || - mTexCoords.mBlob.mStride >= sizeof(Vector2)) && - "Normal buffer length not a multiple of element size"); - const auto bufferSize = mTexCoords.mBlob.GetBufferSize(); + mTexCoords.mBlob.mStride >= sizeof(Vector2)) && + "Normal buffer length not a multiple of element size"); + const auto bufferSize = mTexCoords.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mTexCoords, binFile, buffer.data())) + if(!ReadAccessor(mTexCoords, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << meshPath << "'."; } const auto uvCount = bufferSize / sizeof(Vector2); - if (MaskMatch(mFlags, FLIP_UVS_VERTICAL)) + if(MaskMatch(mFlags, FLIP_UVS_VERTICAL)) { - auto uv = reinterpret_cast(buffer.data()); + auto uv = reinterpret_cast(buffer.data()); auto uvEnd = uv + uvCount; - while (uv != uvEnd) + while(uv != uvEnd) { uv->y = 1.0f - uv->y; ++uv; @@ -676,89 +671,84 @@ MeshDefinition::RawData mTexCoords.mBlob.ApplyMinMax(bufferSize / sizeof(Vector2), reinterpret_cast(buffer.data())); - raw.mAttribs.push_back({ "aTexCoord", Property::VECTOR2, static_cast(uvCount), - std::move(buffer) }); + raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast(uvCount), std::move(buffer)}); } - if (mTangents.IsDefined()) + if(mTangents.IsDefined()) { DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % sizeof(Vector3) == 0) || - mTangents.mBlob.mStride >= sizeof(Vector3)) && - "Tangents buffer length not a multiple of element size"); - const auto bufferSize = mTangents.mBlob.GetBufferSize(); + mTangents.mBlob.mStride >= sizeof(Vector3)) && + "Tangents buffer length not a multiple of element size"); + const auto bufferSize = mTangents.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mTangents, binFile, buffer.data())) + if(!ReadAccessor(mTangents, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << meshPath << "'."; } mTangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast(buffer.data())); - raw.mAttribs.push_back({ "aTangent", Property::VECTOR3, - static_cast(bufferSize / sizeof(Vector3)), std::move(buffer) }); + raw.mAttribs.push_back({"aTangent", Property::VECTOR3, static_cast(bufferSize / sizeof(Vector3)), std::move(buffer)}); } - else if (mTangents.mBlob.mLength != 0 && hasNormals && isTriangles) + else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles) { DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize()); hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw); } - if (IsSkinned()) + if(IsSkinned()) { - if (MaskMatch(mFlags, U16_JOINT_IDS)) + if(MaskMatch(mFlags, U16_JOINT_IDS)) { DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Uint16Vector4) == 0) || - mJoints0.mBlob.mStride >= sizeof(Uint16Vector4)) && - "Joints buffer length not a multiple of element size"); - const auto inBufferSize = mJoints0.mBlob.GetBufferSize(); + mJoints0.mBlob.mStride >= sizeof(Uint16Vector4)) && + "Joints buffer length not a multiple of element size"); + const auto inBufferSize = mJoints0.mBlob.GetBufferSize(); std::vector buffer(inBufferSize * 2); - auto u16s = buffer.data() + inBufferSize; - if (!ReadAccessor(mJoints0, binFile, u16s)) + auto u16s = buffer.data() + inBufferSize; + if(!ReadAccessor(mJoints0, binFile, u16s)) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'."; } auto floats = reinterpret_cast(buffer.data()); - auto end = u16s + inBufferSize; - while (u16s != end) + auto end = u16s + inBufferSize; + while(u16s != end) { auto value = *reinterpret_cast(u16s); - *floats = static_cast(value); + *floats = static_cast(value); u16s += sizeof(uint16_t); ++floats; } - raw.mAttribs.push_back({ "aJoints", Property::VECTOR4, - static_cast(buffer.size() / sizeof(Vector4)), std::move(buffer) }); + raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast(buffer.size() / sizeof(Vector4)), std::move(buffer)}); } else { DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Vector4) == 0) || - mJoints0.mBlob.mStride >= sizeof(Vector4)) && - "Joints buffer length not a multiple of element size"); - const auto bufferSize = mJoints0.mBlob.GetBufferSize(); + mJoints0.mBlob.mStride >= sizeof(Vector4)) && + "Joints buffer length not a multiple of element size"); + const auto bufferSize = mJoints0.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mJoints0, binFile, buffer.data())) + if(!ReadAccessor(mJoints0, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'."; } - raw.mAttribs.push_back({ "aJoints", Property::VECTOR4, - static_cast(bufferSize / sizeof(Vector4)), std::move(buffer) }); + raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast(bufferSize / sizeof(Vector4)), std::move(buffer)}); } DALI_ASSERT_ALWAYS(((mWeights0.mBlob.mLength % sizeof(Vector4) == 0) || - mWeights0.mBlob.mStride >= sizeof(Vector4)) && - "Weights buffer length not a multiple of element size"); - const auto bufferSize = mWeights0.mBlob.GetBufferSize(); + mWeights0.mBlob.mStride >= sizeof(Vector4)) && + "Weights buffer length not a multiple of element size"); + const auto bufferSize = mWeights0.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mWeights0, binFile, buffer.data())) + if(!ReadAccessor(mWeights0, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'."; } - raw.mAttribs.push_back({ "aWeights", Property::VECTOR4, - static_cast(bufferSize / sizeof(Vector4)), std::move(buffer) }); + raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast(bufferSize / sizeof(Vector4)), std::move(buffer)}); } // Calculate the Blob for the blend shapes. @@ -766,11 +756,11 @@ MeshDefinition::RawData blendShapesBlob.mOffset = std::numeric_limits::max(); blendShapesBlob.mLength = 0u; - for (const auto& blendShape : mBlendShapes) + for(const auto& blendShape : mBlendShapes) { - for (auto i : { &blendShape.deltas, &blendShape.normals, &blendShape.tangents }) + for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents}) { - if (i->IsDefined()) + if(i->IsDefined()) { blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset); blendShapesBlob.mLength += i->mBlob.mLength; @@ -778,18 +768,18 @@ MeshDefinition::RawData } } - if (HasBlendShapes()) + if(HasBlendShapes()) { const uint32_t numberOfVertices = mPositions.mBlob.mLength / sizeof(Vector3); // Calculate the size of one buffer inside the texture. raw.mBlendShapeBufferOffset = numberOfVertices; - bool calculateGltf2BlendShapes = false; - uint32_t textureWidth = 0u; - uint32_t textureHeight = 0u; + bool calculateGltf2BlendShapes = false; + uint32_t textureWidth = 0u; + uint32_t textureHeight = 0u; - if (!mBlendShapeHeader.IsDefined()) + if(!mBlendShapeHeader.IsDefined()) { CalculateTextureSize(blendShapesBlob.mLength / sizeof(Vector3), textureWidth, textureHeight); calculateGltf2BlendShapes = true; @@ -798,7 +788,7 @@ MeshDefinition::RawData { uint16_t header[2u]; ReadBlob(mBlendShapeHeader, binFile, reinterpret_cast(header)); - textureWidth = header[0u]; + textureWidth = header[0u]; textureHeight = header[1u]; } @@ -806,9 +796,9 @@ MeshDefinition::RawData raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes); Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F); - uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer(); + uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer(); - if (calculateGltf2BlendShapes) + if(calculateGltf2BlendShapes) { CalculateGltf2BlendShapes(geometryBuffer, binFile, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u]); } @@ -817,16 +807,16 @@ MeshDefinition::RawData Blob unnormalizeFactorBlob; unnormalizeFactorBlob.mLength = sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes); - if (blendShapesBlob.IsDefined()) + if(blendShapesBlob.IsDefined()) { - if (ReadBlob(blendShapesBlob, binFile, geometryBuffer)) + if(ReadBlob(blendShapesBlob, binFile, geometryBuffer)) { unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength; } } // Read the unnormalize factors. - if (unnormalizeFactorBlob.IsDefined()) + if(unnormalizeFactorBlob.IsDefined()) { ReadBlob(unnormalizeFactorBlob, binFile, reinterpret_cast(&raw.mBlendShapeUnnormalizeFactor[0u])); } @@ -843,32 +833,32 @@ MeshGeometry MeshDefinition::Load(RawData&& raw) const meshGeometry.geometry = Geometry::New(); meshGeometry.geometry.SetType(mPrimitiveType); - if (IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers. + if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers. { - auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0; + auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0; meshGeometry.geometry = MakeTexturedQuadGeometry(options); } else { - if (!raw.mIndices.empty()) + if(!raw.mIndices.empty()) { meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size()); } - for (auto& a : raw.mAttribs) + for(auto& a : raw.mAttribs) { a.AttachBuffer(meshGeometry.geometry); } - if (HasBlendShapes()) + if(HasBlendShapes()) { - meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset; + meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset; meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor); - meshGeometry.blendShapeGeometry = Texture::New( TextureType::TEXTURE_2D, - raw.mBlendShapeData.GetPixelFormat(), - raw.mBlendShapeData.GetWidth(), - raw.mBlendShapeData.GetHeight()); + meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D, + raw.mBlendShapeData.GetPixelFormat(), + raw.mBlendShapeData.GetWidth(), + raw.mBlendShapeData.GetHeight()); meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData); } } @@ -876,5 +866,5 @@ MeshGeometry MeshDefinition::Load(RawData&& raw) const return meshGeometry; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/mesh-definition.h b/dali-scene-loader/public-api/mesh-definition.h index 057aad7..cd0ddc9 100644 --- a/dali-scene-loader/public-api/mesh-definition.h +++ b/dali-scene-loader/public-api/mesh-definition.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_MESH_DEFINITION_H #define DALI_SCENE_LOADER_MESH_DEFINITION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,20 +19,19 @@ // INTERNAL INCLUDES #include "dali-scene-loader/public-api/api.h" -#include "dali-scene-loader/public-api/mesh-geometry.h" #include "dali-scene-loader/public-api/blend-shape-details.h" -#include "dali-scene-loader/public-api/utils.h" #include "dali-scene-loader/public-api/index.h" +#include "dali-scene-loader/public-api/mesh-geometry.h" +#include "dali-scene-loader/public-api/utils.h" // EXTERNAL INCLUDES -#include "dali/public-api/common/vector-wrapper.h" #include +#include "dali/public-api/common/vector-wrapper.h" namespace Dali { namespace SceneLoader { - /** * @brief Defines a mesh with its attributes, the primitive type to render it as, * and the file to load it from with the offset and length information for the @@ -42,25 +41,28 @@ struct DALI_SCENE_LOADER_API MeshDefinition { using Vector = std::vector>; - enum : uint32_t { INVALID = std::numeric_limits::max() }; + enum : uint32_t + { + INVALID = std::numeric_limits::max() + }; enum Flags : uint16_t { FLIP_UVS_VERTICAL = NthBit(0), - U32_INDICES = NthBit(1), // default is unsigned short - U16_JOINT_IDS = NthBit(2), // default is floats + U32_INDICES = NthBit(1), // default is unsigned short + U16_JOINT_IDS = NthBit(2), // default is floats }; enum Attributes { - INDICES = NthBit(0), - POSITIONS = NthBit(1), - NORMALS = NthBit(2), - TEX_COORDS = NthBit(3), - TANGENTS = NthBit(4), - LEGACY_BITANGENTS = NthBit(5), // these are ignored; we're calculating them in the (PBR) shader. - JOINTS_0 = NthBit(6), - WEIGHTS_0 = NthBit(7), + INDICES = NthBit(0), + POSITIONS = NthBit(1), + NORMALS = NthBit(2), + TEX_COORDS = NthBit(3), + TANGENTS = NthBit(4), + LEGACY_BITANGENTS = NthBit(5), // these are ignored; we're calculating them in the (PBR) shader. + JOINTS_0 = NthBit(6), + WEIGHTS_0 = NthBit(7), }; /** @@ -69,10 +71,10 @@ struct DALI_SCENE_LOADER_API MeshDefinition */ struct Blob { - uint32_t mOffset = INVALID; // the default means that the blob is undefined. - uint32_t mLength = 0; // if the blob is undefined, its data may still be generated. This is enabled by setting length to some non-0 value. Refer to MeshDefinition for details. - uint16_t mStride = 0; // ignore if 0 - uint16_t mElementSizeHint = 0; // ignore if 0 or stride == 0 + uint32_t mOffset = INVALID; // the default means that the blob is undefined. + uint32_t mLength = 0; // if the blob is undefined, its data may still be generated. This is enabled by setting length to some non-0 value. Refer to MeshDefinition for details. + uint16_t mStride = 0; // ignore if 0 + uint16_t mElementSizeHint = 0; // ignore if 0 or stride == 0 std::vector mMin; std::vector mMax; @@ -80,8 +82,7 @@ struct DALI_SCENE_LOADER_API MeshDefinition Blob() = default; - Blob(uint32_t offset, uint32_t length, uint16_t stride = 0, uint16_t elementSizeHint = 0, - const std::vector& min = {}, const std::vector& max = {}); + Blob(uint32_t offset, uint32_t length, uint16_t stride = 0, uint16_t elementSizeHint = 0, const std::vector& min = {}, const std::vector& max = {}); /** * @brief Calculates the size of a tightly-packed buffer for the elements from the blob. @@ -122,14 +123,14 @@ struct DALI_SCENE_LOADER_API MeshDefinition SparseBlob(const Blob& indices, const Blob& values, uint32_t count); - Blob mIndices; - Blob mValues; + Blob mIndices; + Blob mValues; uint32_t mCount = 0u; }; struct Accessor { - Blob mBlob; + Blob mBlob; std::unique_ptr mSparse; Accessor() = default; @@ -140,8 +141,8 @@ struct DALI_SCENE_LOADER_API MeshDefinition Accessor(Accessor&&) = default; Accessor& operator=(Accessor&&) = default; - Accessor(const MeshDefinition::Blob& blob, - const MeshDefinition::SparseBlob& sparse); + Accessor(const MeshDefinition::Blob& blob, + const MeshDefinition::SparseBlob& sparse); bool IsDefined() const { @@ -155,30 +156,30 @@ struct DALI_SCENE_LOADER_API MeshDefinition struct BlendShape { std::string name; - Accessor deltas; - Accessor normals; - Accessor tangents; - float weight = 0.f; + Accessor deltas; + Accessor normals; + Accessor tangents; + float weight = 0.f; }; struct RawData { struct Attrib { - std::string mName; - Property::Type mType; - uint32_t mNumElements; + std::string mName; + Property::Type mType; + uint32_t mNumElements; std::vector mData; void AttachBuffer(Geometry& g) const; }; std::vector mIndices; - std::vector mAttribs; + std::vector mAttribs; - unsigned int mBlendShapeBufferOffset; + unsigned int mBlendShapeBufferOffset; Dali::Vector mBlendShapeUnnormalizeFactor; - PixelData mBlendShapeData; + PixelData mBlendShapeData; }; MeshDefinition() = default; @@ -235,25 +236,25 @@ struct DALI_SCENE_LOADER_API MeshDefinition MeshGeometry Load(RawData&& raw) const; public: // DATA - uint32_t mFlags = 0x0; + uint32_t mFlags = 0x0; Geometry::Type mPrimitiveType = Geometry::TRIANGLES; - std::string mUri; - Accessor mIndices; - Accessor mPositions; - Accessor mNormals; // data can be generated based on positions - Accessor mTexCoords; - Accessor mTangents; // data can be generated based on normals and texCoords (the latter isn't mandatory; the results will be better if available) - Accessor mJoints0; - Accessor mWeights0; - - Blob mBlendShapeHeader; + std::string mUri; + Accessor mIndices; + Accessor mPositions; + Accessor mNormals; // data can be generated based on positions + Accessor mTexCoords; + Accessor mTangents; // data can be generated based on normals and texCoords (the latter isn't mandatory; the results will be better if available) + Accessor mJoints0; + Accessor mWeights0; + + Blob mBlendShapeHeader; std::vector mBlendShapes; - BlendShapes::Version mBlendShapeVersion = BlendShapes::Version::INVALID; + BlendShapes::Version mBlendShapeVersion = BlendShapes::Version::INVALID; Index mSkeletonIdx = INVALID_INDEX; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_MESH_DEFINITION_H diff --git a/dali-scene-loader/public-api/mesh-geometry.h b/dali-scene-loader/public-api/mesh-geometry.h index bf282da..026e9a7 100644 --- a/dali-scene-loader/public-api/mesh-geometry.h +++ b/dali-scene-loader/public-api/mesh-geometry.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_MESH_GEOMETRY_H #define DALI_SCENE_LOADER_MESH_GEOMETRY_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,16 +28,15 @@ namespace Dali { namespace SceneLoader { - struct DALI_SCENE_LOADER_API MeshGeometry { - Geometry geometry; ///< The array of vertices. - Texture blendShapeGeometry; ///< The array of vertices of the different blend shapes encoded inside a texture with power of two dimensions. + Geometry geometry; ///< The array of vertices. + Texture blendShapeGeometry; ///< The array of vertices of the different blend shapes encoded inside a texture with power of two dimensions. Vector blendShapeUnnormalizeFactor; ///< Factor used to unnormalize the geometry of the blend shape. - unsigned int blendShapeBufferOffset; ///< Offset used to calculate the start of each blend shape. + unsigned int blendShapeBufferOffset; ///< Offset used to calculate the start of each blend shape. }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif // DALI_SCENE_LOADER_MESH_GEOMETRY_H diff --git a/dali-scene-loader/public-api/node-definition.cpp b/dali-scene-loader/public-api/node-definition.cpp index a277371..45e0b23 100644 --- a/dali-scene-loader/public-api/node-definition.cpp +++ b/dali-scene-loader/public-api/node-definition.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ namespace Dali { namespace SceneLoader { - void NodeDefinition::Renderable::RegisterResources(IResourceReceiver& receiver) const { receiver.Register(ResourceType::Shader, mShaderIdx); @@ -35,15 +34,14 @@ void NodeDefinition::Renderable::ReflectResources(IResourceReflector& reflector) reflector.Reflect(ResourceType::Shader, mShaderIdx); } -void NodeDefinition::Renderable::OnCreate(const NodeDefinition& node, CreateParams& params, - Actor& actor) const +void NodeDefinition::Renderable::OnCreate(const NodeDefinition& node, CreateParams& params, Actor& actor) const { DALI_ASSERT_DEBUG(mShaderIdx != INVALID_INDEX); - auto& resources = params.mResources; - Shader shader = resources.mShaders[mShaderIdx].second; + auto& resources = params.mResources; + Shader shader = resources.mShaders[mShaderIdx].second; static Geometry defaultGeometry = Geometry::New(); - Renderer renderer = Renderer::New(defaultGeometry, shader); + Renderer renderer = Renderer::New(defaultGeometry, shader); RendererState::Apply(resources.mShaders[mShaderIdx].first.mRendererState, renderer); @@ -66,19 +64,19 @@ Actor NodeDefinition::CreateActor(CreateParams& params) const actor.RegisterProperty(ORIGINAL_MATRIX_PROPERTY_NAME, GetLocalSpace(), Property::AccessMode::READ_ONLY); - if (mRenderable) + if(mRenderable) { mRenderable->OnCreate(*this, params, actor); } - for (auto& e : mExtras) + for(auto& e : mExtras) { actor.RegisterProperty(e.mKey, e.mValue); } - for (auto& c : mConstraints) + for(auto& c : mConstraints) { - params.mConstrainables.push_back(ConstraintRequest{ &c, actor }); + params.mConstrainables.push_back(ConstraintRequest{&c, actor}); } return actor; @@ -86,7 +84,7 @@ Actor NodeDefinition::CreateActor(CreateParams& params) const Matrix NodeDefinition::GetLocalSpace() const { - Matrix localSpace{ false }; + Matrix localSpace{false}; localSpace.SetTransformComponents(mScale, mOrientation, mPosition); return localSpace; } @@ -111,34 +109,34 @@ void ModelNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParam Renderable::OnCreate(node, params, actor); auto& resources = params.mResources; - auto& mesh = resources.mMeshes[mMeshIdx]; + auto& mesh = resources.mMeshes[mMeshIdx]; - auto renderer = actor.GetRendererAt(0); + auto renderer = actor.GetRendererAt(0); Geometry geometry = mesh.second.geometry; renderer.SetGeometry(geometry); auto shader = renderer.GetShader(); - if (mesh.first.IsSkinned()) + if(mesh.first.IsSkinned()) { - params.mSkinnables.push_back(SkinningShaderConfigurationRequest{ mesh.first.mSkeletonIdx, shader }); + params.mSkinnables.push_back(SkinningShaderConfigurationRequest{mesh.first.mSkeletonIdx, shader}); } - if (mesh.first.HasBlendShapes()) + if(mesh.first.HasBlendShapes()) { - params.mBlendshapeRequests.push_back(BlendshapeShaderConfigurationRequest{ node.mName, mMeshIdx, shader }); + params.mBlendshapeRequests.push_back(BlendshapeShaderConfigurationRequest{node.mName, mMeshIdx, shader}); } TextureSet textures = resources.mMaterials[mMaterialIdx].second; // Set the blend shape texture. - if (mesh.second.blendShapeGeometry) + if(mesh.second.blendShapeGeometry) { TextureSet newTextureSet = TextureSet::New(); newTextureSet.SetTexture(0u, mesh.second.blendShapeGeometry); const unsigned int numberOfTextures = textures.GetTextureCount(); - for (unsigned int index = 0u; index < numberOfTextures; ++index) + for(unsigned int index = 0u; index < numberOfTextures; ++index) { const unsigned int newIndex = index + 1u; newTextureSet.SetTexture(newIndex, textures.GetTexture(index)); @@ -160,14 +158,13 @@ void ModelNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParam actor.RegisterProperty("uIblIntensity", resources.mEnvironmentMaps[envIdx].first.mIblIntensity); const auto alphaCutoff = matDef.GetAlphaCutoff(); - if (alphaCutoff > 0.f) + if(alphaCutoff > 0.f) { actor.RegisterProperty("uAlphaThreshold", alphaCutoff); } } -void ArcNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParams& params, - Actor& actor) const +void ArcNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParams& params, Actor& actor) const { ModelNode::OnCreate(node, params, actor); @@ -176,11 +173,11 @@ void ArcNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParams& actor.RegisterProperty("radius", mRadius); const float startAngleRadians = mStartAngleDegrees * Math::PI_OVER_180; - Vector2 startPolar{ std::cos(startAngleRadians), std::sin(startAngleRadians) }; + Vector2 startPolar{std::cos(startAngleRadians), std::sin(startAngleRadians)}; actor.RegisterProperty("startAngle", startPolar); const float endAngleRadians = mEndAngleDegrees * Math::PI_OVER_180; - Vector2 endPolar{ std::cos(endAngleRadians), std::sin(endAngleRadians) }; + Vector2 endPolar{std::cos(endAngleRadians), std::sin(endAngleRadians)}; actor.RegisterProperty("endAngle", endPolar); } @@ -188,12 +185,12 @@ void ArcNode::GetEndVectorWithDiffAngle(float startAngle, float diffAngle, Vecto { float endAngle = 0.f; - if (diffAngle <= 0.001f) + if(diffAngle <= 0.001f) { //0.001 is used to ensure is empty arc when startAngle = endAngle + 360 * N endAngle = startAngle + 0.001f; } - else if (diffAngle >= 360.f) + else if(diffAngle >= 360.f) { endAngle = diffAngle + 359.99f; } @@ -205,5 +202,5 @@ void ArcNode::GetEndVectorWithDiffAngle(float startAngle, float diffAngle, Vecto endVector.y = sinf(endAngle * Math::PI_OVER_180); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/node-definition.h b/dali-scene-loader/public-api/node-definition.h index 3dec499..b496cf7 100644 --- a/dali-scene-loader/public-api/node-definition.h +++ b/dali-scene-loader/public-api/node-definition.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_NODE_DEFINITION_H_ #define DALI_SCENE_LOADER_NODE_DEFINITION_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,19 +23,18 @@ #include "dali-scene-loader/public-api/resource-bundle.h" // EXTERNAL INCLUDES -#include "dali/public-api/math/quaternion.h" +#include +#include +#include +#include "dali/public-api/actors/actor.h" #include "dali/public-api/math/matrix.h" +#include "dali/public-api/math/quaternion.h" #include "dali/public-api/math/vector4.h" -#include "dali/public-api/actors/actor.h" -#include -#include -#include namespace Dali { namespace SceneLoader { - class ViewProjection; /** @@ -70,7 +69,7 @@ public: struct DALI_SCENE_LOADER_API ConstraintDefinition { std::string mProperty; ///< name of the property to constrain. - Index mSourceIdx; ///< index of the node to serve as the source of the constraint. + Index mSourceIdx; ///< index of the node to serve as the source of the constraint. bool operator<(const ConstraintDefinition& other) const { @@ -90,7 +89,7 @@ struct DALI_SCENE_LOADER_API ConstraintDefinition struct DALI_SCENE_LOADER_API Transforms { - MatrixStack modelStack; + MatrixStack modelStack; const ViewProjection& viewProjection; }; @@ -100,7 +99,7 @@ struct DALI_SCENE_LOADER_API Transforms */ struct DALI_SCENE_LOADER_API SkinningShaderConfigurationRequest { - Index mSkeletonIdx; + Index mSkeletonIdx; Shader mShader; bool operator<(const SkinningShaderConfigurationRequest& other) const @@ -115,8 +114,8 @@ struct DALI_SCENE_LOADER_API SkinningShaderConfigurationRequest struct DALI_SCENE_LOADER_API BlendshapeShaderConfigurationRequest { std::string mNodeName; - Index mMeshIdx; - Shader mShader; + Index mMeshIdx; + Shader mShader; bool operator<(const BlendshapeShaderConfigurationRequest& other) const { @@ -129,8 +128,8 @@ struct DALI_SCENE_LOADER_API BlendshapeShaderConfigurationRequest */ struct DALI_SCENE_LOADER_API ConstraintRequest { - const ConstraintDefinition* const mConstraint; ///< Definition of the constraint to create. - Actor mTarget; ///< Target of the constraint. + const ConstraintDefinition* const mConstraint; ///< Definition of the constraint to create. + Actor mTarget; ///< Target of the constraint. }; /** @@ -140,18 +139,18 @@ struct DALI_SCENE_LOADER_API ConstraintRequest */ struct DALI_SCENE_LOADER_API NodeDefinition { -public: // TYPES +public: // TYPES using Vector = std::vector; struct CreateParams { public: // input const ResourceBundle& mResources; - Transforms& mXforms; + Transforms& mXforms; public: // output - std::vector mConstrainables; - std::vector mSkinnables; + std::vector mConstrainables; + std::vector mSkinnables; std::vector mBlendshapeRequests; }; @@ -176,14 +175,14 @@ public: // TYPES { auto choice = choices.Get(mTag); return std::min(choice != Customization::NONE ? choice : 0, - static_cast(node.mChildren.size() - 1)); + static_cast(node.mChildren.size() - 1)); } }; class IVisitor { public: - virtual void Start(NodeDefinition& n) = 0; + virtual void Start(NodeDefinition& n) = 0; virtual void Finish(NodeDefinition& n) = 0; protected: @@ -193,7 +192,7 @@ public: // TYPES class IConstVisitor { public: - virtual void Start(const NodeDefinition& n) = 0; + virtual void Start(const NodeDefinition& n) = 0; virtual void Finish(const NodeDefinition& n) = 0; protected: @@ -202,7 +201,7 @@ public: // TYPES struct Extra { - std::string mKey; + std::string mKey; Property::Value mValue; bool operator<(const Extra& other) const @@ -211,7 +210,7 @@ public: // TYPES } }; -public: // METHODS +public: // METHODS /** * @brief Creates a DALi Actor from this definition only. * @note Not recursive. @@ -225,28 +224,28 @@ public: // DATA std::string mName; - Vector3 mPosition = Vector3::ZERO; + Vector3 mPosition = Vector3::ZERO; Quaternion mOrientation = Quaternion::IDENTITY; - Vector3 mScale = Vector3::ONE; - Vector3 mSize = Vector3::ONE; + Vector3 mScale = Vector3::ONE; + Vector3 mSize = Vector3::ONE; bool mIsVisible = true; - std::unique_ptr mRenderable; + std::unique_ptr mRenderable; std::unique_ptr mCustomization; - std::vector mExtras; - std::vector mConstraints; + std::vector mExtras; + std::vector mConstraints; std::vector mChildren; - Index mParentIdx = INVALID_INDEX; + Index mParentIdx = INVALID_INDEX; }; class DALI_SCENE_LOADER_API ModelNode : public NodeDefinition::Renderable { public: // DATA - Vector4 mColor = Color::WHITE; - Index mMeshIdx = INVALID_INDEX; - Index mMaterialIdx = INVALID_INDEX; + Vector4 mColor = Color::WHITE; + Index mMeshIdx = INVALID_INDEX; + Index mMaterialIdx = INVALID_INDEX; public: // METHODS void RegisterResources(IResourceReceiver& receiver) const override; @@ -260,11 +259,11 @@ public: // METHODS class DALI_SCENE_LOADER_API ArcNode : public ModelNode { public: // DATA - bool mAntiAliasing = true; - int mArcCaps = 0; + bool mAntiAliasing = true; + int mArcCaps = 0; float mStartAngleDegrees = .0f; - float mEndAngleDegrees = .0f; - float mRadius = .0f; + float mEndAngleDegrees = .0f; + float mRadius = .0f; public: // METHODS static void GetEndVectorWithDiffAngle(float startAngle, float endAngle, Vector2& endVector); @@ -272,7 +271,7 @@ public: // METHODS void OnCreate(const NodeDefinition& node, NodeDefinition::CreateParams& params, Actor& actor) const override; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_NODE_DEFINITION_H_ diff --git a/dali-scene-loader/public-api/parse-renderer-state.cpp b/dali-scene-loader/public-api/parse-renderer-state.cpp index c60b1d4..815dfaf 100644 --- a/dali-scene-loader/public-api/parse-renderer-state.cpp +++ b/dali-scene-loader/public-api/parse-renderer-state.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ */ #include "dali-scene-loader/public-api/parse-renderer-state.h" -#include "dali/devel-api/common/map-wrapper.h" #include +#include "dali/devel-api/common/map-wrapper.h" namespace Dali { @@ -27,9 +27,8 @@ namespace RendererState { namespace { - std::map COMPARISONS{ -#define DECL_COMPARISON(x) { #x, Comparison::x } +#define DECL_COMPARISON(x) {#x, Comparison::x} DECL_COMPARISON(NEVER), DECL_COMPARISON(ALWAYS), DECL_COMPARISON(LESS), @@ -45,7 +44,7 @@ Type InterpretComparison(const std::string_view& str) { Type value = 0x0; auto iFind = COMPARISONS.find(str); - if (iFind != COMPARISONS.end()) + if(iFind != COMPARISONS.end()) { value = iFind->second; } @@ -53,7 +52,7 @@ Type InterpretComparison(const std::string_view& str) } std::map BLEND_FACTORS{ -#define DECL_BLEND_FACTOR(x) { #x, SceneLoader::BlendFactor::x } +#define DECL_BLEND_FACTOR(x) {#x, SceneLoader::BlendFactor::x} DECL_BLEND_FACTOR(ZERO), DECL_BLEND_FACTOR(ONE), DECL_BLEND_FACTOR(SRC_COLOR), @@ -76,7 +75,7 @@ Type InterpretBlendFactor(const std::string_view& str, uint8_t item) { Type value = 0x0; auto iFind = BLEND_FACTORS.find(str); - if (iFind != BLEND_FACTORS.end()) + if(iFind != BLEND_FACTORS.end()) { value = iFind->second << (BLEND_FACTOR_BASE_SHIFT + BLEND_FACTOR_ITEM_BITS * item); } @@ -84,7 +83,7 @@ Type InterpretBlendFactor(const std::string_view& str, uint8_t item) } std::map BUFFER_MODES{ -#define DECL_BUFFER_MODE(x) { #x, BufferMode::x } +#define DECL_BUFFER_MODE(x) {#x, BufferMode::x} DECL_BUFFER_MODE(NONE), DECL_BUFFER_MODE(AUTO), DECL_BUFFER_MODE(COLOR), @@ -96,63 +95,62 @@ Type InterpretBufferMode(const std::string_view& str) { Type value = 0x0; auto iFind = BUFFER_MODES.find(str); - if (iFind != BUFFER_MODES.end()) + if(iFind != BUFFER_MODES.end()) { value = iFind->second << BUFFER_MODE_SHIFT; } return value; } -std::map RENDERER_STATE_PROCESSORS{ - { "DEPTH_WRITE", [](const std::string_view&) -> Type { return DEPTH_WRITE; } }, - { "DEPTH_TEST", [](const std::string_view&) -> Type { return DEPTH_TEST; } }, - { "CULL_FRONT", [](const std::string_view&) -> Type { return CULL_FRONT; } }, - { "CULL_BACK", [](const std::string_view&) -> Type { return CULL_BACK; } }, - { "ALPHA_BLEND", [](const std::string_view&) -> Type { return ALPHA_BLEND; } }, - { "DEPTH_FUNC", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? - (InterpretComparison(std::string_view(arg.data() + 1, arg.size() - 1)) << DEPTH_FUNCTION_SHIFT) : 0x0; - return value; - } }, - { "BLEND_SRC_RGB", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 0) : 0x0; - return value; - }}, - { "BLEND_DST_RGB", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 1) : 0x0; - return value; - }}, - { "BLEND_SRC_ALPHA", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 2) : 0x0; - return value; - }}, - { "BLEND_DST_ALPHA", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 3) : 0x0; - return value; - }}, - { "BUFFER_MODE", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? InterpretBufferMode(std::string_view(arg.data() + 1, arg.size() - 1)) : 0x0; - return value; - }}, +std::map RENDERER_STATE_PROCESSORS{ + {"DEPTH_WRITE", [](const std::string_view&) -> Type { return DEPTH_WRITE; }}, + {"DEPTH_TEST", [](const std::string_view&) -> Type { return DEPTH_TEST; }}, + {"CULL_FRONT", [](const std::string_view&) -> Type { return CULL_FRONT; }}, + {"CULL_BACK", [](const std::string_view&) -> Type { return CULL_BACK; }}, + {"ALPHA_BLEND", [](const std::string_view&) -> Type { return ALPHA_BLEND; }}, + {"DEPTH_FUNC", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? (InterpretComparison(std::string_view(arg.data() + 1, arg.size() - 1)) << DEPTH_FUNCTION_SHIFT) : 0x0; + return value; + }}, + {"BLEND_SRC_RGB", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 0) : 0x0; + return value; + }}, + {"BLEND_DST_RGB", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 1) : 0x0; + return value; + }}, + {"BLEND_SRC_ALPHA", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 2) : 0x0; + return value; + }}, + {"BLEND_DST_ALPHA", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 3) : 0x0; + return value; + }}, + {"BUFFER_MODE", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? InterpretBufferMode(std::string_view(arg.data() + 1, arg.size() - 1)) : 0x0; + return value; + }}, }; -} +} // namespace Type Parse(const char* string, size_t length, StringCallback onError) { - if (length == 0) + if(length == 0) { length = strlen(string); } Type value = 0x0; - auto iEnd = string + length; - while (string != iEnd) + auto iEnd = string + length; + while(string != iEnd) { auto iNextToken = std::find(string, iEnd, '|'); - auto iColon = std::find(string, iNextToken, ':'); - auto i = RENDERER_STATE_PROCESSORS.find(std::string_view(string, iColon - string)); - if (i != RENDERER_STATE_PROCESSORS.end() && size_t(std::distance(string, iNextToken)) >= i->first.size()) + auto iColon = std::find(string, iNextToken, ':'); + auto i = RENDERER_STATE_PROCESSORS.find(std::string_view(string, iColon - string)); + if(i != RENDERER_STATE_PROCESSORS.end() && size_t(std::distance(string, iNextToken)) >= i->first.size()) { value |= i->second(std::string_view(string + i->first.size(), iNextToken - iColon)); } @@ -167,6 +165,6 @@ Type Parse(const char* string, size_t length, StringCallback onError) return value; } -} // RendererState -} -} +} // namespace RendererState +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/parse-renderer-state.h b/dali-scene-loader/public-api/parse-renderer-state.h index 97792aa..38103d0 100644 --- a/dali-scene-loader/public-api/parse-renderer-state.h +++ b/dali-scene-loader/public-api/parse-renderer-state.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_INTERPRET_RENDERER_STATE_H #define DALI_SCENE_LOADER_INTERPRET_RENDERER_STATE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ namespace SceneLoader { namespace RendererState { - /* * @brief Attempts to interpret a string for renderer states, which can be a combination of the following * (using '|' as a delimiter, if multiple specified):
@@ -42,8 +41,8 @@ namespace RendererState */ DALI_SCENE_LOADER_API Type Parse(const char* string, size_t length = 0, StringCallback onError = DefaultErrorCallback); -} -} -} +} // namespace RendererState +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_INTERPRET_RENDERER_STATE_H diff --git a/dali-scene-loader/public-api/renderer-state.cpp b/dali-scene-loader/public-api/renderer-state.cpp index c3888a0..80178b5 100644 --- a/dali-scene-loader/public-api/renderer-state.cpp +++ b/dali-scene-loader/public-api/renderer-state.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ namespace SceneLoader namespace { // NOTE: values for BlendFactor aren't contiguous, hence we need a mapping. -const Dali::BlendFactor::Type kBlendFactors[] = { +const Dali::BlendFactor::Type kBlendFactors[] = { Dali::BlendFactor::ZERO, Dali::BlendFactor::ONE, Dali::BlendFactor::SRC_COLOR, @@ -41,7 +41,7 @@ const Dali::BlendFactor::Type kBlendFactors[] = { Dali::BlendFactor::CONSTANT_ALPHA, Dali::BlendFactor::ONE_MINUS_CONSTANT_ALPHA, }; -} +} // namespace namespace RendererState { @@ -55,48 +55,46 @@ void Apply(Type rendererState, Renderer& renderer) RENDERER_SET_PROPERTY(BLEND_MODE, MaskMatch(rendererState, ALPHA_BLEND) ? BlendMode::ON : BlendMode::OFF); const bool cullBack = MaskMatch(rendererState, CULL_BACK); - RENDERER_SET_PROPERTY(FACE_CULLING_MODE, MaskMatch(rendererState, CULL_FRONT) ? - (cullBack ? FaceCullingMode::FRONT_AND_BACK : FaceCullingMode::FRONT) : - (cullBack ? FaceCullingMode::BACK : FaceCullingMode::NONE)); + RENDERER_SET_PROPERTY(FACE_CULLING_MODE, MaskMatch(rendererState, CULL_FRONT) ? (cullBack ? FaceCullingMode::FRONT_AND_BACK : FaceCullingMode::FRONT) : (cullBack ? FaceCullingMode::BACK : FaceCullingMode::NONE)); - if (auto depthFunc = (rendererState & DEPTH_FUNCTION_MASK) >> DEPTH_FUNCTION_SHIFT) + if(auto depthFunc = (rendererState & DEPTH_FUNCTION_MASK) >> DEPTH_FUNCTION_SHIFT) { RENDERER_SET_PROPERTY(DEPTH_FUNCTION, static_cast(depthFunc - 1)); } - if (auto blendFactors = (rendererState & BLEND_FACTOR_MASK) >> BLEND_FACTOR_BASE_SHIFT) + if(auto blendFactors = (rendererState & BLEND_FACTOR_MASK) >> BLEND_FACTOR_BASE_SHIFT) { - if (auto srcRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK)) + if(auto srcRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK)) { RENDERER_SET_PROPERTY(BLEND_FACTOR_SRC_RGB, kBlendFactors[static_cast(srcRgb - 1)]); } blendFactors >>= BLEND_FACTOR_ITEM_BITS; - if (auto dstRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK)) + if(auto dstRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK)) { RENDERER_SET_PROPERTY(BLEND_FACTOR_DEST_RGB, kBlendFactors[static_cast(dstRgb - 1)]); } blendFactors >>= BLEND_FACTOR_ITEM_BITS; - if (auto srcAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK)) + if(auto srcAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK)) { RENDERER_SET_PROPERTY(BLEND_FACTOR_SRC_ALPHA, kBlendFactors[static_cast(srcAlpha - 1)]); } blendFactors >>= BLEND_FACTOR_ITEM_BITS; - if (auto dstAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK)) + if(auto dstAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK)) { RENDERER_SET_PROPERTY(BLEND_FACTOR_DEST_ALPHA, kBlendFactors[static_cast(dstAlpha - 1)]); } } - if (auto bufferMode = (rendererState & BUFFER_MODE_MASK) >> BUFFER_MODE_SHIFT) + if(auto bufferMode = (rendererState & BUFFER_MODE_MASK) >> BUFFER_MODE_SHIFT) { RENDERER_SET_PROPERTY(RENDER_MODE, static_cast(bufferMode - 1)); } } -} // RendererState +} // namespace RendererState -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/renderer-state.h b/dali-scene-loader/public-api/renderer-state.h index dc1bf63..f70100a 100644 --- a/dali-scene-loader/public-api/renderer-state.h +++ b/dali-scene-loader/public-api/renderer-state.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_RENDERER_STATE_H #define DALI_SCENE_LOADER_RENDERER_STATE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ namespace Dali { namespace SceneLoader { - /* * @brief Contains values for comparison functions used in depth and stencil testing. * @note Relative order of members must match DepthFunction::Type and StencilFunction::Type. @@ -36,7 +35,7 @@ struct DALI_SCENE_LOADER_API Comparison { enum Type { - OMIT, // not specified; will not be set. + OMIT, // not specified; will not be set. NEVER, ALWAYS, LESS, @@ -58,13 +57,13 @@ struct DALI_SCENE_LOADER_API BlendFactor { enum Type { - OMIT, // not specified - will not be updated + OMIT, // not specified - will not be updated ZERO, - ONE, // default for source alpha + ONE, // default for source alpha SRC_COLOR, ONE_MINUS_SRC_COLOR, - SRC_ALPHA, // default for source RGB - ONE_MINUS_SRC_ALPHA, // default for destination RGB and destination alpha + SRC_ALPHA, // default for source RGB + ONE_MINUS_SRC_ALPHA, // default for destination RGB and destination alpha DST_ALPHA, ONE_MINUS_DST_ALPHA, DST_COLOR, @@ -87,12 +86,12 @@ struct DALI_SCENE_LOADER_API BufferMode { enum Type { - OMIT, ///< not specified - will not be updated - NONE, ///< Don’t write to either color or stencil buffer (But will potentially render to depth buffer). - AUTO, ///< Writes are managed by the Actor Clipping API. This is DALi's default. - COLOR, ///< Ignore stencil properties. Write to the color buffer. - STENCIL, ///< Use the stencil properties. Do not write to the color buffer. - COLOR_STENCIL ///< Use the stencil properties AND Write to the color buffer. + OMIT, ///< not specified - will not be updated + NONE, ///< Don’t write to either color or stencil buffer (But will potentially render to depth buffer). + AUTO, ///< Writes are managed by the Actor Clipping API. This is DALi's default. + COLOR, ///< Ignore stencil properties. Write to the color buffer. + STENCIL, ///< Use the stencil properties. Do not write to the color buffer. + COLOR_STENCIL ///< Use the stencil properties AND Write to the color buffer. }; BufferMode() = delete; @@ -103,36 +102,35 @@ struct DALI_SCENE_LOADER_API BufferMode */ namespace RendererState { - -using Type = uint32_t; // 8 bits reserved for flags, 4 * 4 bit for blend factors, 4 bits for depth function +using Type = uint32_t; // 8 bits reserved for flags, 4 * 4 bit for blend factors, 4 bits for depth function enum DALI_SCENE_LOADER_API Value : Type { NONE = 0x0, DEPTH_WRITE = 0x01, - DEPTH_TEST = 0x02, + DEPTH_TEST = 0x02, CULL_FRONT = 0x04, - CULL_BACK = 0x08, + CULL_BACK = 0x08, ALPHA_BLEND = 0x10, DEPTH_FUNCTION_SHIFT = 6, - DEPTH_FUNCTION_BITS = 4, - DEPTH_FUNCTION_MASK = ((1 << DEPTH_FUNCTION_BITS) - 1) << DEPTH_FUNCTION_SHIFT, + DEPTH_FUNCTION_BITS = 4, + DEPTH_FUNCTION_MASK = ((1 << DEPTH_FUNCTION_BITS) - 1) << DEPTH_FUNCTION_SHIFT, BLEND_FACTOR_BASE_SHIFT = DEPTH_FUNCTION_SHIFT + DEPTH_FUNCTION_BITS, - BLEND_FACTOR_ITEM_BITS = 4, - BLEND_FACTOR_ITEMS = 4, - BLEND_FACTOR_BITS = BLEND_FACTOR_ITEM_BITS * BLEND_FACTOR_ITEMS, - BLEND_FACTOR_MASK = ((1 << BLEND_FACTOR_BITS) - 1) << BLEND_FACTOR_BASE_SHIFT, - BLEND_FACTOR_ITEM_MASK = (1 << BLEND_FACTOR_ITEM_BITS) - 1, // after rshifting by BLEND_FACTOR_BASE_SHIFT + BLEND_FACTOR_ITEM_BITS = 4, + BLEND_FACTOR_ITEMS = 4, + BLEND_FACTOR_BITS = BLEND_FACTOR_ITEM_BITS * BLEND_FACTOR_ITEMS, + BLEND_FACTOR_MASK = ((1 << BLEND_FACTOR_BITS) - 1) << BLEND_FACTOR_BASE_SHIFT, + BLEND_FACTOR_ITEM_MASK = (1 << BLEND_FACTOR_ITEM_BITS) - 1, // after rshifting by BLEND_FACTOR_BASE_SHIFT // Buffer mode is DALi's RenderMode, just to avoid too much conflation. - BUFFER_MODE_BITS = 3u, - BUFFER_MODE_SHIFT = 32u - BUFFER_MODE_BITS, // from end - BUFFER_MODE_MASK = ((1u << BUFFER_MODE_BITS) - 1u) << BUFFER_MODE_SHIFT, + BUFFER_MODE_BITS = 3u, + BUFFER_MODE_SHIFT = 32u - BUFFER_MODE_BITS, // from end + BUFFER_MODE_MASK = ((1u << BUFFER_MODE_BITS) - 1u) << BUFFER_MODE_SHIFT, DEFAULT = DEPTH_WRITE | DEPTH_TEST | CULL_BACK | (Comparison::LESS_EQUAL << DEPTH_FUNCTION_SHIFT), }; @@ -141,12 +139,11 @@ enum DALI_SCENE_LOADER_API Value : Type * @brief Encodes the given blend factors into a RenderMode value, maskable into other options, * passable into ApplyRenderMode(). */ -inline -DALI_SCENE_LOADER_API constexpr uint32_t FromBlendFactors(BlendFactor::Type srcRgb, BlendFactor::Type destRgb, - BlendFactor::Type srcAlpha, BlendFactor::Type destAlpha) +inline DALI_SCENE_LOADER_API constexpr uint32_t FromBlendFactors(BlendFactor::Type srcRgb, BlendFactor::Type destRgb, BlendFactor::Type srcAlpha, BlendFactor::Type destAlpha) { return (srcRgb | (destRgb << BLEND_FACTOR_ITEM_BITS) | (srcAlpha << (BLEND_FACTOR_ITEM_BITS * 2)) | - (destAlpha << (BLEND_FACTOR_ITEM_BITS * 3))) << BLEND_FACTOR_BASE_SHIFT; + (destAlpha << (BLEND_FACTOR_ITEM_BITS * 3))) + << BLEND_FACTOR_BASE_SHIFT; } /* @@ -157,9 +154,9 @@ DALI_SCENE_LOADER_API constexpr uint32_t FromBlendFactors(BlendFactor::Type srcR */ DALI_SCENE_LOADER_API void Apply(Type rendererState, Renderer& renderer); -} // RendererState +} // namespace RendererState -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_RENDERER_STATE_H diff --git a/dali-scene-loader/public-api/resource-bundle.cpp b/dali-scene-loader/public-api/resource-bundle.cpp index 9ff10f6..98b08bb 100644 --- a/dali-scene-loader/public-api/resource-bundle.cpp +++ b/dali-scene-loader/public-api/resource-bundle.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,11 @@ #include "dali-scene-loader/public-api/resource-bundle.h" // EXTERNAL -#include "dali/public-api/rendering/sampler.h" -#include "dali-toolkit/public-api/image-loader/sync-image-loader.h" -#include -#include #include #include +#include +#include "dali-toolkit/public-api/image-loader/sync-image-loader.h" +#include "dali/public-api/rendering/sampler.h" namespace Dali { @@ -34,7 +33,6 @@ namespace SceneLoader { namespace { - const char* const RESOURCE_TYPE_NAMES[] = { "Environment", "Shader", @@ -42,7 +40,7 @@ const char* const RESOURCE_TYPE_NAMES[] = { "Material", }; -} // nonamespace +} // namespace const char* GetResourceTypeName(ResourceType::Value type) { @@ -64,9 +62,9 @@ void ResourceBundle::CountEnvironmentReferences(ResourceRefCounts& refCounts) co auto& environmentRefCounts = refCounts[ResourceType::Environment]; const auto& materialRefs = refCounts[ResourceType::Material]; - for (uint32_t i = 0, iEnd = materialRefs.Size(); i != iEnd; ++i) + for(uint32_t i = 0, iEnd = materialRefs.Size(); i != iEnd; ++i) { - if (materialRefs[i] > 0) + if(materialRefs[i] > 0) { ++environmentRefCounts[mMaterials[i].first.mEnvironmentIdx]; } @@ -75,36 +73,36 @@ void ResourceBundle::CountEnvironmentReferences(ResourceRefCounts& refCounts) co void ResourceBundle::LoadResources(const ResourceRefCounts& refCounts, PathProvider pathProvider, Options::Type options) { - const auto kForceLoad = MaskMatch(options, Options::ForceReload); + const auto kForceLoad = MaskMatch(options, Options::ForceReload); const auto kKeepUnused = MaskMatch(options, Options::KeepUnused); - const auto& refCountEnvMaps = refCounts[ResourceType::Environment]; - auto environmentsPath = pathProvider(ResourceType::Environment); - for (uint32_t i = 0, iEnd = refCountEnvMaps.Size(); i != iEnd; ++i) + const auto& refCountEnvMaps = refCounts[ResourceType::Environment]; + auto environmentsPath = pathProvider(ResourceType::Environment); + for(uint32_t i = 0, iEnd = refCountEnvMaps.Size(); i != iEnd; ++i) { - auto refCount = refCountEnvMaps[i]; - auto& iEnvMap = mEnvironmentMaps[i]; - if (refCount > 0 && (kForceLoad || !iEnvMap.second.IsLoaded())) + auto refCount = refCountEnvMaps[i]; + auto& iEnvMap = mEnvironmentMaps[i]; + if(refCount > 0 && (kForceLoad || !iEnvMap.second.IsLoaded())) { - auto raw = iEnvMap.first.LoadRaw(environmentsPath); + auto raw = iEnvMap.first.LoadRaw(environmentsPath); iEnvMap.second = iEnvMap.first.Load(std::move(raw)); } - else if (!kKeepUnused && refCount == 0 && iEnvMap.second.IsLoaded()) + else if(!kKeepUnused && refCount == 0 && iEnvMap.second.IsLoaded()) { - iEnvMap.second.mDiffuse = Texture(); + iEnvMap.second.mDiffuse = Texture(); iEnvMap.second.mSpecular = Texture(); } } const auto& refCountShaders = refCounts[ResourceType::Shader]; - auto shadersPath = pathProvider(ResourceType::Shader); - for (uint32_t i = 0, iEnd = refCountShaders.Size(); i != iEnd; ++i) + auto shadersPath = pathProvider(ResourceType::Shader); + for(uint32_t i = 0, iEnd = refCountShaders.Size(); i != iEnd; ++i) { - auto refCount = refCountShaders[i]; - auto& iShader = mShaders[i]; - if (refCount > 0 && (kForceLoad || !iShader.second)) + auto refCount = refCountShaders[i]; + auto& iShader = mShaders[i]; + if(refCount > 0 && (kForceLoad || !iShader.second)) { - auto raw = iShader.first.LoadRaw(shadersPath); + auto raw = iShader.first.LoadRaw(shadersPath); iShader.second = iShader.first.Load(std::move(raw)); } else if(!kKeepUnused && refCount == 0 && iShader.second) @@ -114,39 +112,39 @@ void ResourceBundle::LoadResources(const ResourceRefCounts& refCounts, PathProvi } const auto& refCountMeshes = refCounts[ResourceType::Mesh]; - auto modelsPath = pathProvider(ResourceType::Mesh); - for (uint32_t i = 0, iEnd = refCountMeshes.Size(); i != iEnd; ++i) + auto modelsPath = pathProvider(ResourceType::Mesh); + for(uint32_t i = 0, iEnd = refCountMeshes.Size(); i != iEnd; ++i) { - auto refCount = refCountMeshes[i]; - auto& iMesh = mMeshes[i]; - if (refCount > 0 && (kForceLoad || !iMesh.second.geometry)) + auto refCount = refCountMeshes[i]; + auto& iMesh = mMeshes[i]; + if(refCount > 0 && (kForceLoad || !iMesh.second.geometry)) { - auto raw = iMesh.first.LoadRaw(modelsPath); + auto raw = iMesh.first.LoadRaw(modelsPath); iMesh.second = iMesh.first.Load(std::move(raw)); } - else if (!kKeepUnused && refCount == 0 && iMesh.second.geometry) + else if(!kKeepUnused && refCount == 0 && iMesh.second.geometry) { iMesh.second.geometry = Geometry(); } } const auto& refCountMaterials = refCounts[ResourceType::Material]; - auto imagesPath = pathProvider(ResourceType::Material); - for (uint32_t i = 0, iEnd = refCountMaterials.Size(); i != iEnd; ++i) + auto imagesPath = pathProvider(ResourceType::Material); + for(uint32_t i = 0, iEnd = refCountMaterials.Size(); i != iEnd; ++i) { - auto refCount = refCountMaterials[i]; + auto refCount = refCountMaterials[i]; auto& iMaterial = mMaterials[i]; - if (refCount > 0 && (kForceLoad || !iMaterial.second)) + if(refCount > 0 && (kForceLoad || !iMaterial.second)) { - auto raw = iMaterial.first.LoadRaw(imagesPath); + auto raw = iMaterial.first.LoadRaw(imagesPath); iMaterial.second = iMaterial.first.Load(mEnvironmentMaps, std::move(raw)); } - else if (!kKeepUnused && refCount == 0 && iMaterial.second) + else if(!kKeepUnused && refCount == 0 && iMaterial.second) { iMaterial.second = TextureSet(); } } } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/resource-bundle.h b/dali-scene-loader/public-api/resource-bundle.h index 16860ec..b1e0936 100644 --- a/dali-scene-loader/public-api/resource-bundle.h +++ b/dali-scene-loader/public-api/resource-bundle.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_RESOURCE_BUNDLE_H_ #define DALI_SCENE_LOADER_RESOURCE_BUNDLE_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,24 +18,23 @@ */ // INTERNAL -#include "dali-scene-loader/public-api/mesh-definition.h" -#include "dali-scene-loader/public-api/material-definition.h" #include "dali-scene-loader/public-api/environment-definition.h" +#include "dali-scene-loader/public-api/material-definition.h" +#include "dali-scene-loader/public-api/mesh-definition.h" #include "dali-scene-loader/public-api/shader-definition.h" #include "dali-scene-loader/public-api/skeleton-definition.h" // EXTERNAL +#include +#include #include "dali/public-api/common/vector-wrapper.h" #include "dali/public-api/rendering/shader.h" #include "dali/public-api/rendering/texture-set.h" -#include -#include namespace Dali { namespace SceneLoader { - /* * @brief The types of resources that .dli may define. */ @@ -73,9 +72,9 @@ public: enum Value : Type { - None = 0, - ForceReload = NthBit(0), ///< Load resources [again] even if they were already loaded. - KeepUnused = NthBit(1) /// sConstraintFactory = { - { - Property::Type::BOOLEAN, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, [](bool& current, const PropertyInputContainer& inputs) { - current = inputs[0]->GetBoolean(); - }); - } - }, - { - Property::Type::INTEGER, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, [](int& current, const PropertyInputContainer& inputs) { - current = inputs[0]->GetInteger(); - }); - } - }, - { - Property::Type::FLOAT, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::VECTOR2, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::VECTOR3, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::VECTOR4, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::MATRIX, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::MATRIX3, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::ROTATION, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, +const std::string JOINT_MATRIX{"jointMatrix"}; + +const std::map sConstraintFactory = { + {Property::Type::BOOLEAN, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, [](bool& current, const PropertyInputContainer& inputs) { + current = inputs[0]->GetBoolean(); + }); + }}, + {Property::Type::INTEGER, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, [](int& current, const PropertyInputContainer& inputs) { + current = inputs[0]->GetInteger(); + }); + }}, + {Property::Type::FLOAT, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::VECTOR2, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::VECTOR3, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::VECTOR4, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::MATRIX, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::MATRIX3, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::ROTATION, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, }; struct ResourceReflector : IResourceReflector { - Index* iMesh = nullptr; + Index* iMesh = nullptr; Index* iShader = nullptr; void Reflect(ResourceType::Value type, Index& id) { - switch (type) + switch(type) { - case ResourceType::Shader: - DALI_ASSERT_ALWAYS(!iShader && "Shader index already assigned!"); - iShader = &id; - break; + case ResourceType::Shader: + DALI_ASSERT_ALWAYS(!iShader && "Shader index already assigned!"); + iShader = &id; + break; - case ResourceType::Mesh: - DALI_ASSERT_ALWAYS(!iMesh && "Mesh index already assigned!"); - iMesh = &id; - break; + case ResourceType::Mesh: + DALI_ASSERT_ALWAYS(!iMesh && "Mesh index already assigned!"); + iMesh = &id; + break; - default: // Other resource types are not relevant to the problem at hand. - break; + default: // Other resource types are not relevant to the problem at hand. + break; } } }; - #ifdef DEBUG_JOINTS Shader sJointDebugShader; -int sNumScenes = 0; +int sNumScenes = 0; void EnsureJointDebugShaderCreated() { - if (0 == sNumScenes) + if(0 == sNumScenes) { sJointDebugShader = Shader::New(SHADER_SCENE_LOADER_JOINT_DEBUG_VERT, SHADER_SCENE_LOADER_JOINT_DEBUG_FRAG); } @@ -151,24 +131,24 @@ void AddJointDebugVisual(Actor aJoint) { Property::Map attribs; attribs["aPosition"] = Property::Type::VECTOR3; - attribs["aColor"] = Property::Type::FLOAT; + attribs["aColor"] = Property::Type::FLOAT; PropertyBuffer vbo = PropertyBuffer::New(attribs); struct Vertex { Vector3 pos; - float color; + float color; } vertices[] = { - { Vector3::ZERO, .999f + .999f * 256.f + .999f * 256.f * 256.f }, - { Vector3::XAXIS, .999f }, - { Vector3::YAXIS, .999f * 256.f }, - { Vector3::ZAXIS, .999f * 256.f * 256.f }, + {Vector3::ZERO, .999f + .999f * 256.f + .999f * 256.f * 256.f}, + {Vector3::XAXIS, .999f}, + {Vector3::YAXIS, .999f * 256.f}, + {Vector3::ZAXIS, .999f * 256.f * 256.f}, }; vbo.SetData(&vertices, std::extent::value); - uint16_t indices[] = { 0, 1, 0, 2, 0, 3 }; + uint16_t indices[] = {0, 1, 0, 2, 0, 3}; Geometry geo = Geometry::New(); geo.AddVertexBuffer(vbo); @@ -180,21 +160,22 @@ void AddJointDebugVisual(Actor aJoint) aJoint.SetVisible(true); } -#endif //DEBUG_JOINTS +#endif //DEBUG_JOINTS class ActorCreatorVisitor : public NodeDefinition::IConstVisitor { public: ActorCreatorVisitor(NodeDefinition::CreateParams& params) : mCreationContext(params) - {} + { + } void Start(const NodeDefinition& n) { mCreationContext.mXforms.modelStack.Push(n.GetLocalSpace()); Actor a = n.CreateActor(mCreationContext); - if (!mActorStack.empty()) + if(!mActorStack.empty()) { mActorStack.back().Add(a); } @@ -218,16 +199,16 @@ public: private: NodeDefinition::CreateParams& mCreationContext; - std::vector mActorStack; - Actor mRoot; + std::vector mActorStack; + Actor mRoot; }; bool IsAncestor(const SceneDefinition& scene, Index ancestor, Index node, Index rootHint = INVALID_INDEX) { bool isAncestor = false; - while (node != rootHint && !isAncestor) + while(node != rootHint && !isAncestor) { - node = scene.GetNode(node)->mParentIdx; + node = scene.GetNode(node)->mParentIdx; isAncestor = ancestor == node; } return isAncestor; @@ -236,7 +217,7 @@ bool IsAncestor(const SceneDefinition& scene, Index ancestor, Index node, Index void InsertUniqueSorted(std::vector& data, Index value) { auto iInsert = std::lower_bound(data.begin(), data.end(), value); - if (iInsert == data.end() || *iInsert != value) + if(iInsert == data.end() || *iInsert != value) { data.insert(iInsert, value); } @@ -245,7 +226,7 @@ void InsertUniqueSorted(std::vector& data, Index value) void RemoveFromSorted(std::vector& data, Index value) { auto iRemove = std::lower_bound(data.begin(), data.end(), value); - if (iRemove != data.end() && *iRemove == value) + if(iRemove != data.end() && *iRemove == value) { data.erase(iRemove); } @@ -254,26 +235,24 @@ void RemoveFromSorted(std::vector& data, Index value) Property::Index ConfigureJointMatrix(Actor actor, Actor ancestor, Property::Index propJointMatrix) { Actor parent = actor.GetParent(); - if (parent != ancestor) + if(parent != ancestor) { propJointMatrix = ConfigureJointMatrix(parent, ancestor, propJointMatrix); } auto myPropJointMatrix = actor.GetPropertyIndex(JOINT_MATRIX); - if (myPropJointMatrix == Property::INVALID_INDEX) + if(myPropJointMatrix == Property::INVALID_INDEX) { - myPropJointMatrix = actor.RegisterProperty(JOINT_MATRIX, Matrix{ false }); - Constraint constraint = Constraint::New(actor, propJointMatrix, - [](Matrix& output, const PropertyInputContainer& inputs) - { - Matrix jointMatrix{ false }; - jointMatrix.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3()); - - Matrix::Multiply(output, jointMatrix, inputs[2]->GetMatrix()); - }); - constraint.AddSource(Source{ actor, Actor::Property::ORIENTATION }); - constraint.AddSource(Source{ actor, Actor::Property::POSITION }); - constraint.AddSource(Source{ parent, propJointMatrix }); + myPropJointMatrix = actor.RegisterProperty(JOINT_MATRIX, Matrix{false}); + Constraint constraint = Constraint::New(actor, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) { + Matrix jointMatrix{false}; + jointMatrix.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3()); + + Matrix::Multiply(output, jointMatrix, inputs[2]->GetMatrix()); + }); + constraint.AddSource(Source{actor, Actor::Property::ORIENTATION}); + constraint.AddSource(Source{actor, Actor::Property::POSITION}); + constraint.AddSource(Source{parent, propJointMatrix}); constraint.Apply(); } @@ -286,38 +265,38 @@ void SortAndDeduplicateSkinningRequests(std::vectormShader; - Index skeletonIdx = i->mSkeletonIdx; + auto i = requests.begin(); + auto iEnd = requests.end(); + Shader s = i->mShader; + Index skeletonIdx = i->mSkeletonIdx; ++i; do { // Multiple identical shader instances are removed. - while (i != iEnd && i->mShader == s) + while(i != iEnd && i->mShader == s) { // Cannot have multiple skeletons input to the same shader. // NOTE: DliModel now makes sure this doesn't happen. DALI_ASSERT_ALWAYS(i->mSkeletonIdx == skeletonIdx && - "Skinning shader must not be shared between different skeletons."); + "Skinning shader must not be shared between different skeletons."); i->mShader = Shader(); ++i; } - if (i == iEnd) + if(i == iEnd) { break; } - s = i->mShader; + s = i->mShader; skeletonIdx = i->mSkeletonIdx; ++i; - } while (true); + } while(true); - requests.erase(std::remove_if(requests.begin(), requests.end(), [](const SkinningShaderConfigurationRequest& sscr) - { - return !sscr.mShader; - }), requests.end()); + requests.erase(std::remove_if(requests.begin(), requests.end(), [](const SkinningShaderConfigurationRequest& sscr) { + return !sscr.mShader; + }), + requests.end()); } void ConfigureBoneMatrix(const Matrix& ibm, Actor joint, Shader& shader, Index& boneIdx) @@ -326,40 +305,38 @@ void ConfigureBoneMatrix(const Matrix& ibm, Actor joint, Shader& shader, Index& char propertyNameBuffer[32]; snprintf(propertyNameBuffer, sizeof(propertyNameBuffer), "%s[%d]", Skinning::BONE_UNIFORM_NAME.c_str(), boneIdx); DALI_ASSERT_DEBUG(shader.GetPropertyIndex(propertyNameBuffer) == Property::INVALID_INDEX); - auto propBoneXform = shader.RegisterProperty(propertyNameBuffer, Matrix{ false }); + auto propBoneXform = shader.RegisterProperty(propertyNameBuffer, Matrix{false}); // Constrain bone matrix to joint transform. - Constraint constraint = Constraint::New(shader, propBoneXform, - [ibm](Matrix& output, const PropertyInputContainer& inputs) - { - Matrix::Multiply(output, ibm, inputs[0]->GetMatrix()); - }); + Constraint constraint = Constraint::New(shader, propBoneXform, [ibm](Matrix& output, const PropertyInputContainer& inputs) { + Matrix::Multiply(output, ibm, inputs[0]->GetMatrix()); + }); auto propJointMatrix = joint.GetPropertyIndex(JOINT_MATRIX); - constraint.AddSource(Source{ joint, propJointMatrix }); + constraint.AddSource(Source{joint, propJointMatrix}); constraint.Apply(); ++boneIdx; } -template +template void VisitInternal(Index iNode, const Customization::Choices& choices, Visitor& v, SceneDefinition& sd) { auto& node = *sd.GetNode(iNode); v.Start(node); - if (node.mCustomization) + if(node.mCustomization) { - if (!node.mChildren.empty()) + if(!node.mChildren.empty()) { - auto choice = choices.Get(node.mCustomization->mTag); - Index i = std::min(choice != Customization::NONE ? choice : 0, static_cast(node.mChildren.size() - 1)); + auto choice = choices.Get(node.mCustomization->mTag); + Index i = std::min(choice != Customization::NONE ? choice : 0, static_cast(node.mChildren.size() - 1)); sd.Visit(node.mChildren[i], choices, v); } } else { - for (auto i : node.mChildren) + for(auto i : node.mChildren) { sd.Visit(i, choices, v); } @@ -368,7 +345,7 @@ void VisitInternal(Index iNode, const Customization::Choices& choices, Visitor& v.Finish(node); } -} // nonamespace +} // namespace SceneDefinition::SceneDefinition() { @@ -392,7 +369,7 @@ SceneDefinition::~SceneDefinition() { #ifdef DEBUG_JOINTS --sNumScenes; - if (sNumScenes == 0) + if(sNumScenes == 0) { sJointDebugShader = Shader(); } @@ -401,7 +378,7 @@ SceneDefinition::~SceneDefinition() uint32_t SceneLoader::SceneDefinition::AddRootNode(Index iNode) { - if (iNode < mNodes.size()) + if(iNode < mNodes.size()) { uint32_t result = mRootNodeIds.size(); mRootNodeIds.push_back(iNode); @@ -421,7 +398,7 @@ const std::vector& SceneDefinition::GetRoots() const void SceneDefinition::RemoveRootNode(Index iRoot) { - if (iRoot < mRootNodeIds.size()) + if(iRoot < mRootNodeIds.size()) { mRootNodeIds.erase(mRootNodeIds.begin() + iRoot); } @@ -474,14 +451,15 @@ void SceneDefinition::CountResourceRefs(Index iNode, const Customization::Choice void Start(const NodeDefinition& n) { - if (n.mRenderable) + if(n.mRenderable) { n.mRenderable->RegisterResources(counter); } } void Finish(const NodeDefinition& n) - {} + { + } } refCounterVisitor; refCounterVisitor.counter.refCounts = &refCounts; @@ -489,8 +467,7 @@ void SceneDefinition::CountResourceRefs(Index iNode, const Customization::Choice Visit(iNode, choices, refCounterVisitor); } -Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices & choices, - NodeDefinition::CreateParams& params) const +Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices& choices, NodeDefinition::CreateParams& params) const { ActorCreatorVisitor actorCreatorVisitor(params); @@ -500,44 +477,46 @@ Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices & c } void SceneDefinition::GetCustomizationOptions(const Customization::Choices& choices, - Customization::Map& outCustomizationOptions, Customization::Choices* outMissingChoices) const + Customization::Map& outCustomizationOptions, + Customization::Choices* outMissingChoices) const { struct : NodeDefinition::IConstVisitor { - const Customization::Choices* choices; // choices that we know about. - Customization::Map* options; // tags are registered here. NO OWNERSHIP. - Customization::Choices* missingChoices; // tags will be registered with the default 0. NO OWNERSHIP. + const Customization::Choices* choices; // choices that we know about. + Customization::Map* options; // tags are registered here. NO OWNERSHIP. + Customization::Choices* missingChoices; // tags will be registered with the default 0. NO OWNERSHIP. void Start(const NodeDefinition& n) { - if (n.mCustomization) + if(n.mCustomization) { const std::string& tag = n.mCustomization->mTag; - if (missingChoices != nullptr && choices->Get(tag) == Customization::NONE) + if(missingChoices != nullptr && choices->Get(tag) == Customization::NONE) { missingChoices->Set(tag, 0); } auto customization = options->Get(tag); - if (!customization) + if(!customization) { customization = options->Set(tag, {}); } customization->nodes.push_back(n.mName); customization->numOptions = std::max(customization->numOptions, - static_cast(n.mChildren.size())); + static_cast(n.mChildren.size())); } } void Finish(const NodeDefinition& n) - {} + { + } } customizationRegistrationVisitor; - customizationRegistrationVisitor.choices = &choices; - customizationRegistrationVisitor.options = &outCustomizationOptions; + customizationRegistrationVisitor.choices = &choices; + customizationRegistrationVisitor.options = &outCustomizationOptions; customizationRegistrationVisitor.missingChoices = outMissingChoices; - for (auto i : mRootNodeIds) + for(auto i : mRootNodeIds) { Visit(i, choices, customizationRegistrationVisitor); } @@ -545,13 +524,13 @@ void SceneDefinition::GetCustomizationOptions(const Customization::Choices& choi NodeDefinition* SceneDefinition::AddNode(std::unique_ptr&& nodeDef) { - if (FindNode(nodeDef->mName)) + if(FindNode(nodeDef->mName)) { return nullptr; } // add next index (to which we're about to push) as a child to the designated parent, if any. - if (nodeDef->mParentIdx != INVALID_INDEX) + if(nodeDef->mParentIdx != INVALID_INDEX) { mNodes[nodeDef->mParentIdx]->mChildren.push_back(mNodes.size()); } @@ -565,20 +544,20 @@ bool SceneDefinition::ReparentNode(const std::string& name, const std::string& n { LOGD(("reparenting %s to %s @ %d", name.c_str(), newParentName.c_str(), siblingOrder)); - std::unique_ptr* nodePtr = nullptr; + std::unique_ptr* nodePtr = nullptr; std::unique_ptr* newParentPtr = nullptr; - if (!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr)) + if(!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr)) { return false; } - auto& node = *nodePtr; - auto iNode = std::distance(mNodes.data(), nodePtr); + auto& node = *nodePtr; + auto iNode = std::distance(mNodes.data(), nodePtr); DEBUG_ONLY(auto dumpNode = [](NodeDefinition const& n) { std::ostringstream stream; stream << n.mName << " (" << n.mParentIdx << "):"; - for (auto i : n.mChildren) + for(auto i : n.mChildren) { stream << i << ", "; } @@ -586,7 +565,7 @@ bool SceneDefinition::ReparentNode(const std::string& name, const std::string& n };) // Remove node from children of previous parent (if any). - if (node->mParentIdx != INVALID_INDEX) + if(node->mParentIdx != INVALID_INDEX) { LOGD(("old parent:")); DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);) @@ -601,7 +580,7 @@ bool SceneDefinition::ReparentNode(const std::string& name, const std::string& n LOGD(("new parent:")); DEBUG_ONLY(dumpNode(**newParentPtr);) auto& children = (*newParentPtr)->mChildren; - if (siblingOrder > children.size()) + if(siblingOrder > children.size()) { siblingOrder = children.size(); } @@ -611,7 +590,7 @@ bool SceneDefinition::ReparentNode(const std::string& name, const std::string& n // Update parent index. LOGD(("node:")); DEBUG_ONLY(dumpNode(*node);) - auto iParent = std::distance(mNodes.data(), newParentPtr); + auto iParent = std::distance(mNodes.data(), newParentPtr); node->mParentIdx = iParent; DEBUG_ONLY(dumpNode(*node);) return true; @@ -620,33 +599,33 @@ bool SceneDefinition::ReparentNode(const std::string& name, const std::string& n bool SceneDefinition::RemoveNode(const std::string& name) { std::unique_ptr* node = nullptr; - if (!FindNode(name, &node)) + if(!FindNode(name, &node)) { return false; } // Reset node def pointers recursively. - auto& thisNodes = mNodes; - unsigned int numReset = 0; + auto& thisNodes = mNodes; + unsigned int numReset = 0; std::function&)> resetFn = [&thisNodes, &resetFn, &numReset](std::unique_ptr& nd) { - LOGD(("resetting %d", &nd - thisNodes.data())); - for (auto i : nd->mChildren) - { - resetFn(thisNodes[i]); - } - nd.reset(); - ++numReset; - }; + LOGD(("resetting %d", &nd - thisNodes.data())); + for(auto i : nd->mChildren) + { + resetFn(thisNodes[i]); + } + nd.reset(); + ++numReset; + }; resetFn(*node); // Gather indices of dead nodes into a vector which we sort on insertion. std::vector offsets; offsets.reserve(numReset); - for (auto& n : mNodes) + for(auto& n : mNodes) { - if (!n) + if(!n) { offsets.push_back(std::distance(mNodes.data(), &n)); } @@ -656,10 +635,13 @@ bool SceneDefinition::RemoveNode(const std::string& name) mNodes.erase(std::remove(mNodes.begin(), mNodes.end(), decltype(mNodes)::value_type()), mNodes.end()); // Offset all indices (parent and child) by the index they'd sort into in offsets. - enum { INDEX_FOR_REMOVAL = INVALID_INDEX }; + enum + { + INDEX_FOR_REMOVAL = INVALID_INDEX + }; auto offsetter = [&offsets](Index& i) { auto iFind = std::lower_bound(offsets.begin(), offsets.end(), i); - if (iFind != offsets.end() && *iFind == i) + if(iFind != offsets.end() && *iFind == i) { LOGD(("marking %d for removal.", i)); i = INDEX_FOR_REMOVAL; @@ -668,7 +650,7 @@ bool SceneDefinition::RemoveNode(const std::string& name) else { auto distance = std::distance(offsets.begin(), iFind); - if (distance > 0) + if(distance > 0) { LOGD(("offsetting %d by %d.", i, distance)); i -= distance; @@ -677,13 +659,13 @@ bool SceneDefinition::RemoveNode(const std::string& name) } }; - for (auto& nd : mNodes) + for(auto& nd : mNodes) { bool parentOffsetResult = offsetter(nd->mParentIdx); - DALI_ASSERT_ALWAYS(parentOffsetResult); // since nodes were recursively removed, we should not be finding invalid parents at this point. + DALI_ASSERT_ALWAYS(parentOffsetResult); // since nodes were recursively removed, we should not be finding invalid parents at this point. auto& children = nd->mChildren; - for (auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0) + for(auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0) { offsetter(*i0); } @@ -696,10 +678,10 @@ bool SceneDefinition::RemoveNode(const std::string& name) void SceneDefinition::GetNodeModelStack(Index index, MatrixStack& model) const { - auto& thisNodes = mNodes; + auto& thisNodes = mNodes; std::function buildStack = [&model, &thisNodes, &buildStack](int i) { auto node = thisNodes[i].get(); - if (node->mParentIdx != INVALID_INDEX) + if(node->mParentIdx != INVALID_INDEX) { buildStack(node->mParentIdx); } @@ -708,32 +690,32 @@ void SceneDefinition::GetNodeModelStack(Index index, MatrixStack& model) const buildStack(index); } -NodeDefinition* SceneDefinition::FindNode(const std::string &name, Index* outIndex) +NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex) { auto iBegin = mNodes.begin(); - auto iEnd = mNodes.end(); - auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr& nd) { + auto iEnd = mNodes.end(); + auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr& nd) { return nd->mName == name; }); auto result = iFind != iEnd ? iFind->get() : nullptr; - if (result && outIndex) + if(result && outIndex) { *outIndex = std::distance(iBegin, iFind); } return result; } -const NodeDefinition* SceneDefinition::FindNode(const std::string &name, Index* outIndex) const +const NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex) const { auto iBegin = mNodes.begin(); - auto iEnd = mNodes.end(); - auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr& nd) { + auto iEnd = mNodes.end(); + auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr& nd) { return nd->mName == name; }); auto result = iFind != iEnd ? iFind->get() : nullptr; - if (result && outIndex) + if(result && outIndex) { *outIndex = std::distance(iBegin, iFind); } @@ -743,24 +725,23 @@ const NodeDefinition* SceneDefinition::FindNode(const std::string &name, Index* Index SceneDefinition::FindNodeIndex(const NodeDefinition& node) const { auto iBegin = mNodes.begin(); - auto iEnd = mNodes.end(); - auto iFind = std::find_if(iBegin, iEnd, [&node](const std::unique_ptr& n) { + auto iEnd = mNodes.end(); + auto iFind = std::find_if(iBegin, iEnd, [&node](const std::unique_ptr& n) { return n.get() == &node; }); return iFind != iEnd ? std::distance(iBegin, iFind) : INVALID_INDEX; } -void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, - unsigned int limit) +void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, unsigned int limit) { unsigned int n = 0; - for (auto& defp : mNodes) + for(auto& defp : mNodes) { - if (predicate(*defp)) + if(predicate(*defp)) { consumer(*defp); ++n; - if (n == limit) + if(n == limit) { break; } @@ -768,17 +749,16 @@ void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, } } -void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer, - unsigned int limit) const +void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer, unsigned int limit) const { unsigned int n = 0; - for (auto& defp : mNodes) + for(auto& defp : mNodes) { - if (predicate(*defp)) + if(predicate(*defp)) { consumer(*defp); ++n; - if (n == limit) + if(n == limit) { break; } @@ -786,51 +766,59 @@ void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consu } } -void SceneDefinition::ApplyConstraints(Actor& root, - std::vector&& constrainables, StringCallback onError) const +void SceneDefinition::ApplyConstraints(Actor& root, + std::vector&& constrainables, + StringCallback onError) const { - for (auto& cr : constrainables) + for(auto& cr : constrainables) { - auto& nodeDef = mNodes[cr.mConstraint->mSourceIdx]; - auto sourceName = nodeDef->mName.c_str(); - Property::Index iTarget = cr.mTarget.GetPropertyIndex(cr.mConstraint->mProperty); - if (iTarget != Property::INVALID_INDEX) + auto& nodeDef = mNodes[cr.mConstraint->mSourceIdx]; + auto sourceName = nodeDef->mName.c_str(); + Property::Index iTarget = cr.mTarget.GetPropertyIndex(cr.mConstraint->mProperty); + if(iTarget != Property::INVALID_INDEX) { auto propertyType = cr.mTarget.GetPropertyType(iTarget); - auto iFind = sConstraintFactory.find(propertyType); - if (iFind == sConstraintFactory.end()) + auto iFind = sConstraintFactory.find(propertyType); + if(iFind == sConstraintFactory.end()) { onError(FormatString("node '%s': Property '%s' has unsupported type '%s'; ignored.", - sourceName, cr.mConstraint->mProperty.c_str(), PropertyTypes::GetName(propertyType))); + sourceName, + cr.mConstraint->mProperty.c_str(), + PropertyTypes::GetName(propertyType))); continue; } Constraint constraint = iFind->second(cr.mTarget, iTarget); Actor source = root.FindChildByName(nodeDef->mName); - if (!source) + if(!source) { auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get(); onError(FormatString("node '%s': Failed to locate constraint source %s@%s; ignored.", - sourceName, cr.mConstraint->mProperty.c_str(), targetName.c_str())); + sourceName, + cr.mConstraint->mProperty.c_str(), + targetName.c_str())); continue; } - else if (source == cr.mTarget) + else if(source == cr.mTarget) { onError(FormatString("node '%s': Cyclic constraint definition for property '%s'; ignored.", - sourceName, cr.mConstraint->mProperty.c_str())); + sourceName, + cr.mConstraint->mProperty.c_str())); continue; } Property::Index iSource = source.GetPropertyIndex(cr.mConstraint->mProperty); - constraint.AddSource(Source{ source, iSource }); + constraint.AddSource(Source{source, iSource}); constraint.Apply(); } else { auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get(); onError(FormatString("node '%s': Failed to create constraint for property %s@%s; ignored.", - sourceName, cr.mConstraint->mProperty.c_str(), targetName.c_str())); + sourceName, + cr.mConstraint->mProperty.c_str(), + targetName.c_str())); } } } @@ -841,29 +829,28 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi // to the refcount of each node we have visited, in our temporary registry. Those with refcount 1 // are the leaves, while the most descendant node with the highest refcount is the root of the skeleton. std::map> rootsJoints; - std::vector path; + std::vector path; path.reserve(16); - for (auto& s : skeletons) + for(auto& s : skeletons) { - std::map jointRefs; - for (auto& j : s.mJoints) + std::map jointRefs; + for(auto& j : s.mJoints) { auto nodeIdx = j.mNodeIdx; do // Traverse upwards and record each node we have visited until we reach the scene root. { path.push_back(nodeIdx); - if (nodeIdx == iRoot) + if(nodeIdx == iRoot) { break; } auto node = GetNode(nodeIdx); - nodeIdx = node->mParentIdx; - } - while (nodeIdx != INVALID_INDEX); + nodeIdx = node->mParentIdx; + } while(nodeIdx != INVALID_INDEX); - if (nodeIdx == iRoot) // If the joint is in the correct scene, increment the reference count for all visited nodes. + if(nodeIdx == iRoot) // If the joint is in the correct scene, increment the reference count for all visited nodes. { - for (auto i : path) + for(auto i : path) { ++jointRefs[i]; } @@ -873,31 +860,31 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi } // Only record the skeleton if we have encountered the root of the current scene. - if (jointRefs.empty()) + if(jointRefs.empty()) { continue; } - Index root = s.mRootNodeIdx; + Index root = s.mRootNodeIdx; uint32_t maxRef = 0; - auto iFind = jointRefs.find(root); - if (iFind != jointRefs.end()) + auto iFind = jointRefs.find(root); + if(iFind != jointRefs.end()) { maxRef = iFind->second; } std::vector joints; - for (auto& j : jointRefs) // NOTE: jointRefs are sorted, so joints will also be. + for(auto& j : jointRefs) // NOTE: jointRefs are sorted, so joints will also be. { // The most descendant node with the highest ref count is the root of the skeleton. - if (j.second > maxRef || (j.second == maxRef && IsAncestor(*this, root, j.first, iRoot))) + if(j.second > maxRef || (j.second == maxRef && IsAncestor(*this, root, j.first, iRoot))) { maxRef = j.second; RemoveFromSorted(joints, root); root = j.first; } - else if (j.second == 1) // This one's a leaf. + else if(j.second == 1) // This one's a leaf. { InsertUniqueSorted(joints, j.first); } @@ -905,20 +892,20 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi // Merge skeletons that share the same root. auto& finalJoints = rootsJoints[root]; - for (auto j : joints) + for(auto j : joints) { - if (std::find_if(finalJoints.begin(), finalJoints.end(), [this, j, root](Index jj) { - return IsAncestor(*this, j, jj, root); - }) != finalJoints.end()) + if(std::find_if(finalJoints.begin(), finalJoints.end(), [this, j, root](Index jj) { + return IsAncestor(*this, j, jj, root); + }) != finalJoints.end()) { - continue; // if the joint is found to be an ancestor of another joint already registered, move on. + continue; // if the joint is found to be an ancestor of another joint already registered, move on. } auto i = j; - while (i != root) // See if the current joint is a better leaf, i.e. descended from another leaf - which we'll then remove. + while(i != root) // See if the current joint is a better leaf, i.e. descended from another leaf - which we'll then remove. { auto node = GetNode(i); - i = node->mParentIdx; + i = node->mParentIdx; RemoveFromSorted(finalJoints, i); } @@ -929,42 +916,43 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi // 2, Merge records where one root joint is descendant of another. Handle leaf node changes - remove previous // leaf nodes that now have descendants, and add new ones. - auto iRoots = rootsJoints.begin(); + auto iRoots = rootsJoints.begin(); auto iRootsEnd = rootsJoints.end(); - while (iRoots != iRootsEnd) + while(iRoots != iRootsEnd) { - auto i = iRoots->first; + auto i = iRoots->first; bool merged = false; - while (i != iRoot) // Starting with the root joint of the skeleton, traverse upwards. + while(i != iRoot) // Starting with the root joint of the skeleton, traverse upwards. { auto node = GetNode(i); - i = node->mParentIdx; + i = node->mParentIdx; auto iFind = rootsJoints.find(i); - if (iFind != rootsJoints.end()) // Check if we've reached the root of another skeleton. + if(iFind != rootsJoints.end()) // Check if we've reached the root of another skeleton. { // Now find out which leaf of iFind is an ancestor, if any. auto iFindLeaf = std::find_if(iFind->second.begin(), iFind->second.end(), [this, iRoots, iFind](Index j) { return IsAncestor(*this, j, iRoots->first, iFind->first); }); - if (iFindLeaf != iFind->second.end()) + if(iFindLeaf != iFind->second.end()) { - iFind->second.erase(iFindLeaf); // Will no longer be a leaf -- remove it. + iFind->second.erase(iFindLeaf); // Will no longer be a leaf -- remove it. } // Merge iRoots with iFind auto& targetJoints = iFind->second; - if (iRoots->second.empty()) // The root is a leaf. + if(iRoots->second.empty()) // The root is a leaf. { InsertUniqueSorted(targetJoints, iRoots->first); } - else for (auto j : iRoots->second) - { - InsertUniqueSorted(targetJoints, j); - } + else + for(auto j : iRoots->second) + { + InsertUniqueSorted(targetJoints, j); + } merged = true; - break; // Traverse no more + break; // Traverse no more } } @@ -972,26 +960,24 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi } // 3, For each root, register joint matrices and constraints - for (auto r : rootsJoints) + for(auto r : rootsJoints) { - auto node = GetNode(r.first); + auto node = GetNode(r.first); auto rootJoint = root.FindChildByName(node->mName); DALI_ASSERT_ALWAYS(!!rootJoint); DALI_ASSERT_DEBUG(rootJoint.GetPropertyIndex(JOINT_MATRIX) == Property::INVALID_INDEX); - auto propJointMatrix = rootJoint.RegisterProperty(JOINT_MATRIX, Matrix{ false }); - Constraint constraint = Constraint::New(rootJoint, propJointMatrix, - [](Matrix& output, const PropertyInputContainer& inputs) - { - output.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3()); - }); + auto propJointMatrix = rootJoint.RegisterProperty(JOINT_MATRIX, Matrix{false}); + Constraint constraint = Constraint::New(rootJoint, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) { + output.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3()); + }); constraint.AddSource(Source(rootJoint, Actor::Property::ORIENTATION)); constraint.AddSource(Source(rootJoint, Actor::Property::POSITION)); constraint.Apply(); - for (auto j : r.second) + for(auto j : r.second) { - node = GetNode(j); + node = GetNode(j); auto joint = rootJoint.FindChildByName(node->mName); ConfigureJointMatrix(joint, rootJoint, propJointMatrix); } @@ -1001,17 +987,17 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resources) const { std::map>> skinningShaderUsers; - for (auto& node : mNodes) + for(auto& node : mNodes) { - if (node->mRenderable) + if(node->mRenderable) { ResourceReflector reflector; node->mRenderable->ReflectResources(reflector); - if (reflector.iMesh) + if(reflector.iMesh) { const auto& mesh = resources.mMeshes[*reflector.iMesh].first; - if (mesh.IsSkinned()) + if(mesh.IsSkinned()) { skinningShaderUsers[*reflector.iShader][mesh.mSkeletonIdx].push_back(reflector.iShader); } @@ -1022,22 +1008,22 @@ void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resour // For each shader, and each skeleton using the same shader as the first skeleton, // update the shader references (from nodes with skinned meshes) with a new copy of // the shader definition from the node using the first skeleton. - for (auto& users : skinningShaderUsers) + for(auto& users : skinningShaderUsers) { - auto& skeletons = users.second; - auto iterSkeleton = skeletons.begin(); + auto& skeletons = users.second; + auto iterSkeleton = skeletons.begin(); // skipping the first skeleton. ++iterSkeleton; resources.mShaders.reserve(resources.mShaders.size() + std::distance(iterSkeleton, skeletons.end())); const ShaderDefinition& shaderDef = resources.mShaders[users.first].first; - while (iterSkeleton != skeletons.end()) + while(iterSkeleton != skeletons.end()) { Index iShader = resources.mShaders.size(); - resources.mShaders.push_back({ shaderDef, Shader() }); + resources.mShaders.push_back({shaderDef, Shader()}); - for (auto& i : iterSkeleton->second) + for(auto& i : iterSkeleton->second) { *i = iShader; } @@ -1046,40 +1032,42 @@ void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resour } } -void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle& resources, - Actor rootActor, std::vector&& requests) const +void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle& resources, + Actor rootActor, + std::vector&& requests) const { - if (requests.empty()) + if(requests.empty()) { return; } SortAndDeduplicateSkinningRequests(requests); - for (auto& i : requests) + for(auto& i : requests) { auto& skeleton = resources.mSkeletons[i.mSkeletonIdx]; - if (skeleton.mJoints.empty()) + if(skeleton.mJoints.empty()) { LOGD(("Skeleton %d has no joints.", i.mSkeletonIdx)); continue; } Index boneIdx = 0; - for (auto& j : skeleton.mJoints) + for(auto& j : skeleton.mJoints) { - auto node = GetNode(j.mNodeIdx); + auto node = GetNode(j.mNodeIdx); Actor actor = rootActor.FindChildByName(node->mName); ConfigureBoneMatrix(j.mInverseBindMatrix, actor, i.mShader, boneIdx); } } } -bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources, - Actor rootActor, std::vector&& requests, - StringCallback onError ) const +bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources, + Actor rootActor, + std::vector&& requests, + StringCallback onError) const { - if (requests.empty()) + if(requests.empty()) { return true; } @@ -1088,45 +1076,45 @@ bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources std::sort(requests.begin(), requests.end()); // Remove duplicates. - auto i = requests.begin(); - auto iEnd = requests.end(); - Shader s = i->mShader; + auto i = requests.begin(); + auto iEnd = requests.end(); + Shader s = i->mShader; ++i; do { // Multiple identical shader instances are removed. - while (i != iEnd && i->mShader == s) + while(i != iEnd && i->mShader == s) { i->mShader = Shader(); ++i; } - if (i == iEnd) + if(i == iEnd) { break; } s = i->mShader; ++i; - } while (true); + } while(true); - requests.erase(std::remove_if(requests.begin(), requests.end(), [](const BlendshapeShaderConfigurationRequest& bscr) - { - return !bscr.mShader; - }), requests.end()); + requests.erase(std::remove_if(requests.begin(), requests.end(), [](const BlendshapeShaderConfigurationRequest& bscr) { + return !bscr.mShader; + }), + requests.end()); // Configure the rest. bool ok = true; - for (auto& i : requests) + for(auto& i : requests) { Index iNode; - if (FindNode(i.mNodeName, &iNode)) + if(FindNode(i.mNodeName, &iNode)) { const auto& node = GetNode(iNode); const auto& mesh = resources.mMeshes[i.mMeshIdx]; - if (mesh.first.HasBlendShapes()) + if(mesh.first.HasBlendShapes()) { Actor actor = rootActor.FindChildByName(node->mName); @@ -1142,17 +1130,17 @@ bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources void SceneDefinition::EnsureUniqueBlendShapeShaderInstances(ResourceBundle& resources) const { std::map>> blendShapeShaderUsers; - for (auto& node : mNodes) + for(auto& node : mNodes) { - if (node->mRenderable) + if(node->mRenderable) { ResourceReflector reflector; node->mRenderable->ReflectResources(reflector); - if (reflector.iMesh) + if(reflector.iMesh) { const auto& mesh = resources.mMeshes[*reflector.iMesh].first; - if (mesh.HasBlendShapes()) + if(mesh.HasBlendShapes()) { blendShapeShaderUsers[*reflector.iShader][node->mName].push_back(reflector.iShader); } @@ -1160,22 +1148,22 @@ void SceneDefinition::EnsureUniqueBlendShapeShaderInstances(ResourceBundle& reso } } - for (auto& users : blendShapeShaderUsers) + for(auto& users : blendShapeShaderUsers) { resources.mShaders.reserve(resources.mShaders.size() + users.second.size() - 1u); const ShaderDefinition& shaderDef = resources.mShaders[users.first].first; - auto nodesIt = users.second.begin(); + auto nodesIt = users.second.begin(); auto nodesEndIt = users.second.end(); // skipping the first node. ++nodesIt; while(nodesIt != nodesEndIt) { Index iShader = resources.mShaders.size(); - resources.mShaders.push_back({ shaderDef, Shader() }); + resources.mShaders.push_back({shaderDef, Shader()}); auto& nodes = *nodesIt; - for (auto& shader : nodes.second) + for(auto& shader : nodes.second) { *shader = iShader; } @@ -1197,13 +1185,12 @@ bool SceneDefinition::FindNode(const std::string& name, std::unique_ptr& nd) { - return nd->mName == name; - }).base(); + auto iFind = std::find_if(mNodes.rbegin(), mNodes.rend(), [&name](const std::unique_ptr& nd) { + return nd->mName == name; + }).base(); const bool success = iFind != mNodes.begin(); - if (success && result) + if(success && result) { --iFind; *result = &*iFind; @@ -1212,5 +1199,5 @@ bool SceneDefinition::FindNode(const std::string& name, std::unique_ptr +#include +#include "dali/public-api/actors/actor.h" #include "dali/public-api/math/matrix.h" +#include "dali/public-api/math/quaternion.h" #include "dali/public-api/math/vector4.h" -#include "dali/public-api/actors/actor.h" -#include -#include namespace Dali { namespace SceneLoader { - class MatrixStack; /* @@ -44,9 +43,9 @@ class MatrixStack; */ class DALI_SCENE_LOADER_API SceneDefinition { -public: // TYPES - using NodePredicate = std::function; - using NodeConsumer = std::function; +public: // TYPES + using NodePredicate = std::function; + using NodeConsumer = std::function; using ConstNodeConsumer = std::function; public: // METHODS @@ -112,8 +111,7 @@ public: // METHODS * from node definitions. * @return Handle to the root actor. */ - Actor CreateNodes(Index iNode, const Customization::Choices& choices, - NodeDefinition::CreateParams& params) const; + Actor CreateNodes(Index iNode, const Customization::Choices& choices, NodeDefinition::CreateParams& params) const; /* * @brief Creates / update a registry of mappings from customization tags to @@ -123,8 +121,8 @@ public: // METHODS * choice of 0. */ void GetCustomizationOptions(const Customization::Choices& choices, - Customization::Map& outCustomizationOptions, - Customization::Choices* outMissingChoices) const; + Customization::Map& outCustomizationOptions, + Customization::Choices* outMissingChoices) const; /* * @brief Attempts to add @a nodeDef to the end of nodes, and its index to the end of @@ -198,9 +196,9 @@ public: // METHODS /* * @brief Applies constraints from the given requests. */ - void ApplyConstraints(Actor& root, - std::vector&& constrainables, - StringCallback onError = DefaultErrorCallback) const; + void ApplyConstraints(Actor& root, + std::vector&& constrainables, + StringCallback onError = DefaultErrorCallback) const; /* * @brief Sets up joint matrix properties and constraints on actors that are involved in skeletal @@ -239,8 +237,9 @@ public: // METHODS * of separate instances need to be declared in the .dli to avoid clashing uniform * definitions and constraints. */ - void ConfigureSkinningShaders(const ResourceBundle& resources, - Actor root, std::vector&& requests) const; + void ConfigureSkinningShaders(const ResourceBundle& resources, + Actor root, + std::vector&& requests) const; /* * @brief Ensures there is no two meshes with blend shapes sharing the same shader. @@ -258,21 +257,22 @@ public: // METHODS * @param[in] resources The resources bundle. Meshes need to be accessed to configure the blend shapes. * @param[in] onError The error callback. */ - bool ConfigureBlendshapeShaders(const ResourceBundle& resources, - Actor root, std::vector&& requests, - StringCallback onError = DefaultErrorCallback) const; + bool ConfigureBlendshapeShaders(const ResourceBundle& resources, + Actor root, + std::vector&& requests, + StringCallback onError = DefaultErrorCallback) const; SceneDefinition& operator=(SceneDefinition&& other); private: // METHODS bool FindNode(const std::string& name, std::unique_ptr** result); -private: // DATA - std::vector> mNodes; // size unknown up front (may discard nodes). - std::vector mRootNodeIds; +private: // DATA + std::vector> mNodes; // size unknown up front (may discard nodes). + std::vector mRootNodeIds; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_SCENE_DEFINITION_H_ diff --git a/dali-scene-loader/public-api/shader-definition-factory.cpp b/dali-scene-loader/public-api/shader-definition-factory.cpp index f0a2ad8..843fbcf 100644 --- a/dali-scene-loader/public-api/shader-definition-factory.cpp +++ b/dali-scene-loader/public-api/shader-definition-factory.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,12 +14,12 @@ * limitations under the License. * */ -#include "dali-scene-loader/internal/hash.h" #include "dali-scene-loader/public-api/shader-definition-factory.h" -#include "dali-scene-loader/public-api/node-definition.h" +#include +#include "dali-scene-loader/internal/hash.h" #include "dali-scene-loader/public-api/blend-shape-details.h" +#include "dali-scene-loader/public-api/node-definition.h" #include "dali/devel-api/common/map-wrapper.h" -#include namespace Dali { @@ -29,28 +29,29 @@ namespace { struct ResourceReceiver : IResourceReceiver { - const ResourceBundle& mResources; - const MeshDefinition* mMeshDef = nullptr; + const ResourceBundle& mResources; + const MeshDefinition* mMeshDef = nullptr; const MaterialDefinition* mMaterialDef = nullptr; ResourceReceiver(const ResourceBundle& resources) : mResources(resources) - {} + { + } void Register(ResourceType::Value type, Index id) override { - switch (type) + switch(type) { - case ResourceType::Mesh: - mMeshDef = &mResources.mMeshes[id].first; - break; + case ResourceType::Mesh: + mMeshDef = &mResources.mMeshes[id].first; + break; - case ResourceType::Material: - mMaterialDef = &mResources.mMaterials[id].first; - break; + case ResourceType::Material: + mMaterialDef = &mResources.mMaterials[id].first; + break; - default: - break; + default: + break; } } }; @@ -59,11 +60,11 @@ const std::string PBR_SHADER_NAME = "dli_pbr"; void RetrieveBlendShapeComponents(const std::vector& blendShapes, bool& hasPositions, bool& hasNormals, bool& hasTangents) { - for (const auto& blendShape : blendShapes) + for(const auto& blendShape : blendShapes) { hasPositions = hasPositions || blendShape.deltas.IsDefined(); - hasNormals = hasNormals || blendShape.normals.IsDefined(); - hasTangents = hasTangents || blendShape.tangents.IsDefined(); + hasNormals = hasNormals || blendShape.normals.IsDefined(); + hasTangents = hasTangents || blendShape.tangents.IsDefined(); } } @@ -77,65 +78,65 @@ uint64_t HashNode(const NodeDefinition& nodeDef, const MaterialDefinition& mater const bool hasTransparency = MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY); hash.Add(hasTransparency); - if (hasTransparency || - materialDef.CheckTextures(MaterialDefinition::ALBEDO) || - materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) || - materialDef.CheckTextures(MaterialDefinition::NORMAL)) + if(hasTransparency || + materialDef.CheckTextures(MaterialDefinition::ALBEDO) || + materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) || + materialDef.CheckTextures(MaterialDefinition::NORMAL)) { hash.Add("3TEX"); } - if (materialDef.GetAlphaCutoff() > 0.f) + if(materialDef.GetAlphaCutoff() > 0.f) { - hash.Add("ALPH"/*A_TEST*/); + hash.Add("ALPH" /*A_TEST*/); } - if (MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE)) { hash.Add("SSS"); } - if (MaskMatch(materialDef.mFlags, MaterialDefinition::GLTF_CHANNELS)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::GLTF_CHANNELS)) { - hash.Add("GLTF"/*_CHANNELS*/); + hash.Add("GLTF" /*_CHANNELS*/); } - if (meshDef.IsSkinned()) + if(meshDef.IsSkinned()) { - hash.Add("SKIN"/*NING*/); + hash.Add("SKIN" /*NING*/); } - if (MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL)) + if(MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL)) { - hash.Add("FLIP"/*_V*/); + hash.Add("FLIP" /*_V*/); } - if (meshDef.HasBlendShapes()) + if(meshDef.HasBlendShapes()) { bool hasPositions = false; - bool hasNormals = false; - bool hasTangents = false; + bool hasNormals = false; + bool hasTangents = false; RetrieveBlendShapeComponents(meshDef.mBlendShapes, hasPositions, hasNormals, hasTangents); - if (hasPositions) + if(hasPositions) { hash.Add("MORPHPOS"); } - if (hasNormals) + if(hasNormals) { hash.Add("MORPHNOR"); } - if (hasTangents) + if(hasTangents) { hash.Add("MORPHTAN"); } - if (hasPositions || hasNormals || hasTangents) + if(hasPositions || hasNormals || hasTangents) { hash.Add("MORPH"); - if (BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion) + if(BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion) { hash.Add("MORPHV2"); } @@ -144,17 +145,18 @@ uint64_t HashNode(const NodeDefinition& nodeDef, const MaterialDefinition& mater return hash; } -} +} // namespace struct ShaderDefinitionFactory::Impl { - ResourceBundle* mResources; // no ownership + ResourceBundle* mResources; // no ownership std::map mShaderMap; }; ShaderDefinitionFactory::ShaderDefinitionFactory() -: mImpl{ new Impl() } -{} +: mImpl{new Impl()} +{ +} ShaderDefinitionFactory::~ShaderDefinitionFactory() = default; @@ -168,106 +170,106 @@ Index ShaderDefinitionFactory::ProduceShader(const NodeDefinition& nodeDef) { DALI_ASSERT_DEBUG(nodeDef.mRenderable); - auto& resources = *mImpl->mResources; - ResourceReceiver receiver{ resources }; + auto& resources = *mImpl->mResources; + ResourceReceiver receiver{resources}; nodeDef.mRenderable->RegisterResources(receiver); - if (!(receiver.mMeshDef && receiver.mMaterialDef)) + if(!(receiver.mMeshDef && receiver.mMaterialDef)) { return INVALID_INDEX; } - auto& shaderMap = mImpl->mShaderMap; - uint64_t hash = HashNode(nodeDef, *receiver.mMaterialDef, *receiver.mMeshDef); - auto iFind = shaderMap.find(hash); - if (iFind != shaderMap.end()) + auto& shaderMap = mImpl->mShaderMap; + uint64_t hash = HashNode(nodeDef, *receiver.mMaterialDef, *receiver.mMeshDef); + auto iFind = shaderMap.find(hash); + if(iFind != shaderMap.end()) { return iFind->second; } ShaderDefinition shaderDef; - shaderDef.mVertexShaderPath = PBR_SHADER_NAME + ".vsh"; + shaderDef.mVertexShaderPath = PBR_SHADER_NAME + ".vsh"; shaderDef.mFragmentShaderPath = PBR_SHADER_NAME + ".fsh"; - shaderDef.mRendererState = RendererState::DEPTH_TEST | RendererState::DEPTH_WRITE | RendererState::CULL_BACK; + shaderDef.mRendererState = RendererState::DEPTH_TEST | RendererState::DEPTH_WRITE | RendererState::CULL_BACK; - auto& materialDef = *receiver.mMaterialDef; + auto& materialDef = *receiver.mMaterialDef; const bool hasTransparency = MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY); - if (hasTransparency) + if(hasTransparency) { // TODO: this requires more granularity shaderDef.mRendererState = (shaderDef.mRendererState | RendererState::ALPHA_BLEND) & ~RendererState::DEPTH_WRITE; } - if (hasTransparency || - materialDef.CheckTextures(MaterialDefinition::ALBEDO) || - materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) || - materialDef.CheckTextures(MaterialDefinition::NORMAL)) + if(hasTransparency || + materialDef.CheckTextures(MaterialDefinition::ALBEDO) || + materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) || + materialDef.CheckTextures(MaterialDefinition::NORMAL)) { shaderDef.mDefines.push_back("THREE_TEX"); } - if (materialDef.GetAlphaCutoff() > 0.f) + if(materialDef.GetAlphaCutoff() > 0.f) { shaderDef.mDefines.push_back("ALPHA_TEST"); } - if (MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE)) { shaderDef.mDefines.push_back("SSS"); } - if (MaskMatch(receiver.mMaterialDef->mFlags, MaterialDefinition::GLTF_CHANNELS)) + if(MaskMatch(receiver.mMaterialDef->mFlags, MaterialDefinition::GLTF_CHANNELS)) { shaderDef.mDefines.push_back("GLTF_CHANNELS"); } const auto& meshDef = *receiver.mMeshDef; - if (meshDef.IsSkinned()) + if(meshDef.IsSkinned()) { shaderDef.mDefines.push_back("SKINNING"); } - if (MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL)) + if(MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL)) { shaderDef.mDefines.push_back("FLIP_V"); } - if (meshDef.HasBlendShapes()) + if(meshDef.HasBlendShapes()) { bool hasPositions = false; - bool hasNormals = false; - bool hasTangents = false; + bool hasNormals = false; + bool hasTangents = false; RetrieveBlendShapeComponents(meshDef.mBlendShapes, hasPositions, hasNormals, hasTangents); - if (hasPositions) + if(hasPositions) { shaderDef.mDefines.push_back("MORPH_POSITION"); } - if (hasNormals) + if(hasNormals) { shaderDef.mDefines.push_back("MORPH_NORMAL"); } - if (hasTangents) + if(hasTangents) { shaderDef.mDefines.push_back("MORPH_TANGENT"); } - if (hasPositions || hasNormals || hasTangents) + if(hasPositions || hasNormals || hasTangents) { shaderDef.mDefines.push_back("MORPH"); - if (BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion) + if(BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion) { shaderDef.mDefines.push_back("MORPH_VERSION_2_0"); } } } - shaderDef.mUniforms["uMaxLOD"] = 6.f; + shaderDef.mUniforms["uMaxLOD"] = 6.f; shaderDef.mUniforms["uCubeMatrix"] = Matrix::IDENTITY; - Index result = resources.mShaders.size(); + Index result = resources.mShaders.size(); shaderMap[hash] = result; resources.mShaders.emplace_back(std::move(shaderDef), Shader()); @@ -275,5 +277,5 @@ Index ShaderDefinitionFactory::ProduceShader(const NodeDefinition& nodeDef) return result; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/shader-definition-factory.h b/dali-scene-loader/public-api/shader-definition-factory.h index 4f55bbe..387984d 100644 --- a/dali-scene-loader/public-api/shader-definition-factory.h +++ b/dali-scene-loader/public-api/shader-definition-factory.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_SHADER_DEFINITION_FACTORY_H_ #define DALI_SCENE_LOADER_SHADER_DEFINITION_FACTORY_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ */ // INTERNAL INCLUDES -#include "dali-scene-loader/public-api/index.h" #include "dali-scene-loader/public-api/api.h" +#include "dali-scene-loader/public-api/index.h" // EXTERNAL INCLUDER #include @@ -28,7 +28,6 @@ namespace Dali { namespace SceneLoader { - struct NodeDefinition; class ResourceBundle; @@ -57,7 +56,7 @@ private: const std::unique_ptr mImpl; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_SHADER_DEFINITION_FACTORY_H_ diff --git a/dali-scene-loader/public-api/shader-definition.cpp b/dali-scene-loader/public-api/shader-definition.cpp index 5fbec33..73c18ba 100644 --- a/dali-scene-loader/public-api/shader-definition.cpp +++ b/dali-scene-loader/public-api/shader-definition.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,11 +25,10 @@ namespace SceneLoader { namespace { - const std::string SHADER_HINT_OUTPUT_IS_TRANSPARENT("OUTPUT_IS_TRANSPARENT"); ///< Might generate transparent alpha from opaque inputs. -const std::string SHADER_HINT_MODIFIES_GEOMETRY("MODIFIES_GEOMETRY"); ///< Might change position of vertices, this option disables any culling optimizations. +const std::string SHADER_HINT_MODIFIES_GEOMETRY("MODIFIES_GEOMETRY"); ///< Might change position of vertices, this option disables any culling optimizations. -} +} // namespace ShaderDefinition::ShaderDefinition(const ShaderDefinition& other) : mRendererState(other.mRendererState), @@ -38,31 +37,32 @@ ShaderDefinition::ShaderDefinition(const ShaderDefinition& other) mDefines(other.mDefines), mHints(other.mHints), mUniforms(other.mUniforms) -{} +{ +} void ShaderDefinition::ApplyDefine(std::string& shaderCode, const std::string& definevar) { const std::string IF_1 = "#if 1"; std::size_t found = shaderCode.find(definevar); - while (found != std::string::npos) + while(found != std::string::npos) { // Greater then "@" character means is a letter, // therefore is not has the definevar we looking for. - if ((found + definevar.length()) < shaderCode.length() && shaderCode.at(found + definevar.length()) > '@') + if((found + definevar.length()) < shaderCode.length() && shaderCode.at(found + definevar.length()) > '@') { found = shaderCode.find(definevar, found + definevar.length()); continue; } - if (found > 0u && shaderCode.at(found - 1) > '@') + if(found > 0u && shaderCode.at(found - 1) > '@') { found = shaderCode.find(definevar, found + definevar.length()); continue; } - std::size_t defidx = shaderCode.rfind("#ifdef", found); + std::size_t defidx = shaderCode.rfind("#ifdef", found); std::size_t newlineidx = shaderCode.rfind("\n", found); - if (newlineidx < defidx && defidx != std::string::npos) + if(newlineidx < defidx && defidx != std::string::npos) { shaderCode.replace(defidx, found - defidx + definevar.length(), IF_1); found = defidx + IF_1.length(); @@ -76,18 +76,18 @@ void ShaderDefinition::ApplyDefine(std::string& shaderCode, const std::string& d } ShaderDefinition::RawData - ShaderDefinition::LoadRaw(const std::string& shadersPath) const +ShaderDefinition::LoadRaw(const std::string& shadersPath) const { RawData raw; - bool fail = false; + bool fail = false; raw.mVertexShaderSource = LoadTextFile((shadersPath + mVertexShaderPath).c_str(), &fail); - if (!fail) + if(!fail) { raw.mFragmentShaderSource = LoadTextFile((shadersPath + mFragmentShaderPath).c_str(), &fail); - if (!fail) + if(!fail) { - for (auto definevar : mDefines) + for(auto definevar : mDefines) { ApplyDefine(raw.mVertexShaderSource, definevar); ApplyDefine(raw.mFragmentShaderSource, definevar); @@ -95,14 +95,12 @@ ShaderDefinition::RawData } else { - ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" << - shadersPath + mFragmentShaderPath << "'."; + ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" << shadersPath + mFragmentShaderPath << "'."; } } else { - ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" << - shadersPath + mVertexShaderPath << "'."; + ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" << shadersPath + mVertexShaderPath << "'."; } return raw; } @@ -110,21 +108,20 @@ ShaderDefinition::RawData Shader ShaderDefinition::Load(RawData&& raw) const { uint32_t hints = Shader::Hint::NONE; - for (const auto& hint : mHints) + for(const auto& hint : mHints) { - if (hint == SHADER_HINT_OUTPUT_IS_TRANSPARENT) + if(hint == SHADER_HINT_OUTPUT_IS_TRANSPARENT) { hints |= Shader::Hint::OUTPUT_IS_TRANSPARENT; } - else if (hint == SHADER_HINT_MODIFIES_GEOMETRY) + else if(hint == SHADER_HINT_MODIFIES_GEOMETRY) { hints |= Shader::Hint::MODIFIES_GEOMETRY; } } - Shader shader = Shader::New(raw.mVertexShaderSource, raw.mFragmentShaderSource, - static_cast(hints)); - for (Property::Map::SizeType i0 = 0, i1 = mUniforms.Count(); i0 != i1; ++i0) + Shader shader = Shader::New(raw.mVertexShaderSource, raw.mFragmentShaderSource, static_cast(hints)); + for(Property::Map::SizeType i0 = 0, i1 = mUniforms.Count(); i0 != i1; ++i0) { auto pair = mUniforms.GetKeyValue(i0); DALI_ASSERT_ALWAYS(pair.first.type == Property::Key::STRING); @@ -134,5 +131,5 @@ Shader ShaderDefinition::Load(RawData&& raw) const return shader; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/shader-definition.h b/dali-scene-loader/public-api/shader-definition.h index 29693fb..d7f390b 100644 --- a/dali-scene-loader/public-api/shader-definition.h +++ b/dali-scene-loader/public-api/shader-definition.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_SHADER_DEFINITION_H #define DALI_SCENE_LOADER_SHADER_DEFINITION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +21,14 @@ #include "dali-scene-loader/public-api/renderer-state.h" // EXTERNAL INCLUDES +#include #include "dali/public-api/common/vector-wrapper.h" #include "dali/public-api/rendering/shader.h" -#include namespace Dali { namespace SceneLoader { - /* * @brief Defines a shader with paths to the files which define its * vertex and fragment components, and a mapping of uniform names (which are @@ -76,15 +75,15 @@ struct DALI_SCENE_LOADER_API ShaderDefinition public: // DATA RendererState::Type mRendererState = RendererState::NONE; - std::string mVertexShaderPath; - std::string mFragmentShaderPath; + std::string mVertexShaderPath; + std::string mFragmentShaderPath; std::vector mDefines; std::vector mHints; Property::Map mUniforms; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_SHADER_DEFINITION_H diff --git a/dali-scene-loader/public-api/skeleton-definition.h b/dali-scene-loader/public-api/skeleton-definition.h index a06f19b..9bd7133 100644 --- a/dali-scene-loader/public-api/skeleton-definition.h +++ b/dali-scene-loader/public-api/skeleton-definition.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_SKELETON_H #define DALI_SCENE_LOADER_SKELETON_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ namespace Dali { namespace SceneLoader { - /* * @brief A set of joints (stored as node indices), and an optional root node index. * @note The list of joints must not be empty and must not contain INVALID_INDEX. @@ -39,17 +38,17 @@ struct DALI_SCENE_LOADER_API SkeletonDefinition { struct Joint { - Index mNodeIdx; + Index mNodeIdx; Matrix mInverseBindMatrix; }; using Vector = std::vector; - Index mRootNodeIdx = INVALID_INDEX; + Index mRootNodeIdx = INVALID_INDEX; std::vector mJoints; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_SKELETON_H diff --git a/dali-scene-loader/public-api/skinning-details.cpp b/dali-scene-loader/public-api/skinning-details.cpp index 92ded02..0edb58b 100644 --- a/dali-scene-loader/public-api/skinning-details.cpp +++ b/dali-scene-loader/public-api/skinning-details.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,18 +15,17 @@ * */ #include "dali-scene-loader/public-api/skinning-details.h" -#include "dali/public-api/rendering/shader.h" -#include "dali/public-api/object/property.h" #include "dali/public-api/animation/constraints.h" +#include "dali/public-api/object/property.h" +#include "dali/public-api/rendering/shader.h" namespace Dali { namespace SceneLoader { - const unsigned int Skinning::MAX_JOINTS = 64; const std::string Skinning::BONE_UNIFORM_NAME = "uBone"; -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/skinning-details.h b/dali-scene-loader/public-api/skinning-details.h index 415d25a..4ad1676 100644 --- a/dali-scene-loader/public-api/skinning-details.h +++ b/dali-scene-loader/public-api/skinning-details.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_SKINNING_DETAILS_H_ #define DALI_SCENE_LOADER_SKINNING_DETAILS_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,8 @@ #include "dali-scene-loader/public-api/api.h" // EXTERNAL INCLUDES -#include "dali/public-api/rendering/shader.h" #include +#include "dali/public-api/rendering/shader.h" namespace Dali { @@ -43,7 +43,7 @@ struct DALI_SCENE_LOADER_API Skinning Skinning() = delete; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif // DALI_SCENE_LOADER_SKINNING_DETAILS_H_ diff --git a/dali-scene-loader/public-api/string-callback.cpp b/dali-scene-loader/public-api/string-callback.cpp index d13fc15..8bf02e6 100644 --- a/dali-scene-loader/public-api/string-callback.cpp +++ b/dali-scene-loader/public-api/string-callback.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,11 +21,10 @@ namespace Dali { namespace SceneLoader { - void DefaultErrorCallback(const std::string& message) { DALI_LOG_ERROR("%s", message.c_str()); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/string-callback.h b/dali-scene-loader/public-api/string-callback.h index 9569b2d..5a1d289 100644 --- a/dali-scene-loader/public-api/string-callback.h +++ b/dali-scene-loader/public-api/string-callback.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_STRING_CALLBACK_H #define DALI_SCENE_LOADER_STRING_CALLBACK_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ namespace Dali { namespace SceneLoader { - /* * @brief A callback to post strings to. */ @@ -39,7 +38,7 @@ using StringCallback = std::function; */ DALI_SCENE_LOADER_API void DefaultErrorCallback(const std::string& message); -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_STRING_CALLBACK_H diff --git a/dali-scene-loader/public-api/utils.cpp b/dali-scene-loader/public-api/utils.cpp index 8b8132e..4d4396d 100644 --- a/dali-scene-loader/public-api/utils.cpp +++ b/dali-scene-loader/public-api/utils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,12 @@ #include "dali-scene-loader/public-api/utils.h" // EXTERNAL -#include "dali/public-api/common/vector-wrapper.h" -#include "dali/public-api/animation/constraints.h" -#include -#include -#include #include +#include +#include +#include +#include "dali/public-api/animation/constraints.h" +#include "dali/public-api/common/vector-wrapper.h" namespace Dali { @@ -46,10 +46,11 @@ ExceptionFlinger::Impl::~Impl() noexcept(false) } ExceptionFlinger::ExceptionFlinger(const char* location) noexcept(true) -: mImpl{ location }, +: mImpl{location}, mStreamBuffer(GetMessageBuffer(), MESSAGE_BUFFER_SIZE - 1), mStream(&mStreamBuffer) -{} +{ +} ExceptionFlinger::~ExceptionFlinger() noexcept(false) { @@ -79,16 +80,16 @@ std::string FormatString(const char* format, ...) return result; } -std::string LoadTextFile(const char * path, bool* fail) +std::string LoadTextFile(const char* path, bool* fail) { std::ifstream inFile(path); - if (inFile) + if(inFile) { std::istreambuf_iterator eos; std::istreambuf_iterator i(inFile.rdbuf()); return std::string(i, eos); } - else if (fail) + else if(fail) { *fail = true; } @@ -102,32 +103,31 @@ Geometry MakeTexturedQuadGeometry(TexturedQuadOptions::Type options) properties.Insert("aTexCoord", Property::VECTOR2); std::vector bytes; - size_t stride = 0; - size_t uvOffset = 0; + size_t stride = 0; + size_t uvOffset = 0; struct { Vector3 aPosition; Vector2 aTexCoord; } vertices[] = { - { Vector3(-0.5f, 0.5f, 0.0f), Vector2(0.0f, .0f) }, - { Vector3(0.5f, 0.5f, 0.0f), Vector2(1.0f, .0f) }, - { Vector3(-0.5f, -0.5f, 0.0f), Vector2(0.0f, 1.0f) }, - { Vector3(0.5f, -0.5f, 0.0f), Vector2(1.0f, 1.0f) } - }; + {Vector3(-0.5f, 0.5f, 0.0f), Vector2(0.0f, .0f)}, + {Vector3(0.5f, 0.5f, 0.0f), Vector2(1.0f, .0f)}, + {Vector3(-0.5f, -0.5f, 0.0f), Vector2(0.0f, 1.0f)}, + {Vector3(0.5f, -0.5f, 0.0f), Vector2(1.0f, 1.0f)}}; bytes.resize(sizeof(vertices)); - stride = sizeof(vertices[0]); + stride = sizeof(vertices[0]); uvOffset = reinterpret_cast(&vertices[0].aTexCoord) - reinterpret_cast(&vertices[0]); std::memcpy(bytes.data(), vertices, sizeof(vertices)); - if (MaskMatch(options, TexturedQuadOptions::FLIP_VERTICAL)) + if(MaskMatch(options, TexturedQuadOptions::FLIP_VERTICAL)) { Vector2* uv = reinterpret_cast(reinterpret_cast(bytes.data()) + uvOffset); - for (int i = 0; i < 4; ++i) + for(int i = 0; i < 4; ++i) { uv->y = 1.0f - uv->y; - uv = reinterpret_cast(reinterpret_cast(uv) + stride); + uv = reinterpret_cast(reinterpret_cast(uv) + stride); } } @@ -145,5 +145,5 @@ void ToUnixFileSeparators(std::string& path) std::replace(path.begin(), path.end(), '\\', '/'); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/utils.h b/dali-scene-loader/public-api/utils.h index 1aace35..f9213e1 100644 --- a/dali-scene-loader/public-api/utils.h +++ b/dali-scene-loader/public-api/utils.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_UTILS_H_ #define DALI_SCENE_LOADER_UTILS_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,17 +21,16 @@ #include "dali-scene-loader/public-api/api.h" // EXTERNAL INCLUDES +#include +#include #include "dali/public-api/actors/actor.h" -#include "dali/public-api/rendering/renderer.h" #include "dali/public-api/common/dali-common.h" -#include -#include +#include "dali/public-api/rendering/renderer.h" namespace Dali { namespace SceneLoader { - /* * @brief Fixed size backing buffer to use with std::ostreams where control over * allocations (which this does not make), is required. @@ -52,14 +51,16 @@ public: class DALI_SCENE_LOADER_API ExceptionFlinger { public: - enum { MESSAGE_BUFFER_SIZE = 512 }; + enum + { + MESSAGE_BUFFER_SIZE = 512 + }; ExceptionFlinger(const char* location) noexcept(true); - [[noreturn]] - ~ExceptionFlinger() noexcept(false); + [[noreturn]] ~ExceptionFlinger() noexcept(false); - template + template ExceptionFlinger& operator<<(const T& rhs) noexcept(true) { mStream << rhs; @@ -71,13 +72,12 @@ private: { const char* mLocation; - [[noreturn]] - ~Impl() noexcept(false); + [[noreturn]] ~Impl() noexcept(false); }; static char* GetMessageBuffer() noexcept(true); - Impl mImpl; + Impl mImpl; StreamBuffer mStreamBuffer; std::ostream mStream; }; @@ -90,13 +90,15 @@ DALI_SCENE_LOADER_API std::string FormatString(const char* format, ...); /* * @return The @n th bit in a bitmask. */ -DALI_SCENE_LOADER_API constexpr size_t NthBit(size_t n) { return 1 << n; } +DALI_SCENE_LOADER_API constexpr size_t NthBit(size_t n) +{ + return 1 << n; +} /* * @return Whether all of @a mask 's bits are set on @a value. */ -inline -DALI_SCENE_LOADER_API bool MaskMatch(uint32_t value, uint32_t mask) +inline DALI_SCENE_LOADER_API bool MaskMatch(uint32_t value, uint32_t mask) { return (value & mask) == mask; } @@ -104,8 +106,7 @@ DALI_SCENE_LOADER_API bool MaskMatch(uint32_t value, uint32_t mask) /* * @brief Convert a four-letter(, null-terminated) string literal into a uint32_t. */ -inline -DALI_SCENE_LOADER_API constexpr uint32_t FourCC(const char(&fourCC)[5]) +inline DALI_SCENE_LOADER_API constexpr uint32_t FourCC(const char (&fourCC)[5]) { return (fourCC[3] << 24) | (fourCC[2] << 16) | (fourCC[1] << 8) | fourCC[0]; } @@ -116,11 +117,10 @@ DALI_SCENE_LOADER_API constexpr uint32_t FourCC(const char(&fourCC)[5]) * @param[in] b, compare string * @return true if strings are equal */ -inline -DALI_SCENE_LOADER_API bool CaseInsensitiveCharacterCompare( unsigned char a, unsigned char b ) +inline DALI_SCENE_LOADER_API bool CaseInsensitiveCharacterCompare(unsigned char a, unsigned char b) { // Converts to lower case in the current locale. - return std::tolower( a ) == std::tolower( b ); + return std::tolower(a) == std::tolower(b); } /* @@ -128,13 +128,12 @@ DALI_SCENE_LOADER_API bool CaseInsensitiveCharacterCompare( unsigned char a, uns * @param[in] a, compare string * @param[in] b, compare string */ -inline -DALI_SCENE_LOADER_API bool CaseInsensitiveStringCompare( const std::string& a, const std::string& b ) +inline DALI_SCENE_LOADER_API bool CaseInsensitiveStringCompare(const std::string& a, const std::string& b) { bool result = false; - if( a.length() == b.length() ) + if(a.length() == b.length()) { - result = std::equal( a.begin(), a.end(), b.begin(), &CaseInsensitiveCharacterCompare ); + result = std::equal(a.begin(), a.end(), b.begin(), &CaseInsensitiveCharacterCompare); } return result; } @@ -154,9 +153,8 @@ DALI_SCENE_LOADER_API std::string LoadTextFile(const char* path, bool* fail = nu * @note Use of a @a fn that is itself recursing in @a is also discouraged * for performance and stability reasons. */ -template -inline -DALI_SCENE_LOADER_API void VisitActor(Actor a, Func fn) +template +inline DALI_SCENE_LOADER_API void VisitActor(Actor a, Func fn) { fn(a); @@ -171,8 +169,7 @@ DALI_SCENE_LOADER_API void VisitActor(Actor a, Func fn) * @brief Convenience function to set the given actor @a 's anchor point * and parent origin to center. */ -inline -DALI_SCENE_LOADER_API void SetActorCentered(Actor a) +inline DALI_SCENE_LOADER_API void SetActorCentered(Actor a) { a.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); a.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); @@ -184,10 +181,10 @@ using Type = uint32_t; enum DALI_SCENE_LOADER_API Values : Type { - NONE = 0x00, + NONE = 0x00, FLIP_VERTICAL = 0x01, }; -} +} // namespace TexturedQuadOptions /* * @brief Makes... geometry for a textured quad. @@ -198,9 +195,9 @@ DALI_SCENE_LOADER_API Geometry MakeTexturedQuadGeometry(TexturedQuadOptions::Typ * @brief Fixes the path of a file. Replaces the '\\' separator by the '/' one. * @param[in,out] path The path to be fixed. */ -DALI_SCENE_LOADER_API void ToUnixFileSeparators( std::string& path ); +DALI_SCENE_LOADER_API void ToUnixFileSeparators(std::string& path); -} -} +} // namespace SceneLoader +} // namespace Dali #endif /* DALI_SCENE_LOADER_UTILS_H_ */ diff --git a/dali-scene-loader/public-api/view-projection.cpp b/dali-scene-loader/public-api/view-projection.cpp index ed8cbe3..ce2e6b0 100644 --- a/dali-scene-loader/public-api/view-projection.cpp +++ b/dali-scene-loader/public-api/view-projection.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,17 +21,16 @@ namespace Dali { namespace SceneLoader { - void ViewProjection::Update() { Matrix::Multiply(mViewProjection, mView, mProjection); mInvProjection = mProjection; - if (!mInvProjection.Invert()) + if(!mInvProjection.Invert()) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to find inverse of projection matrix " << mProjection << "."; } } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/view-projection.h b/dali-scene-loader/public-api/view-projection.h index 70efc4f..26ce908 100644 --- a/dali-scene-loader/public-api/view-projection.h +++ b/dali-scene-loader/public-api/view-projection.h @@ -1,7 +1,7 @@ #ifndef DALI_SCENE_LOADER_VIEW_PROJECTION_H_ #define DALI_SCENE_LOADER_VIEW_PROJECTION_H_ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ namespace Dali { namespace SceneLoader { - /** * @brief Contains view and projection matrices, also caching the view-projection * and inverse projection matrices. @@ -35,18 +34,36 @@ namespace SceneLoader class ViewProjection { public: - Matrix& GetView() { return mView; } - Matrix& GetProjection() { return mProjection; } + Matrix& GetView() + { + return mView; + } + Matrix& GetProjection() + { + return mProjection; + } /* * @brief Updates the cached view projection and inverse projection matrices. */ void Update(); - const Matrix& GetView() const { return mView; } - const Matrix& GetProjection() const { return mProjection; } - const Matrix& GetInverseProjection() const { return mInvProjection; } - const Matrix& GetViewProjection() const { return mViewProjection; } + const Matrix& GetView() const + { + return mView; + } + const Matrix& GetProjection() const + { + return mProjection; + } + const Matrix& GetInverseProjection() const + { + return mInvProjection; + } + const Matrix& GetViewProjection() const + { + return mViewProjection; + } private: Matrix mView; @@ -55,7 +72,7 @@ private: Matrix mViewProjection; }; -} -} +} // namespace SceneLoader +} // namespace Dali #endif //DALI_SCENE_LOADER_VIEW_PROJECTION_H_ diff --git a/dali-scene-loader/third-party/.clang-format b/dali-scene-loader/third-party/.clang-format new file mode 100644 index 0000000..297ddc2 --- /dev/null +++ b/dali-scene-loader/third-party/.clang-format @@ -0,0 +1,5 @@ +--- +Language: Cpp +DisableFormat: true +SortIncludes: false +... diff --git a/dali-toolkit/devel-api/builder/builder.h b/dali-toolkit/devel-api/builder/builder.h index f10f037..b255c11 100644 --- a/dali-toolkit/devel-api/builder/builder.h +++ b/dali-toolkit/devel-api/builder/builder.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_UIBUILDER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -163,9 +163,23 @@ public: * @brief Adds user defined constants to all future style template or animation expansions * * e.g. - * Property::Map map; - * map["IMAGE_DIRECTORY"] = "/usr/share/images"; - * builder.AddConstants( map ); + * @code + * Property::Map map; + * map["IMAGE_DIRECTORY"] = "/usr/share/images"; + * builder.AddConstants( map ); + * @endcode + * + * The following shows a list of constants available by default: + * + * Constant | Description + * ----------------------------- | ---------------------------------------------------------------------------------------------------- + * DALI_IMAGE_DIR | The Image Directory used by Toolkit. + * DALI_SOUND_DIR | The Sound Directory used by Toolkit. + * DALI_STYLE_DIR | The Style directory that the Toolkit uses. + * DALI_STYLE_IMAGE_DIR | The directory that stores all the images used by Toolkit's style. + * DALI_SHADER_VERSION_PREFIX | For use in custom shaders to prepend the shader version in use. @ref Shader::GetShaderVersionPrefix + * DALI_VERTEX_SHADER_PREFIX | For use in custom vertex shaders to preprocessor prefix used. @ref Shader::GetVertexShaderPrefix + * DALI_FRAGMENT_SHADER_PREFIX | For use in custom vertex shaders to preprocessor prefix used. @ref Shader::GetFragmentShaderPrefix() * * @pre The Builder has been initialized. * @param map The user defined constants used in template expansions. @@ -180,6 +194,8 @@ public: * builder.AddConstant( "IMAGE_DIRECTORY", "/usr/share/images" ); * @endcode * + * @see AddConstants(const Property::Map&) for builder pre-defined default constants. + * * @pre The Builder has been initialized. * @param key The constant name to add or update * @param value The new value for the constant. diff --git a/dali-toolkit/devel-api/builder/tree-node.cpp b/dali-toolkit/devel-api/builder/tree-node.cpp index 0d04753..571816a 100644 --- a/dali-toolkit/devel-api/builder/tree-node.cpp +++ b/dali-toolkit/devel-api/builder/tree-node.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ namespace Dali { - /** * return true if the lower cased ASCII strings are equal. */ diff --git a/dali-toolkit/devel-api/controls/accessible-impl.cpp b/dali-toolkit/devel-api/controls/accessible-impl.cpp new file mode 100644 index 0000000..f986bd4 --- /dev/null +++ b/dali-toolkit/devel-api/controls/accessible-impl.cpp @@ -0,0 +1,421 @@ +/* + * Copyright (c) 2021 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// CLASS HEADER +#include "accessible-impl.h" + +// EXTERNAL INCLUDES +#include + +// INTERNAL INCLUDES +#include +#include +#include +#include +#include +#include + +namespace Dali::Toolkit::DevelControl { + +AccessibleImpl::AccessibleImpl(Dali::Actor self, Dali::Accessibility::Role role, bool modal) +: self(self), + modal(modal) +{ + auto control = Dali::Toolkit::Control::DownCast(self); + + Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control); + Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl); + if(controlImpl.mAccessibilityRole == Dali::Accessibility::Role::UNKNOWN) + controlImpl.mAccessibilityRole = role; + + self.PropertySetSignal().Connect(&controlImpl, [this, &controlImpl](Dali::Handle& handle, Dali::Property::Index index, Dali::Property::Value value) { + if(this->self != Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor()) + { + return; + } + + if(index == DevelControl::Property::ACCESSIBILITY_NAME || (index == GetNamePropertyIndex() && !controlImpl.mAccessibilityNameSet)) + { + if(controlImpl.mAccessibilityGetNameSignal.Empty()) + { + Emit(Dali::Accessibility::ObjectPropertyChangeEvent::NAME); + } + } + + if(index == DevelControl::Property::ACCESSIBILITY_DESCRIPTION || (index == GetDescriptionPropertyIndex() && !controlImpl.mAccessibilityDescriptionSet)) + { + if(controlImpl.mAccessibilityGetDescriptionSignal.Empty()) + { + Emit(Dali::Accessibility::ObjectPropertyChangeEvent::DESCRIPTION); + } + } + }); +} + +std::string AccessibleImpl::GetName() +{ + auto control = Dali::Toolkit::Control::DownCast(self); + + Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control); + Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl); + + if(!controlImpl.mAccessibilityGetNameSignal.Empty()) + { + std::string ret; + controlImpl.mAccessibilityGetNameSignal.Emit(ret); + return ret; + } + + if(controlImpl.mAccessibilityNameSet) + return controlImpl.mAccessibilityName; + + if(auto raw = GetNameRaw(); !raw.empty()) + return raw; + + return self.GetProperty(Actor::Property::NAME); +} + +std::string AccessibleImpl::GetNameRaw() +{ + return {}; +} + +std::string AccessibleImpl::GetDescription() +{ + auto control = Dali::Toolkit::Control::DownCast(self); + + Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control); + Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl); + + if(!controlImpl.mAccessibilityGetDescriptionSignal.Empty()) + { + std::string ret; + controlImpl.mAccessibilityGetDescriptionSignal.Emit(ret); + return ret; + } + + if(controlImpl.mAccessibilityDescriptionSet) + return controlImpl.mAccessibilityDescription; + + return GetDescriptionRaw(); +} + +std::string AccessibleImpl::GetDescriptionRaw() +{ + return ""; +} + +Dali::Accessibility::Accessible* AccessibleImpl::GetParent() +{ + return Dali::Accessibility::Accessible::Get(self.GetParent()); +} + +size_t AccessibleImpl::GetChildCount() +{ + return self.GetChildCount(); +} + +Dali::Accessibility::Accessible* AccessibleImpl::GetChildAtIndex(size_t index) +{ + return Dali::Accessibility::Accessible::Get(self.GetChildAt(static_cast(index))); +} + +size_t AccessibleImpl::GetIndexInParent() +{ + auto s = self; + auto parent = s.GetParent(); + DALI_ASSERT_ALWAYS(parent && "can't call GetIndexInParent on object without parent"); + auto count = parent.GetChildCount(); + for(auto i = 0u; i < count; ++i) + { + auto c = parent.GetChildAt(i); + if(c == s) + return i; + } + DALI_ASSERT_ALWAYS(false && "object isn't child of it's parent"); + return static_cast(-1); +} + +Dali::Accessibility::Role AccessibleImpl::GetRole() +{ + return self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE); +} + +Dali::Accessibility::States AccessibleImpl::CalculateStates() +{ + Dali::Accessibility::States s; + s[Dali::Accessibility::State::FOCUSABLE] = self.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE); + s[Dali::Accessibility::State::FOCUSED] = Toolkit::KeyboardFocusManager::Get().GetCurrentFocusActor() == self; + if(self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE).GetType() == Dali::Property::NONE) + s[Dali::Accessibility::State::HIGHLIGHTABLE] = false; + else + s[Dali::Accessibility::State::HIGHLIGHTABLE] = self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE).Get(); + s[Dali::Accessibility::State::HIGHLIGHTED] = GetCurrentlyHighlightedActor() == self; + s[Dali::Accessibility::State::ENABLED] = true; + s[Dali::Accessibility::State::SENSITIVE] = true; + s[Dali::Accessibility::State::ANIMATED] = self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED).Get(); + s[Dali::Accessibility::State::VISIBLE] = true; + if(modal) + { + s[Dali::Accessibility::State::MODAL] = true; + } + s[Dali::Accessibility::State::SHOWING] = !self.GetProperty(Dali::DevelActor::Property::CULLED).Get() && self.GetCurrentProperty(Actor::Property::VISIBLE); + + s[Dali::Accessibility::State::DEFUNCT] = !self.GetProperty(Dali::DevelActor::Property::CONNECTED_TO_SCENE).Get(); + return s; +} + +Dali::Accessibility::States AccessibleImpl::GetStates() +{ + return CalculateStates(); +} + +Dali::Accessibility::Attributes AccessibleImpl::GetAttributes() +{ + std::unordered_map attribute_map; + auto q = Dali::Toolkit::Control::DownCast(self); + auto w = + q.GetProperty(Dali::Toolkit::DevelControl::Property::ACCESSIBILITY_ATTRIBUTES); + auto z = w.GetMap(); + + if(z) + { + auto map_size = z->Count(); + + for(unsigned int i = 0; i < map_size; i++) + { + auto map_key = z->GetKeyAt(i); + if(map_key.type == Dali::Property::Key::STRING) + { + std::string map_value; + if(z->GetValue(i).Get(map_value)) + { + attribute_map.emplace(std::move(map_key.stringKey), + std::move(map_value)); + } + } + } + } + + return attribute_map; +} + +Dali::Accessibility::ComponentLayer AccessibleImpl::GetLayer() +{ + return Dali::Accessibility::ComponentLayer::WINDOW; +} + +Dali::Rect<> AccessibleImpl::GetExtents(Dali::Accessibility::CoordType ctype) +{ + Vector2 screenPosition = + self.GetProperty(Dali::DevelActor::Property::SCREEN_POSITION) + .Get(); + auto size = self.GetCurrentProperty(Actor::Property::SIZE) * self.GetCurrentProperty(Actor::Property::WORLD_SCALE); + bool positionUsesAnchorPoint = + self.GetProperty(Dali::DevelActor::Property::POSITION_USES_ANCHOR_POINT) + .Get(); + Vector3 anchorPointOffSet = + size * (positionUsesAnchorPoint ? self.GetCurrentProperty(Actor::Property::ANCHOR_POINT) + : AnchorPoint::TOP_LEFT); + Vector2 position = Vector2(screenPosition.x - anchorPointOffSet.x, + screenPosition.y - anchorPointOffSet.y); + + return {position.x, position.y, size.x, size.y}; +} + +int16_t AccessibleImpl::GetMdiZOrder() +{ + return 0; +} +double AccessibleImpl::GetAlpha() +{ + return 0; +} + +bool AccessibleImpl::GrabFocus() +{ + return Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor(self); +} + +static Dali::Actor CreateHighlightIndicatorActor() +{ + std::string focusBorderImagePath(AssetManager::GetDaliImagePath()); + focusBorderImagePath += "/keyboard_focus.9.png"; + // Create the default if it hasn't been set and one that's shared by all the + // keyboard focusable actors + auto actor = Toolkit::ImageView::New(focusBorderImagePath); + actor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); + DevelControl::AppendAccessibilityAttribute(actor, "highlight", ""); + actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED, true); + actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false); + + return actor; +} + +bool AccessibleImpl::GrabHighlight() +{ + auto old = GetCurrentlyHighlightedActor(); + + if(!Dali::Accessibility::IsUp()) + return false; + if(self == old) + return true; + if(old) + { + auto c = dynamic_cast(Internal::Control::Impl::GetAccessibilityObject(old)); + if(c) + c->ClearHighlight(); + } + auto highlight = GetHighlightActor(); + if(!highlight) + { + highlight = CreateHighlightIndicatorActor(); + SetHighlightActor(highlight); + } + highlight.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + highlight.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + highlight.SetProperty(Actor::Property::POSITION_Z, 1.0f); + highlight.SetProperty(Actor::Property::POSITION, Vector2(0.0f, 0.0f)); + + EnsureSelfVisible(); + self.Add(highlight); + SetCurrentlyHighlightedActor(self); + EmitHighlighted(true); + + return true; +} + +bool AccessibleImpl::ClearHighlight() +{ + if(!Dali::Accessibility::IsUp()) + return false; + if(GetCurrentlyHighlightedActor() == self) + { + self.Remove(GetHighlightActor()); + SetCurrentlyHighlightedActor({}); + EmitHighlighted(false); + return true; + } + return false; +} + +std::string AccessibleImpl::GetActionName(size_t index) +{ + if(index >= GetActionCount()) return ""; + Dali::TypeInfo type; + self.GetTypeInfo(type); + DALI_ASSERT_ALWAYS(type && "no TypeInfo object"); + return type.GetActionName(index); +} + +std::string AccessibleImpl::GetLocalizedActionName(size_t index) +{ + // TODO: add localization + return GetActionName(index); +} + +std::string AccessibleImpl::GetActionDescription(size_t index) +{ + return ""; +} + +size_t AccessibleImpl::GetActionCount() +{ + Dali::TypeInfo type; + self.GetTypeInfo(type); + DALI_ASSERT_ALWAYS(type && "no TypeInfo object"); + return type.GetActionCount(); +} + +std::string AccessibleImpl::GetActionKeyBinding(size_t index) +{ + return ""; +} + +bool AccessibleImpl::DoAction(size_t index) +{ + std::string actionName = GetActionName(index); + return self.DoAction(actionName, {}); +} + +bool AccessibleImpl::DoAction(const std::string& name) +{ + return self.DoAction(name, {}); +} + +bool AccessibleImpl::DoGesture(const Dali::Accessibility::GestureInfo& gestureInfo) +{ + auto control = Dali::Toolkit::Control::DownCast(self); + + Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control); + Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl); + + if(!controlImpl.mAccessibilityDoGestureSignal.Empty()) + { + auto ret = std::make_pair(gestureInfo, false); + controlImpl.mAccessibilityDoGestureSignal.Emit(ret); + return ret.second; + } + + return false; +} + +std::vector AccessibleImpl::GetRelationSet() +{ + auto control = Dali::Toolkit::Control::DownCast(self); + + Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control); + Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl); + + std::vector ret; + + auto& v = controlImpl.mAccessibilityRelations; + for(auto i = 0u; i < v.size(); ++i) + { + if(v[i].empty()) + continue; + + ret.emplace_back(Accessibility::Relation{static_cast(i), v[i]}); + } + + return ret; +} + +void AccessibleImpl::EnsureChildVisible(Actor child) +{ +} + +void AccessibleImpl::EnsureSelfVisible() +{ + auto parent = dynamic_cast(GetParent()); + if(parent) + { + parent->EnsureChildVisible(self); + } +} + +Dali::Property::Index AccessibleImpl::GetNamePropertyIndex() +{ + return Actor::Property::NAME; +} + +Dali::Property::Index AccessibleImpl::GetDescriptionPropertyIndex() +{ + return Dali::Property::INVALID_INDEX; +} + +} // namespace Dali::Toolkit::DevelControl diff --git a/dali-toolkit/devel-api/controls/accessible-impl.h b/dali-toolkit/devel-api/controls/accessible-impl.h new file mode 100644 index 0000000..feffe75 --- /dev/null +++ b/dali-toolkit/devel-api/controls/accessible-impl.h @@ -0,0 +1,217 @@ +#ifndef DALI_TOOLKIT_ACCESSIBLE_IMPL_H +#define DALI_TOOLKIT_ACCESSIBLE_IMPL_H +/* + * Copyright (c) 2021 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +// EXTERNAL INCLUDES +#include +#include + +// INTERNAL INCLUDES +#include + +namespace Dali::Toolkit::DevelControl { + +/** + * @brief Represents the Accessible object for Dali::Toolkit::Control and derived classes + * + * You can create a derived class (and register it using SetAccessibilityConstructor) + * in order to customize Accessibility for a given control. + * + * @see Dali::Toolkit::DevelControl::SetAccessibilityConstructor + * @see Dali::Accessibility::Accessible + * @see Dali::Accessibility::Component + * @see Dali::Accessibility::Collection + * @see Dali::Accessibility::Action + * @see Dali::Accessibility::Value + * @see Dali::Accessibility::Text + * @see Dali::Accessibility::EditableText + */ +struct DALI_TOOLKIT_API AccessibleImpl : public virtual Dali::Accessibility::Accessible, + public virtual Dali::Accessibility::Component, + public virtual Dali::Accessibility::Collection, + public virtual Dali::Accessibility::Action +{ + Dali::Actor self; + bool modal = false, root = false; + + AccessibleImpl(Dali::Actor self, Dali::Accessibility::Role role, bool modal = false); + + /** + * @copydoc Dali::Accessibility::Accessible::GetName() + */ + std::string GetName() override; + + /** + * @brief Returns the actor's name in the absence of ACCESSIBILITY_NAME property + */ + virtual std::string GetNameRaw(); + + /** + * @copydoc Dali::Accessibility::Accessible::GetDescription() + */ + std::string GetDescription() override; + + /** + * @brief Returns the actor's description in the absence of ACCESSIBILITY_DESCRIPTION property + */ + virtual std::string GetDescriptionRaw(); + + /** + * @copydoc Dali::Accessibility::Accessible::GetParent() + */ + Dali::Accessibility::Accessible* GetParent() override; + + /** + * @copydoc Dali::Accessibility::Accessible::GetChildCount() + */ + size_t GetChildCount() override; + + /** + * @copydoc Dali::Accessibility::Accessible::GetChildAtIndex() + */ + Dali::Accessibility::Accessible* GetChildAtIndex(size_t index) override; + + /** + * @copydoc Dali::Accessibility::Accessible::GetIndexInParent() + */ + size_t GetIndexInParent() override; + + /** + * @copydoc Dali::Accessibility::Accessible::GetRole() + */ + Dali::Accessibility::Role GetRole() override; + + /** + * @copydoc Dali::Accessibility::Accessible::GetStates() + */ + Dali::Accessibility::States GetStates() override; + + /** + * @copydoc Dali::Accessibility::Accessible::GetAttributes() + */ + Dali::Accessibility::Attributes GetAttributes() override; + + /** + * @copydoc Dali::Accessibility::Component::GetExtents() + */ + Dali::Rect<> GetExtents(Dali::Accessibility::CoordType ctype) override; + + /** + * @copydoc Dali::Accessibility::Component::GetLayer() + */ + Dali::Accessibility::ComponentLayer GetLayer() override; + + /** + * @copydoc Dali::Accessibility::Component::GetMdiZOrder() + */ + int16_t GetMdiZOrder() override; + + /** + * @copydoc Dali::Accessibility::Component::GrabFocus() + */ + bool GrabFocus() override; + + /** + * @copydoc Dali::Accessibility::Component::GetAlpha() + */ + double GetAlpha() override; + + /** + * @copydoc Dali::Accessibility::Component::GrabHighlight() + */ + bool GrabHighlight() override; + + /** + * @copydoc Dali::Accessibility::Component::ClearHighlight() + */ + bool ClearHighlight() override; + + /** + * @copydoc Dali::Accessibility::Action::GetActionName() + */ + std::string GetActionName(size_t index) override; + + /** + * @copydoc Dali::Accessibility::Action::GetLocalizedActionName() + */ + std::string GetLocalizedActionName(size_t index) override; + + /** + * @copydoc Dali::Accessibility::Action::GetActionDescription() + */ + std::string GetActionDescription(size_t index) override; + + /** + * @copydoc Dali::Accessibility::Action::GetActionCount() + */ + size_t GetActionCount() override; + + /** + * @copydoc Dali::Accessibility::Action::GetActionKeyBinding() + */ + std::string GetActionKeyBinding(size_t index) override; + + /** + * @copydoc Dali::Accessibility::Action::DoAction(size_t) + */ + bool DoAction(size_t index) override; + + /** + * @copydoc Dali::Accessibility::Action::DoAction(const std::string&) + */ + bool DoAction(const std::string& name) override; + + /** + * @copydoc Dali::Accessibility::Accessible::DoGesture() + */ + bool DoGesture(const Dali::Accessibility::GestureInfo& gestureInfo) override; + + /** + * @copydoc Dali::Accessibility::Accessible::GetRelationSet() + */ + std::vector GetRelationSet() override; + + /** + * @copydoc Dali::Accessibility::Accessible::GetStates() + */ + virtual Dali::Accessibility::States CalculateStates(); + + /** + * @brief Makes sure that a given child of this container (e.g. ItemView) is visible + */ + virtual void EnsureChildVisible(Actor child); + + /** + * @brief Makes sure this actor is visible (when moving the highlight frame to an + * actor that is scrolled out of the viewport) + */ + virtual void EnsureSelfVisible(); + + /** + * @brief Returns the index of the property that represents this actor's name + */ + virtual Dali::Property::Index GetNamePropertyIndex(); + + /** + * @brief Returns the index of the property that represents this actor's description + */ + virtual Dali::Property::Index GetDescriptionPropertyIndex(); +}; + +} // namespace Dali::Toolkit::DevelControl + +#endif // DALI_TOOLKIT_ACCESSIBLE_IMPL_H diff --git a/dali-toolkit/devel-api/controls/control-devel.cpp b/dali-toolkit/devel-api/controls/control-devel.cpp index 0670e68..157051b 100644 --- a/dali-toolkit/devel-api/controls/control-devel.cpp +++ b/dali-toolkit/devel-api/controls/control-devel.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ // INTERNAL INCLUDES #include #include -#include #include +#include namespace Dali { @@ -122,230 +122,230 @@ Dali::Property GetVisualProperty(Control control, Dali::Property::Index index, D return controlDataImpl.GetVisualProperty(index, visualPropertyKey); } -static Toolkit::Internal::Control::Impl *GetControlImplementationIfAny( Dali::Actor actor) +static Toolkit::Internal::Control::Impl* GetControlImplementationIfAny(Dali::Actor actor) { - Dali::Toolkit::Control c = Toolkit::Control::DownCast( actor ); - if ( c ) + Dali::Toolkit::Control c = Toolkit::Control::DownCast(actor); + if(c) { - auto &impl1 = Toolkit::Internal::GetImplementation( c ); - auto &impl2 = Toolkit::Internal::Control::Impl::Get( impl1 ); + auto& impl1 = Toolkit::Internal::GetImplementation(c); + auto& impl2 = Toolkit::Internal::Control::Impl::Get(impl1); return &impl2; } return nullptr; } -Toolkit::DevelControl::AccessibilityActivateSignalType &AccessibilityActivateSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityActivateSignalType& AccessibilityActivateSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityActivateSignal; } -Toolkit::DevelControl::AccessibilityReadingSkippedSignalType &AccessibilityReadingSkippedSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityReadingSkippedSignalType& AccessibilityReadingSkippedSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityReadingSkippedSignal; } -Toolkit::DevelControl::AccessibilityReadingPausedSignalType &AccessibilityReadingPausedSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityReadingPausedSignalType& AccessibilityReadingPausedSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityReadingPausedSignal; } -Toolkit::DevelControl::AccessibilityReadingResumedSignalType &AccessibilityReadingResumedSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityReadingResumedSignalType& AccessibilityReadingResumedSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityReadingResumedSignal; } -Toolkit::DevelControl::AccessibilityReadingCancelledSignalType &AccessibilityReadingCancelledSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityReadingCancelledSignalType& AccessibilityReadingCancelledSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityReadingCancelledSignal; } -Toolkit::DevelControl::AccessibilityReadingStoppedSignalType &AccessibilityReadingStoppedSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityReadingStoppedSignalType& AccessibilityReadingStoppedSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityReadingStoppedSignal; } -Toolkit::DevelControl::AccessibilityGetNameSignalType &AccessibilityGetNameSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityGetNameSignalType& AccessibilityGetNameSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityGetNameSignal; } -Toolkit::DevelControl::AccessibilityGetDescriptionSignalType &AccessibilityGetDescriptionSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityGetDescriptionSignalType& AccessibilityGetDescriptionSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityGetDescriptionSignal; } -Toolkit::DevelControl::AccessibilityDoGestureSignalType &AccessibilityDoGestureSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityDoGestureSignalType& AccessibilityDoGestureSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityDoGestureSignal; } -void AppendAccessibilityRelation( Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation) +void AppendAccessibilityRelation(Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { auto index = static_cast(relation); - if (index >= ac->mAccessibilityRelations.size()) + if(index >= ac->mAccessibilityRelations.size()) { - DALI_LOG_ERROR( "Relation index exceeds vector size." ); - return; + DALI_LOG_ERROR("Relation index exceeds vector size."); + return; } auto obj = ac->GetAccessibilityObject(destination); - if (obj) + if(obj) ac->mAccessibilityRelations[index].push_back(obj->GetAddress()); } } -void RemoveAccessibilityRelation( Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation) +void RemoveAccessibilityRelation(Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { auto index = static_cast(relation); - if (index >= ac->mAccessibilityRelations.size()) + if(index >= ac->mAccessibilityRelations.size()) { - DALI_LOG_ERROR( "Relation index exceeds vector size." ); - return; + DALI_LOG_ERROR("Relation index exceeds vector size."); + return; } auto obj = ac->GetAccessibilityObject(destination); - if (!obj) + if(!obj) return; auto address = obj->GetAddress(); - auto &targets = ac->mAccessibilityRelations[index]; - for (auto i = 0u; i < targets.size(); ++i) { - if (targets[i].ToString() == address.ToString()) - { - targets[i] = targets.back(); - targets.erase(targets.end() - 1); - } + auto& targets = ac->mAccessibilityRelations[index]; + for(auto i = 0u; i < targets.size(); ++i) + { + if(targets[i].ToString() == address.ToString()) + { + targets[i] = targets.back(); + targets.erase(targets.end() - 1); + } } } } -std::vector> GetAccessibilityRelations( Dali::Actor control ) +std::vector> GetAccessibilityRelations(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { return ac->mAccessibilityRelations; } return {}; } -void ClearAccessibilityRelations( Dali::Actor control ) +void ClearAccessibilityRelations(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - for (auto &it : ac->mAccessibilityRelations) + for(auto& it : ac->mAccessibilityRelations) it.clear(); } } -void SetAccessibilityConstructor( Dali::Actor control, - std::function< std::unique_ptr< Dali::Accessibility::Accessible >( Dali::Actor ) > constructor ) +void SetAccessibilityConstructor(Dali::Actor control, + std::function(Dali::Actor)> constructor) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { ac->accessibilityConstructor = constructor; } } -void AppendAccessibilityAttribute( Dali::Actor control, const std::string& key, - const std::string value ) +void AppendAccessibilityAttribute(Dali::Actor control, const std::string& key, const std::string value) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - ac->AppendAccessibilityAttribute( key, value ); + ac->AppendAccessibilityAttribute(key, value); } } -void RemoveAccessibilityAttribute( Dali::Actor control, const std::string& key ) +void RemoveAccessibilityAttribute(Dali::Actor control, const std::string& key) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - ac->RemoveAccessibilityAttribute( key ); + ac->RemoveAccessibilityAttribute(key); } } -void ClearAccessibilityAttributes( Dali::Actor control ) +void ClearAccessibilityAttributes(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { ac->ClearAccessibilityAttributes(); } } -void SetAccessibilityReadingInfoType( Dali::Actor control, const Dali::Accessibility::ReadingInfoTypes types ) +void SetAccessibilityReadingInfoType(Dali::Actor control, const Dali::Accessibility::ReadingInfoTypes types) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - ac->SetAccessibilityReadingInfoType( types ); + ac->SetAccessibilityReadingInfoType(types); } } -Dali::Accessibility::ReadingInfoTypes GetAccessibilityReadingInfoType(Dali::Actor control ) +Dali::Accessibility::ReadingInfoTypes GetAccessibilityReadingInfoType(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { return ac->GetAccessibilityReadingInfoType(); } return {}; } -bool ClearAccessibilityHighlight( Dali::Actor control ) +bool ClearAccessibilityHighlight(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - auto ptr = dynamic_cast( ac->GetAccessibilityObject() ); - if( ptr ) + auto ptr = dynamic_cast(ac->GetAccessibilityObject()); + if(ptr) return ptr->ClearHighlight(); } return false; } -bool GrabAccessibilityHighlight( Dali::Actor control ) +bool GrabAccessibilityHighlight(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - auto ptr = dynamic_cast( ac->GetAccessibilityObject() ); - if( ptr ) + auto ptr = dynamic_cast(ac->GetAccessibilityObject()); + if(ptr) return ptr->GrabHighlight(); } return false; } -Dali::Accessibility::States GetAccessibilityStates( Dali::Actor control ) +Dali::Accessibility::States GetAccessibilityStates(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - auto ptr = dynamic_cast( ac->GetAccessibilityObject() ); + auto ptr = dynamic_cast(ac->GetAccessibilityObject()); if(ptr) return ptr->GetStates(); } return {}; } -void NotifyAccessibilityStateChange( Dali::Actor control, Dali::Accessibility::States states, bool doRecursive ) +void NotifyAccessibilityStateChange(Dali::Actor control, Dali::Accessibility::States states, bool doRecursive) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - ac->GetAccessibilityObject()->NotifyAccessibilityStateChange( std::move(states), doRecursive ); + ac->GetAccessibilityObject()->NotifyAccessibilityStateChange(std::move(states), doRecursive); } } -Dali::Accessibility::Accessible *GetBoundAccessibilityObject( Dali::Actor control ) +Dali::Accessibility::Accessible* GetBoundAccessibilityObject(Dali::Actor control) { - return Dali::Accessibility::Accessible::Get( control ); + return Dali::Accessibility::Accessible::Get(control); } } // namespace DevelControl diff --git a/dali-toolkit/devel-api/controls/control-devel.h b/dali-toolkit/devel-api/controls/control-devel.h index af6c76c..3d340ec 100644 --- a/dali-toolkit/devel-api/controls/control-devel.h +++ b/dali-toolkit/devel-api/controls/control-devel.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_CONTROL_DEVEL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ #include // INTERNAL INCLUDES +#include #include #include @@ -39,31 +40,31 @@ class Base; namespace DevelControl { /// @brief AccessibilityActivate signal type. -typedef Signal< void ( ) > AccessibilityActivateSignalType; +typedef Signal AccessibilityActivateSignalType; /// @brief AccessibilityReadingSkipped signal type. -typedef Signal< void ( ) > AccessibilityReadingSkippedSignalType; +typedef Signal AccessibilityReadingSkippedSignalType; /// @brief AccessibilityReadingPaused signal type. -typedef Signal< void ( ) > AccessibilityReadingPausedSignalType; +typedef Signal AccessibilityReadingPausedSignalType; /// @brief AccessibilityReadingResumed signal type. -typedef Signal< void ( ) > AccessibilityReadingResumedSignalType; +typedef Signal AccessibilityReadingResumedSignalType; /// @brief AccessibilityReadingCancelled signal type. -typedef Signal< void ( ) > AccessibilityReadingCancelledSignalType; +typedef Signal AccessibilityReadingCancelledSignalType; /// @brief AccessibilityReadingStopped signal type. -typedef Signal< void ( ) > AccessibilityReadingStoppedSignalType; +typedef Signal AccessibilityReadingStoppedSignalType; /// @brief AccessibilityGetName signal type. -typedef Signal< void ( std::string& ) > AccessibilityGetNameSignalType; +typedef Signal AccessibilityGetNameSignalType; /// @brief AccessibilityGetDescription signal type. -typedef Signal< void ( std::string& ) > AccessibilityGetDescriptionSignalType; +typedef Signal AccessibilityGetDescriptionSignalType; /// @brief AccessibilityDoGesture signal type. -typedef Signal< void ( std::pair& ) > AccessibilityDoGestureSignalType; +typedef Signal&)> AccessibilityDoGestureSignalType; enum State { @@ -364,8 +365,6 @@ DALI_TOOLKIT_API VisualEventSignalType& VisualEventSignal(Control control); * @param[in] index The Property index of the visual. * @param[in] visualPropertyKey The key of the visual's property. * @return The Property object - * @pre The control should be added to the Scene. - * @pre The returned object is valid for as long as the control is on the Scene. */ DALI_TOOLKIT_API Dali::Property GetVisualProperty(Control control, Dali::Property::Index index, Dali::Property::Key visualPropertyKey); @@ -373,7 +372,7 @@ DALI_TOOLKIT_API Dali::Property GetVisualProperty(Control control, Dali::Propert * @brief The signal is emmited as a succession of "activate" signal send by accessibility client. * @return The signal to connect to */ -DALI_TOOLKIT_API AccessibilityActivateSignalType &AccessibilityActivateSignal( Toolkit::Control control ); +DALI_TOOLKIT_API AccessibilityActivateSignalType& AccessibilityActivateSignal(Toolkit::Control control); /** * @brief The signal is emmited when text send via Dali::Accessibility::Bridge::Say @@ -381,21 +380,21 @@ DALI_TOOLKIT_API AccessibilityActivateSignalType &AccessibilityActivateSignal( T * * @return The signal to connect to */ -DALI_TOOLKIT_API AccessibilityReadingSkippedSignalType &AccessibilityReadingSkippedSignal( Toolkit::Control control ); +DALI_TOOLKIT_API AccessibilityReadingSkippedSignalType& AccessibilityReadingSkippedSignal(Toolkit::Control control); /** * @brief * * @return The signal to connect to */ -DALI_TOOLKIT_API AccessibilityReadingPausedSignalType &AccessibilityReadingPausedSignal( Toolkit::Control control ); +DALI_TOOLKIT_API AccessibilityReadingPausedSignalType& AccessibilityReadingPausedSignal(Toolkit::Control control); /** * @brief * * @return The signal to connect to */ -DALI_TOOLKIT_API AccessibilityReadingResumedSignalType &AccessibilityReadingResumedSignal( Toolkit::Control control ); +DALI_TOOLKIT_API AccessibilityReadingResumedSignalType& AccessibilityReadingResumedSignal(Toolkit::Control control); /** * @brief The signal is emmited when text send via Dali::Accessibility::Bridge::Say @@ -403,7 +402,7 @@ DALI_TOOLKIT_API AccessibilityReadingResumedSignalType &AccessibilityReadingResu * * @return The signal to connect to */ -DALI_TOOLKIT_API AccessibilityReadingCancelledSignalType &AccessibilityReadingCancelledSignal( Toolkit::Control control ); +DALI_TOOLKIT_API AccessibilityReadingCancelledSignalType& AccessibilityReadingCancelledSignal(Toolkit::Control control); /** * @brief The signal is emmited when text send via Dali::Accessibility::Bridge::Say @@ -411,7 +410,7 @@ DALI_TOOLKIT_API AccessibilityReadingCancelledSignalType &AccessibilityReadingCa * * @return The signal to connect to */ -DALI_TOOLKIT_API AccessibilityReadingStoppedSignalType &AccessibilityReadingStoppedSignal( Toolkit::Control control ); +DALI_TOOLKIT_API AccessibilityReadingStoppedSignalType& AccessibilityReadingStoppedSignal(Toolkit::Control control); /** * @brief The signal is emmited when accessibility client asks for object's name. @@ -423,7 +422,7 @@ DALI_TOOLKIT_API AccessibilityReadingStoppedSignalType &AccessibilityReadingStop * Priority is as above. If none is used, default implementation is provided. * @return [description] */ -DALI_TOOLKIT_API AccessibilityGetNameSignalType &AccessibilityGetNameSignal( Toolkit::Control control ); +DALI_TOOLKIT_API AccessibilityGetNameSignalType& AccessibilityGetNameSignal(Toolkit::Control control); /** * @brief The signal is emmited when accessibility client asks for object's description. @@ -435,7 +434,7 @@ DALI_TOOLKIT_API AccessibilityGetNameSignalType &AccessibilityGetNameSignal( Too * Priority is as above. If none is used, default implementation is provided. * @return signal handler */ -DALI_TOOLKIT_API AccessibilityGetDescriptionSignalType &AccessibilityGetDescriptionSignal( Toolkit::Control control ); +DALI_TOOLKIT_API AccessibilityGetDescriptionSignalType& AccessibilityGetDescriptionSignal(Toolkit::Control control); /** * @brief The signal is emitted when accessibility client call "DoGesture" method via IPC mechanism. @@ -443,7 +442,7 @@ DALI_TOOLKIT_API AccessibilityGetDescriptionSignalType &AccessibilityGetDescript * This signal allows developers to serve incoming gesture in specific way. * @return signal handler */ -DALI_TOOLKIT_API AccessibilityDoGestureSignalType &AccessibilityDoGestureSignal( Toolkit::Control control ); +DALI_TOOLKIT_API AccessibilityDoGestureSignalType& AccessibilityDoGestureSignal(Toolkit::Control control); /** * @brief The method allows connection with other actor with usage of concrete accessibility relation type. @@ -452,7 +451,7 @@ DALI_TOOLKIT_API AccessibilityDoGestureSignalType &AccessibilityDoGestureSignal( * @param destination Actor object * @param relation enumerated value describing relation */ -DALI_TOOLKIT_API void AppendAccessibilityRelation( Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation ); +DALI_TOOLKIT_API void AppendAccessibilityRelation(Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation); /** * @brief The method allows removing relation @@ -461,7 +460,7 @@ DALI_TOOLKIT_API void AppendAccessibilityRelation( Dali::Actor control, Actor de * @param destination Actor object * @param relation enumerated value describing relation */ -DALI_TOOLKIT_API void RemoveAccessibilityRelation( Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation ); +DALI_TOOLKIT_API void RemoveAccessibilityRelation(Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation); /** * @brief The method returns collection accessibility addresses representing objects connected with current object @@ -469,14 +468,14 @@ DALI_TOOLKIT_API void RemoveAccessibilityRelation( Dali::Actor control, Actor de * @param control object to append attribute to * @return std::vector, where index is casted value of Accessibility::RelationType and value is std::vector of type Accessibility::Address */ -DALI_TOOLKIT_API std::vector> GetAccessibilityRelations( Dali::Actor control ); +DALI_TOOLKIT_API std::vector> GetAccessibilityRelations(Dali::Actor control); /** * @brief The method removes all previously appended relations * * @param control object to append attribute to */ -DALI_TOOLKIT_API void ClearAccessibilityRelations( Dali::Actor control ); +DALI_TOOLKIT_API void ClearAccessibilityRelations(Dali::Actor control); /** * @brief The method allows to add or modify value matched with given key. @@ -486,21 +485,21 @@ DALI_TOOLKIT_API void ClearAccessibilityRelations( Dali::Actor control ); * @param key std::string value * @param value std::string value */ -DALI_TOOLKIT_API void AppendAccessibilityAttribute( Dali::Actor control, const std::string& key, const std::string value ); +DALI_TOOLKIT_API void AppendAccessibilityAttribute(Dali::Actor control, const std::string& key, const std::string value); /** * @brief The method erases key with its value from accessibility attributes * @param control object to append attribute to * @param key std::string value */ -DALI_TOOLKIT_API void RemoveAccessibilityAttribute( Dali::Actor control, const std::string& key ); +DALI_TOOLKIT_API void RemoveAccessibilityAttribute(Dali::Actor control, const std::string& key); /** * @brief The method clears accessibility attributes * * @param control object to append attribute to */ -DALI_TOOLKIT_API void ClearAccessibilityAttributes( Dali::Actor control ); +DALI_TOOLKIT_API void ClearAccessibilityAttributes(Dali::Actor control); /** * @brief The method inserts reading information of an accessible object into attributes @@ -508,7 +507,7 @@ DALI_TOOLKIT_API void ClearAccessibilityAttributes( Dali::Actor control ); * @param control object to append attribute to * @param types Reading information types */ -DALI_TOOLKIT_API void SetAccessibilityReadingInfoType( Dali::Actor control, const Dali::Accessibility::ReadingInfoTypes types ); +DALI_TOOLKIT_API void SetAccessibilityReadingInfoType(Dali::Actor control, const Dali::Accessibility::ReadingInfoTypes types); /** * @brief The method returns reading information of an accessible object @@ -516,7 +515,7 @@ DALI_TOOLKIT_API void SetAccessibilityReadingInfoType( Dali::Actor control, cons * @param control object to append attribute to * @return Reading information types */ -DALI_TOOLKIT_API Dali::Accessibility::ReadingInfoTypes GetAccessibilityReadingInfoType( Dali::Actor control ); +DALI_TOOLKIT_API Dali::Accessibility::ReadingInfoTypes GetAccessibilityReadingInfoType(Dali::Actor control); /** * @brief The method erases highlight. @@ -524,7 +523,7 @@ DALI_TOOLKIT_API Dali::Accessibility::ReadingInfoTypes GetAccessibilityReadingIn * @param control object to append attribute to * @return bool value, false when it is not possible or something went wrong, at the other way true. */ -DALI_TOOLKIT_API bool ClearAccessibilityHighlight( Dali::Actor control ); +DALI_TOOLKIT_API bool ClearAccessibilityHighlight(Dali::Actor control); /** * @brief The method grabs highlight. @@ -532,7 +531,7 @@ DALI_TOOLKIT_API bool ClearAccessibilityHighlight( Dali::Actor control ); * @param control object to append attribute to * @return bool value, false when it is not possible or something went wrong, at the other way true. */ -DALI_TOOLKIT_API bool GrabAccessibilityHighlight( Dali::Actor control ); +DALI_TOOLKIT_API bool GrabAccessibilityHighlight(Dali::Actor control); /** * @brief The metod presents bitset of control's states. @@ -540,7 +539,7 @@ DALI_TOOLKIT_API bool GrabAccessibilityHighlight( Dali::Actor control ); * @param control object to append attribute to * @return Dali::Accessibility::States is vector of enumerated State. */ -DALI_TOOLKIT_API Dali::Accessibility::States GetAccessibilityStates( Dali::Actor control ); +DALI_TOOLKIT_API Dali::Accessibility::States GetAccessibilityStates(Dali::Actor control); /** * @brief The method force sending notifications about current states to accessibility clients @@ -549,7 +548,7 @@ DALI_TOOLKIT_API Dali::Accessibility::States GetAccessibilityStates( Dali::Actor * @param states mask with states expected to broadcast * @param doRecursive flag pointing if notifications of children's state would be sent */ -DALI_TOOLKIT_API void NotifyAccessibilityStateChange( Dali::Actor control, Dali::Accessibility::States states, bool doRecursive ); +DALI_TOOLKIT_API void NotifyAccessibilityStateChange(Dali::Actor control, Dali::Accessibility::States states, bool doRecursive); /** * The method allows to set specific constructor for creating accessibility structure @@ -568,14 +567,14 @@ DALI_TOOLKIT_API void NotifyAccessibilityStateChange( Dali::Actor control, Dali: * * param constructor callback creating Accessible object */ -DALI_TOOLKIT_API void SetAccessibilityConstructor( Dali::Actor control, std::function(Dali::Actor)> constructor); +DALI_TOOLKIT_API void SetAccessibilityConstructor(Dali::Actor control, std::function(Dali::Actor)> constructor); /** * Returns accessibility object bound to actor, if any * * This method won't bound new accessibility object. Use Dali::Accessibility::Accessible::Get in that case. */ -DALI_TOOLKIT_API Dali::Accessibility::Accessible *GetBoundAccessibilityObject( Dali::Actor control ); +DALI_TOOLKIT_API Dali::Accessibility::Accessible* GetBoundAccessibilityObject(Dali::Actor control); } // namespace DevelControl diff --git a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.cpp b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.cpp old mode 100755 new mode 100644 index c8f9aeb..f50a912 --- a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,11 +25,10 @@ namespace Dali { namespace Toolkit { - const std::string EMPTY_STRING; -WebBackForwardListItem::WebBackForwardListItem( const Dali::WebEngineBackForwardListItem* item ) -: mWebEngineBackForwardListItem( item ) +WebBackForwardListItem::WebBackForwardListItem(const Dali::WebEngineBackForwardListItem* item) +: mWebEngineBackForwardListItem(item) { } diff --git a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.h b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.h old mode 100755 new mode 100644 index 44a3bc1..2ae0e35 --- a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.h +++ b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.h @@ -26,12 +26,10 @@ namespace Dali { - class WebEngineBackForwardListItem; namespace Toolkit { - /** * @addtogroup dali_toolkit_controls_web_view * @{ @@ -50,7 +48,7 @@ public: /** * @brief Creates a WebBackForwardListItem. */ - WebBackForwardListItem( const Dali::WebEngineBackForwardListItem* item ); + WebBackForwardListItem(const Dali::WebEngineBackForwardListItem* item); /** * @brief Destructor. @@ -82,7 +80,6 @@ public: std::string GetOriginalUrl() const; private: - const Dali::WebEngineBackForwardListItem* mWebEngineBackForwardListItem; }; diff --git a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.cpp b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.cpp old mode 100755 new mode 100644 index fe4e33b..75014f0 --- a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,9 @@ namespace Dali { namespace Toolkit { - -WebBackForwardList::WebBackForwardList( const Dali::WebEngineBackForwardList& list ) -: mWebEngineBackForwardList( list ) -, mWebBackForwardListItem( 0 ) +WebBackForwardList::WebBackForwardList(const Dali::WebEngineBackForwardList& list) +: mWebEngineBackForwardList(list), + mWebBackForwardListItem(0) { } @@ -39,13 +38,13 @@ WebBackForwardList::~WebBackForwardList() WebBackForwardListItem* WebBackForwardList::GetCurrentItem() { - mWebBackForwardListItem = WebBackForwardListItem( &mWebEngineBackForwardList.GetCurrentItem() ); + mWebBackForwardListItem = WebBackForwardListItem(&mWebEngineBackForwardList.GetCurrentItem()); return &mWebBackForwardListItem; } -WebBackForwardListItem* WebBackForwardList::GetItemAtIndex( uint32_t index ) +WebBackForwardListItem* WebBackForwardList::GetItemAtIndex(uint32_t index) { - mWebBackForwardListItem = WebBackForwardListItem( &mWebEngineBackForwardList.GetItemAtIndex( index ) ); + mWebBackForwardListItem = WebBackForwardListItem(&mWebEngineBackForwardList.GetItemAtIndex(index)); return &mWebBackForwardListItem; } diff --git a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.h b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.h old mode 100755 new mode 100644 index 144c02b..9dc81fc --- a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.h +++ b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_WEB_BACK_FORWARD_LIST_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ namespace Dali { - class WebEngineBackForwardList; namespace Toolkit @@ -49,7 +48,7 @@ public: /** * @brief Creates a WebBackForwardList. */ - WebBackForwardList( const Dali::WebEngineBackForwardList& list ); + WebBackForwardList(const Dali::WebEngineBackForwardList& list); /** * @brief Destructor. @@ -78,9 +77,8 @@ public: uint32_t GetItemCount() const; private: - const Dali::WebEngineBackForwardList& mWebEngineBackForwardList; + const Dali::WebEngineBackForwardList& mWebEngineBackForwardList; Dali::Toolkit::WebBackForwardListItem mWebBackForwardListItem; - }; /** diff --git a/dali-toolkit/devel-api/controls/web-view/web-context.cpp b/dali-toolkit/devel-api/controls/web-view/web-context.cpp old mode 100755 new mode 100644 index 1e0cbbd..c72012c --- a/dali-toolkit/devel-api/controls/web-view/web-context.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-context.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,8 @@ namespace Dali { namespace Toolkit { - -WebContext::WebContext( Dali::WebEngineContext& context) -: mWebEngineContext( context ) +WebContext::WebContext(Dali::WebEngineContext& context) +: mWebEngineContext(context) { } @@ -37,29 +36,29 @@ Dali::WebEngineContext::CacheModel WebContext::GetCacheModel() const return mWebEngineContext.GetCacheModel(); } -void WebContext::SetCacheModel(Dali::WebEngineContext::CacheModel cacheModel ) +void WebContext::SetCacheModel(Dali::WebEngineContext::CacheModel cacheModel) { - mWebEngineContext.SetCacheModel( cacheModel ); + mWebEngineContext.SetCacheModel(cacheModel); } -void WebContext::SetProxyUri( const std::string& uri ) +void WebContext::SetProxyUri(const std::string& uri) { - mWebEngineContext.SetProxyUri( uri ); + mWebEngineContext.SetProxyUri(uri); } -void WebContext::SetCertificateFilePath( const std::string& certificatePath ) +void WebContext::SetCertificateFilePath(const std::string& certificatePath) { - mWebEngineContext.SetCertificateFilePath( certificatePath ); + mWebEngineContext.SetCertificateFilePath(certificatePath); } -void WebContext::DisableCache( bool cacheDisabled ) +void WebContext::DisableCache(bool cacheDisabled) { - mWebEngineContext.DisableCache( cacheDisabled ); + mWebEngineContext.DisableCache(cacheDisabled); } -void WebContext::SetDefaultProxyAuth( const std::string& username, const std::string& password ) +void WebContext::SetDefaultProxyAuth(const std::string& username, const std::string& password) { - mWebEngineContext.SetDefaultProxyAuth( username, password ); + mWebEngineContext.SetDefaultProxyAuth(username, password); } void WebContext::DeleteWebDatabase() diff --git a/dali-toolkit/devel-api/controls/web-view/web-context.h b/dali-toolkit/devel-api/controls/web-view/web-context.h old mode 100755 new mode 100644 index 1640c70..ead4efd --- a/dali-toolkit/devel-api/controls/web-view/web-context.h +++ b/dali-toolkit/devel-api/controls/web-view/web-context.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_WEB_CONTEXT_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,18 +19,16 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include namespace Dali { - namespace Toolkit { - /** * @addtogroup dali_toolkit_controls_web_view * @{ @@ -45,13 +43,12 @@ namespace Toolkit class DALI_TOOLKIT_API WebContext { public: - /** * @brief Creates a WebContext. * * @param[in] context The context of web engine. */ - WebContext( Dali::WebEngineContext& context ); + WebContext(Dali::WebEngineContext& context); /** * @brief Destructor. @@ -70,14 +67,14 @@ public: * * @param[in] cacheModel The cache model */ - void SetCacheModel(Dali::WebEngineContext::CacheModel cacheModel ); + void SetCacheModel(Dali::WebEngineContext::CacheModel cacheModel); /** * @brief Sets the given proxy URI to network backend of specific context. * * @param[in] uri The proxy URI to set */ - void SetProxyUri( const std::string& uri ); + void SetProxyUri(const std::string& uri); /** * Adds CA certificates to persistent NSS certificate database @@ -89,7 +86,7 @@ public: * * @param[in] certificatePath path to a CA certificate file(s), see above for details */ - void SetCertificateFilePath( const std::string& certificatePath ); + void SetCertificateFilePath(const std::string& certificatePath); /** * Toggles the cache to be enabled or disabled @@ -99,7 +96,7 @@ public: * * @param[in] cacheDisabled enable or disable cache */ - void DisableCache( bool cacheDisabled ); + void DisableCache(bool cacheDisabled); /** * @brief Sets a proxy auth credential to network backend of specific context. @@ -107,7 +104,7 @@ public: * @param[in] username username to set * @param[in] password password to set */ - void SetDefaultProxyAuth( const std::string& username, const std::string& password ); + void SetDefaultProxyAuth(const std::string& username, const std::string& password); /** * Requests for deleting all web databases. @@ -133,8 +130,7 @@ public: void ClearCache(); private: - - Dali::WebEngineContext& mWebEngineContext; + Dali::WebEngineContext& mWebEngineContext; }; /** diff --git a/dali-toolkit/devel-api/controls/web-view/web-cookie-manager.cpp b/dali-toolkit/devel-api/controls/web-view/web-cookie-manager.cpp old mode 100755 new mode 100644 index ef6bd64..fba924a --- a/dali-toolkit/devel-api/controls/web-view/web-cookie-manager.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-cookie-manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,8 @@ namespace Dali { namespace Toolkit { - -WebCookieManager::WebCookieManager( Dali::WebEngineCookieManager& manager ) -: mWebEngineCookieManager( manager ) +WebCookieManager::WebCookieManager(Dali::WebEngineCookieManager& manager) +: mWebEngineCookieManager(manager) { } @@ -32,9 +31,9 @@ WebCookieManager::~WebCookieManager() { } -void WebCookieManager::SetCookieAcceptPolicy( Dali::WebEngineCookieManager::CookieAcceptPolicy cookieAcceptPolicy ) +void WebCookieManager::SetCookieAcceptPolicy(Dali::WebEngineCookieManager::CookieAcceptPolicy cookieAcceptPolicy) { - mWebEngineCookieManager.SetCookieAcceptPolicy( cookieAcceptPolicy ); + mWebEngineCookieManager.SetCookieAcceptPolicy(cookieAcceptPolicy); } Dali::WebEngineCookieManager::CookieAcceptPolicy WebCookieManager::GetCookieAcceptPolicy() const @@ -47,9 +46,9 @@ void WebCookieManager::ClearCookies() mWebEngineCookieManager.ClearCookies(); } -void WebCookieManager::SetPersistentStorage( const std::string& path, Dali::WebEngineCookieManager::CookiePersistentStorage storage ) +void WebCookieManager::SetPersistentStorage(const std::string& path, Dali::WebEngineCookieManager::CookiePersistentStorage storage) { - mWebEngineCookieManager.SetPersistentStorage( path, storage ); + mWebEngineCookieManager.SetPersistentStorage(path, storage); } } // namespace Toolkit diff --git a/dali-toolkit/devel-api/controls/web-view/web-cookie-manager.h b/dali-toolkit/devel-api/controls/web-view/web-cookie-manager.h old mode 100755 new mode 100644 index adb8481..a332e06 --- a/dali-toolkit/devel-api/controls/web-view/web-cookie-manager.h +++ b/dali-toolkit/devel-api/controls/web-view/web-cookie-manager.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_WEB_COOKIE_MANAGER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -31,7 +31,6 @@ class WebEngineCookieManager; namespace Toolkit { - /** * @addtogroup dali_toolkit_controls_web_view * @{ @@ -47,12 +46,11 @@ namespace Toolkit class DALI_TOOLKIT_API WebCookieManager { public: - /** * @brief Creates a WebCookieManager. * @param[in] manager A #Dali::WebEngineCookieManager */ - WebCookieManager( Dali::WebEngineCookieManager& manager ); + WebCookieManager(Dali::WebEngineCookieManager& manager); /** * @brief Destructor. @@ -67,7 +65,7 @@ public: * * @param[in] policy A #Dali::WebEngineCookieManager::CookieAcceptPolicy */ - void SetCookieAcceptPolicy(Dali::WebEngineCookieManager::CookieAcceptPolicy policy ); + void SetCookieAcceptPolicy(Dali::WebEngineCookieManager::CookieAcceptPolicy policy); /** * @brief Gets the cookie acceptance policy. The default is Toolkit::WebCookieManager::CookieAcceptPolicy::NO_THIRD_PARTY. @@ -93,11 +91,10 @@ public: * @param[in] path The path where to read/write Cookies * @param[in] storage The type of storage */ - void SetPersistentStorage( const std::string& path, Dali::WebEngineCookieManager::CookiePersistentStorage storage ); + void SetPersistentStorage(const std::string& path, Dali::WebEngineCookieManager::CookiePersistentStorage storage); private: - - Dali::WebEngineCookieManager& mWebEngineCookieManager; + Dali::WebEngineCookieManager& mWebEngineCookieManager; }; /** diff --git a/dali-toolkit/devel-api/controls/web-view/web-settings.cpp b/dali-toolkit/devel-api/controls/web-view/web-settings.cpp index 7b6dc13..d39a93e 100755 --- a/dali-toolkit/devel-api/controls/web-view/web-settings.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-settings.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,9 +25,8 @@ namespace Dali { namespace Toolkit { - -WebSettings::WebSettings( Dali::WebEngineSettings& settings ) -: mWebEngineSettings( settings ) +WebSettings::WebSettings(Dali::WebEngineSettings& settings) +: mWebEngineSettings(settings) { } @@ -35,14 +34,14 @@ WebSettings::~WebSettings() { } -void WebSettings::AllowMixedContents( bool allowed ) +void WebSettings::AllowMixedContents(bool allowed) { - mWebEngineSettings.AllowMixedContents( allowed ); + mWebEngineSettings.AllowMixedContents(allowed); } -void WebSettings::EnableSpatialNavigation( bool enabled ) +void WebSettings::EnableSpatialNavigation(bool enabled) { - mWebEngineSettings.AllowMixedContents( enabled ); + mWebEngineSettings.AllowMixedContents(enabled); } int WebSettings::GetDefaultFontSize() const @@ -50,19 +49,34 @@ int WebSettings::GetDefaultFontSize() const return mWebEngineSettings.GetDefaultFontSize(); } -void WebSettings::SetDefaultFontSize( int defaultFontSize ) +void WebSettings::SetDefaultFontSize(int defaultFontSize) +{ + mWebEngineSettings.SetDefaultFontSize(defaultFontSize); +} + +void WebSettings::EnableWebSecurity(bool enabled) { - mWebEngineSettings.SetDefaultFontSize( defaultFontSize ); + mWebEngineSettings.EnableWebSecurity(enabled); } -void WebSettings::EnableWebSecurity( bool enabled ) +void WebSettings::EnableCacheBuilder(bool enabled) { - mWebEngineSettings.EnableWebSecurity( enabled ); + mWebEngineSettings.EnableCacheBuilder(enabled); } -void WebSettings::AllowFileAccessFromExternalUrl( bool allowed ) +void WebSettings::UseScrollbarThumbFocusNotifications(bool used) { - mWebEngineSettings.AllowFileAccessFromExternalUrl( allowed ); + mWebEngineSettings.UseScrollbarThumbFocusNotifications(used); +} + +void WebSettings::EnableDoNotTrack( bool enabled ) +{ + mWebEngineSettings.EnableDoNotTrack(enabled); +} + +void WebSettings::AllowFileAccessFromExternalUrl(bool allowed) +{ + mWebEngineSettings.AllowFileAccessFromExternalUrl(allowed); } bool WebSettings::IsJavaScriptEnabled() const @@ -70,14 +84,134 @@ bool WebSettings::IsJavaScriptEnabled() const return mWebEngineSettings.IsJavaScriptEnabled(); } -void WebSettings::EnableJavaScript( bool enabled ) +void WebSettings::EnableJavaScript(bool enabled) +{ + mWebEngineSettings.EnableJavaScript(enabled); +} + +bool WebSettings::IsAutoFittingEnabled() const +{ + return mWebEngineSettings.IsAutoFittingEnabled(); +} + +void WebSettings::EnableAutoFitting(bool enabled) +{ + mWebEngineSettings.EnableAutoFitting(enabled); +} + +bool WebSettings::ArePluginsEnabled() const +{ + return mWebEngineSettings.ArePluginsEnabled(); +} + +void WebSettings::EnablePlugins(bool enabled) +{ + mWebEngineSettings.EnablePlugins(enabled); +} + +bool WebSettings::IsPrivateBrowsingEnabled() const +{ + return mWebEngineSettings.IsPrivateBrowsingEnabled(); +} + +void WebSettings::EnablePrivateBrowsing(bool enabled) +{ + mWebEngineSettings.EnablePrivateBrowsing(enabled); +} + +bool WebSettings::IsLinkMagnifierEnabled() const +{ + return mWebEngineSettings.IsLinkMagnifierEnabled(); +} + +void WebSettings::EnableLinkMagnifier(bool enabled) +{ + mWebEngineSettings.EnableLinkMagnifier(enabled); +} + +bool WebSettings::IsKeypadWithoutUserActionUsed() const +{ + return mWebEngineSettings.IsKeypadWithoutUserActionUsed(); +} + +void WebSettings::UseKeypadWithoutUserAction(bool used) +{ + mWebEngineSettings.UseKeypadWithoutUserAction(used); +} + +bool WebSettings::IsAutofillPasswordFormEnabled() const +{ + return mWebEngineSettings.IsAutofillPasswordFormEnabled(); +} + +void WebSettings::EnableAutofillPasswordForm(bool enabled) +{ + mWebEngineSettings.EnableAutofillPasswordForm(enabled); +} + +bool WebSettings::IsFormCandidateDataEnabled() const +{ + return mWebEngineSettings.IsFormCandidateDataEnabled(); +} + +void WebSettings::EnableFormCandidateData( bool enabled ) +{ + mWebEngineSettings.EnableFormCandidateData(enabled); +} + +bool WebSettings::IsTextSelectionEnabled() const +{ + return mWebEngineSettings.IsTextSelectionEnabled(); +} + +void WebSettings::EnableTextSelection( bool enabled ) +{ + return mWebEngineSettings.EnableTextSelection(enabled); +} + +bool WebSettings::IsTextAutosizingEnabled() const +{ + return mWebEngineSettings.IsTextAutosizingEnabled(); +} + +void WebSettings::EnableTextAutosizing( bool enabled ) +{ + return mWebEngineSettings.EnableTextAutosizing(enabled); +} + +bool WebSettings::IsArrowScrollEnabled() const +{ + return mWebEngineSettings.IsArrowScrollEnabled(); +} + +void WebSettings::EnableArrowScroll( bool enabled ) +{ + return mWebEngineSettings.EnableArrowScroll(enabled); +} + +bool WebSettings::IsClipboardEnabled() const +{ + return mWebEngineSettings.IsClipboardEnabled(); +} + +void WebSettings::EnableClipboard( bool enabled ) +{ + return mWebEngineSettings.EnableClipboard(enabled); +} + +bool WebSettings::IsImePanelEnabled() const +{ + return mWebEngineSettings.IsImePanelEnabled(); +} + +void WebSettings::EnableImePanel( bool enabled ) { - mWebEngineSettings.EnableJavaScript( enabled ); + return mWebEngineSettings.EnableImePanel(enabled); } -void WebSettings::AllowScriptsOpenWindows( bool allowed ) +void WebSettings::AllowScriptsOpenWindows(bool allowed) { - mWebEngineSettings.AllowScriptsOpenWindows( allowed ); + mWebEngineSettings.AllowScriptsOpenWindows(allowed); } bool WebSettings::AreImagesLoadedAutomatically() const @@ -85,9 +219,9 @@ bool WebSettings::AreImagesLoadedAutomatically() const return mWebEngineSettings.AreImagesLoadedAutomatically(); } -void WebSettings::AllowImagesLoadAutomatically( bool automatic ) +void WebSettings::AllowImagesLoadAutomatically(bool automatic) { - mWebEngineSettings.AllowImagesLoadAutomatically( automatic ); + mWebEngineSettings.AllowImagesLoadAutomatically(automatic); } std::string WebSettings::GetDefaultTextEncodingName() const @@ -95,9 +229,9 @@ std::string WebSettings::GetDefaultTextEncodingName() const return mWebEngineSettings.GetDefaultTextEncodingName(); } -void WebSettings::SetDefaultTextEncodingName( const std::string& defaultTextEncodingName ) +void WebSettings::SetDefaultTextEncodingName(const std::string& defaultTextEncodingName) { - mWebEngineSettings.SetDefaultTextEncodingName( defaultTextEncodingName ); + mWebEngineSettings.SetDefaultTextEncodingName(defaultTextEncodingName); } } // namespace Toolkit diff --git a/dali-toolkit/devel-api/controls/web-view/web-settings.h b/dali-toolkit/devel-api/controls/web-view/web-settings.h index dc46e7c..ba8b1fa 100755 --- a/dali-toolkit/devel-api/controls/web-view/web-settings.h +++ b/dali-toolkit/devel-api/controls/web-view/web-settings.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_WEB_SETTINGS_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,6 @@ class WebEngineSettings; namespace Toolkit { - /** * @addtogroup dali_toolkit_controls_web_view * @{ @@ -51,7 +50,7 @@ public: * * @param[in] settings A settings of web engine. */ - WebSettings( Dali::WebEngineSettings& settings ); + WebSettings(Dali::WebEngineSettings& settings); /** * @brief Destructor. @@ -64,7 +63,7 @@ public: * @param[in] allowed if true, allow to run mixed contents, * otherwise not allow */ - void AllowMixedContents( bool allowed ); + void AllowMixedContents(bool allowed); /** * @brief Enable the spatial navigation or not. @@ -72,7 +71,7 @@ public: * @param[in] enabled if true, use spatial navigation, * otherwise to disable */ - void EnableSpatialNavigation( bool enabled ); + void EnableSpatialNavigation(bool enabled); /** * @brief Returns the default font size in pixel. The default value is 16. @@ -86,7 +85,7 @@ public: * * @param[in] defaultFontSize A new default font size to set */ - void SetDefaultFontSize( int defaultFontSize ); + void SetDefaultFontSize(int defaultFontSize); /** * @brief Enables/disables web security. @@ -94,7 +93,30 @@ public: * @param[in] enabled if true, to enable the web security * otherwise to disable */ - void EnableWebSecurity( bool enabled ); + void EnableWebSecurity(bool enabled); + + /** + * @brief Enables/disables cache builder. + * + * @param[in] enabled if true, to enable the cache builder + * otherwise to disable + */ + void EnableCacheBuilder( bool enabled ); + + /** + * @brief Used/Unused uses scrollbar thumb focus notifications. The default is used. + * + * @param[in] used True if uses scrollbar thumb focus notifications, false otherwise + */ + void UseScrollbarThumbFocusNotifications ( bool used ); + + /** + * @brief Enable/disables do not track executing. + * + * @param[in] enabled if true, to enable do not track + * otherwise to disable + */ + void EnableDoNotTrack( bool enabled ); /** * @brief Allow/Disallow file access from external url @@ -102,7 +124,7 @@ public: * @param[in] allowed if true, to allow file access from external url * otherwise to disallow */ - void AllowFileAccessFromExternalUrl( bool allowed ); + void AllowFileAccessFromExternalUrl(bool allowed); /** * @brief Returns whether JavaScript can be executable. The default is true. @@ -116,7 +138,175 @@ public: * * @param[in] enabled True if JavaScript executing is enabled, false otherwise */ - void EnableJavaScript( bool enabled ); + void EnableJavaScript(bool enabled); + + /** + * @brief Returns whether auto fitting can be executable. The default is true. + * + * @return true if auto fitting executing is enabled, false otherwise + */ + bool IsAutoFittingEnabled() const; + + /** + * @brief Enables/disables auto fitting executing. The default is enabled. + * + * @param[in] enabled True if auto fitting executing is enabled, false otherwise + */ + void EnableAutoFitting( bool enabled ); + + /** + * @brief Returns whether plugins can be executable. The default is true. + * + * @return true if plugins executing is enabled, false otherwise + */ + bool ArePluginsEnabled() const; + + /** + * @brief Enables/disables Plugins executing. The default is enabled. + * + * @param[in] enabled True if Plugins executing is enabled, false otherwise + */ + void EnablePlugins( bool enabled ); + + /** + * @brief Returns whether private browsing can be executable. The default is true. + * + * @return true if private browsing executing is enabled, false otherwise + */ + bool IsPrivateBrowsingEnabled() const; + + /** + * @brief Enables/disables private browsing executing. The default is enabled. + * + * @param[in] enabled True if private browsing executing is enabled, false otherwise + */ + void EnablePrivateBrowsing( bool enabled ); + + /** + * @brief Returns whether link magnifier can be executable. The default is true. + * + * @return true if link magnifier executing is enabled, false otherwise + */ + bool IsLinkMagnifierEnabled() const; + + /** + * @brief Enables/disables link magnifier executing. The default is enabled. + * + * @param[in] enabled True if link magnifier executing is enabled, false otherwise + */ + void EnableLinkMagnifier( bool enabled ); + + /** + * @brief Returns whether uses keypad without user action can be executable. The default is true. + * + * @return true if keypad without user action executing is used, false otherwise + */ + bool IsKeypadWithoutUserActionUsed() const; + + /** + * @brief Uses/Unused keypad without user action executing. The default is used. + * + * @param[in] used True if keypad without user action executing is used, false otherwise + */ + void UseKeypadWithoutUserAction( bool used ); + + /** + * @brief Returns whether autofill password form can be executable. The default is true. + * + * @return true if autofill password form executing is enabled, false otherwise + */ + bool IsAutofillPasswordFormEnabled() const; + + /** + * @brief Enables/disables autofill password form executing. The default is enabled. + * + * @param[in] enabled True if autofill password form executing is enabled, false otherwise + */ + void EnableAutofillPasswordForm( bool enabled ); + + /** + * @brief Returns whether form candidate data can be executable. The default is true. + * + * @return true if form candidate data executing is enabled, false otherwise + */ + bool IsFormCandidateDataEnabled() const; + + /** + * @brief Enables/disables form candidate data executing. The default is enabled. + * + * @param[in] enabled True if form candidate data executing is enabled, false otherwise + */ + void EnableFormCandidateData( bool enabled ); + + /** + * @brief Returns whether text selection can be executable. The default is true. + * + * @return true if text selection executing is enabled, false otherwise + */ + bool IsTextSelectionEnabled() const; + + /** + * brief Enables/disables text selection executing. The default is enabled. + * + * @param[in] enabled True if text selection executing is enabled, false otherwise + */ + void EnableTextSelection( bool enabled ); + + /** + * @brief Returns whether text autosizing can be executable. The default is true. + * + * @return true if text autosizing executing is enabled, false otherwise + */ + bool IsTextAutosizingEnabled() const; + + /** + * @brief Enables/disables text autosizing executing. The default is enabled. + * + * @param[in] enabled True if text autosizing executing is enabled, false otherwise + */ + void EnableTextAutosizing( bool enabled ); + + /** + * @brief Returns whether arrow scroll can be executable. The default is true. + * + * @return true if arrow scroll executing is enabled, false otherwise + */ + bool IsArrowScrollEnabled() const; + + /** + * @brief Enables/disables arrow scroll executing. The default is enabled. + * + * @param[in] enabled True if arrow scroll executing is enabled, false otherwise + */ + void EnableArrowScroll( bool enabled ); + + /** + * @brief Returns whether clipboard can be executable. The default is true. + * + * @return true if clipboard executing is enabled, false otherwise + */ + bool IsClipboardEnabled() const; + + /** + * @brief Enables/disables clipboard executing. The default is enabled. + * + * @param[in] enabled True if clipboard is enabled, false otherwise + */ + void EnableClipboard( bool enabled ); + + /** + * @brief Returns whether ime panel can be executable. The default is true. + * + * @return true if ime panel executing is enabled, false otherwise + */ + bool IsImePanelEnabled() const; + + /** + * @brief Enables/disables ime panel executing. The default is enabled. + * + * @param[in] enabled True if ime panel executing is enabled, false otherwise + */ + void EnableImePanel( bool enabled ); /** * @brief Allow if the scripts can open new windows. @@ -124,7 +314,7 @@ public: * @param[in] allowed if true, the scripts can open new windows, * otherwise not */ - void AllowScriptsOpenWindows( bool allowed ); + void AllowScriptsOpenWindows(bool allowed); /** * @brief Returns whether images can be loaded automatically. The default is true. @@ -138,7 +328,7 @@ public: * * @param[in] automatic True if images are loaded automatically, false otherwise */ - void AllowImagesLoadAutomatically( bool automatic ); + void AllowImagesLoadAutomatically(bool automatic); /** * @brief Gets the default text encoding name (e.g. UTF-8). @@ -152,7 +342,7 @@ public: * * @param[in] defaultTextEncodingName The default text encoding name */ - void SetDefaultTextEncodingName( const std::string& defaultTextEncodingName ); + void SetDefaultTextEncodingName(const std::string& defaultTextEncodingName); private: Dali::WebEngineSettings& mWebEngineSettings; diff --git a/dali-toolkit/devel-api/controls/web-view/web-view.cpp b/dali-toolkit/devel-api/controls/web-view/web-view.cpp old mode 100755 new mode 100644 index 4c9de03..201f280 --- a/dali-toolkit/devel-api/controls/web-view/web-view.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-view.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ // INTERNAL INCLUDES #include +#include namespace Dali { @@ -58,6 +59,11 @@ WebView WebView::New(const std::string& locale, const std::string& timezoneId) return Internal::WebView::New(locale, timezoneId); } +WebView WebView::New(int argc, char** argv) +{ + return Internal::WebView::New(argc, argv); +} + WebView WebView::DownCast(BaseHandle handle) { return Control::DownCast(handle); @@ -65,22 +71,27 @@ WebView WebView::DownCast(BaseHandle handle) Dali::Toolkit::WebSettings* WebView::GetSettings() const { - return Dali::Toolkit::GetImpl( *this ).GetSettings(); + return Dali::Toolkit::GetImpl(*this).GetSettings(); } Dali::Toolkit::WebContext* WebView::GetContext() const { - return Dali::Toolkit::GetImpl( *this ).GetContext(); + return Dali::Toolkit::GetImpl(*this).GetContext(); } Dali::Toolkit::WebCookieManager* WebView::GetCookieManager() const { - return Dali::Toolkit::GetImpl( *this ).GetCookieManager(); + return Dali::Toolkit::GetImpl(*this).GetCookieManager(); } Dali::Toolkit::WebBackForwardList* WebView::GetBackForwardList() const { - return Dali::Toolkit::GetImpl( *this ).GetBackForwardList(); + return Dali::Toolkit::GetImpl(*this).GetBackForwardList(); +} + +Dali::Toolkit::ImageView& WebView::GetFavicon() +{ + return Dali::Toolkit::GetImpl(*this).GetFavicon(); } void WebView::LoadUrl(const std::string& url) @@ -113,9 +124,9 @@ void WebView::Resume() Dali::Toolkit::GetImpl(*this).Resume(); } -void WebView::ScrollBy( int deltaX, int deltaY ) +void WebView::ScrollBy(int deltaX, int deltaY) { - Dali::Toolkit::GetImpl( *this ).ScrollBy( deltaX, deltaY ); + Dali::Toolkit::GetImpl(*this).ScrollBy(deltaX, deltaY); } bool WebView::CanGoForward() @@ -153,16 +164,56 @@ void WebView::AddJavaScriptMessageHandler(const std::string& exposedObjectName, Dali::Toolkit::GetImpl(*this).AddJavaScriptMessageHandler(exposedObjectName, handler); } +void WebView::RegisterJavaScriptAlertCallback( Dali::WebEnginePlugin::JavaScriptAlertCallback callback ) +{ + Dali::Toolkit::GetImpl( *this ).RegisterJavaScriptAlertCallback( callback ); +} + +void WebView::JavaScriptAlertReply() +{ + Dali::Toolkit::GetImpl( *this ).JavaScriptAlertReply(); +} + +void WebView::RegisterJavaScriptConfirmCallback( Dali::WebEnginePlugin::JavaScriptConfirmCallback callback ) +{ + Dali::Toolkit::GetImpl( *this ).RegisterJavaScriptConfirmCallback( callback ); +} + +void WebView::JavaScriptConfirmReply( bool confirmed ) +{ + Dali::Toolkit::GetImpl( *this ).JavaScriptConfirmReply( confirmed ); +} + +void WebView::RegisterJavaScriptPromptCallback( Dali::WebEnginePlugin::JavaScriptPromptCallback callback ) +{ + Dali::Toolkit::GetImpl( *this ).RegisterJavaScriptPromptCallback( callback ); +} + +void WebView::JavaScriptPromptReply( const std::string& result ) +{ + Dali::Toolkit::GetImpl( *this ).JavaScriptPromptReply( result ); +} + void WebView::ClearHistory() { Dali::Toolkit::GetImpl(*this).ClearHistory(); } +void WebView::ClearAllTilesResources() +{ + Dali::Toolkit::GetImpl( *this ).ClearAllTilesResources(); +} + WebView::WebViewPageLoadSignalType& WebView::PageLoadStartedSignal() { return Dali::Toolkit::GetImpl(*this).PageLoadStartedSignal(); } +WebView::WebViewPageLoadSignalType& WebView::PageLoadInProgressSignal() +{ + return Dali::Toolkit::GetImpl( *this ).PageLoadInProgressSignal(); +} + WebView::WebViewPageLoadSignalType& WebView::PageLoadFinishedSignal() { return Dali::Toolkit::GetImpl(*this).PageLoadFinishedSignal(); @@ -175,7 +226,12 @@ WebView::WebViewPageLoadErrorSignalType& WebView::PageLoadErrorSignal() WebView::WebViewScrollEdgeReachedSignalType& WebView::ScrollEdgeReachedSignal() { - return Dali::Toolkit::GetImpl( *this ).ScrollEdgeReachedSignal(); + return Dali::Toolkit::GetImpl(*this).ScrollEdgeReachedSignal(); +} + +WebView::WebViewUrlChangedSignalType& WebView::UrlChangedSignal() +{ + return Dali::Toolkit::GetImpl( *this ).UrlChangedSignal(); } WebView::WebView(Internal::WebView& implementation) diff --git a/dali-toolkit/devel-api/controls/web-view/web-view.h b/dali-toolkit/devel-api/controls/web-view/web-view.h old mode 100755 new mode 100644 index 2fa6433..13ce3c0 --- a/dali-toolkit/devel-api/controls/web-view/web-view.h +++ b/dali-toolkit/devel-api/controls/web-view/web-view.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_WEB_VIEW_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,13 +22,14 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { namespace Toolkit { +class ImageView; class WebBackForwardList; class WebContext; class WebCookieManager; @@ -55,7 +56,6 @@ class WebView; class DALI_TOOLKIT_API WebView : public Control { public: - /** * @brief Enumeration for the start and end property ranges for this control. */ @@ -80,27 +80,43 @@ public: /** * @brief The user agent string. - * @details Name "userAgent", type Property::STRING. + * @details name "userAgent", type Property::STRING. */ USER_AGENT, /** * @brief The current position of scroll. - * @details Name "scrollPosition", type Property::VECTOR2. + * @details name "scrollPosition", type Property::VECTOR2. */ SCROLL_POSITION, /** - * @brief The current position of scroll. - * @details Name "scrollSize", type Property::VECTOR2. Read-only. + * @brief The current size of scroll. + * @details name "scrollSize", type Property::VECTOR2. + * @note The value is read-only. */ SCROLL_SIZE, /** - * @brief The current position of scroll. - * @details Name "contentSize", type Property::VECTOR2. Read-only. + * @brief The current size of content. + * @details name "contentSize", type Property::VECTOR2. + * @note The value is read-only. */ CONTENT_SIZE, + + /** + * @brief The title of web page. + * @details name "title", type Property::STRING. + * @note The value is read-only. + */ + TITLE, + + /** + * @brief Whether video hole is enabled or not. + * @details name "videoHoleEnabled", type Property::BOOLEAN. + * @note The value is read-only. + */ + VIDEO_HOLE_ENABLED, }; }; @@ -109,96 +125,42 @@ public: */ enum class LoadErrorCode { - /** - * @brief Unknown. - */ - UNKNOWN = 0, - - /** - * @brief User canceled. - */ - CANCELED, - - /** - * @brief Can't show the page for this MIME type. - */ - CANT_SUPPORT_MIMETYPE, - - /** - * @brief File IO error. - */ - FAILED_FILE_IO, - - /** - * @brief Cannot connect to the network. - */ - CANT_CONNECT, - - /** - * @brief Fail to look up host from the DNS. - */ - CANT_LOOKUP_HOST, - - /** - * @brief Fail to SSL/TLS handshake. - */ - FAILED_TLS_HANDSHAKE, - - /** - * @brief Received certificate is invalid. - */ - INVALID_CERTIFICATE, - - /** - * @brief Connection timeout. - */ - REQUEST_TIMEOUT, - - /** - * @brief Too many redirects. - */ - TOO_MANY_REDIRECTS, - - /** - * @brief Too many requests during this load. - */ - TOO_MANY_REQUESTS, - - /** - * @brief Malformed URL. - */ - BAD_URL, - - /** - * @brief Unsupported scheme. - */ - UNSUPPORTED_SCHEME, - - /** - * @brief User authentication failed on the server. - */ - AUTHENTICATION, - - /** - * @brief Web server has an internal server error. - */ - INTERNAL_SERVER + UNKNOWN = 0, ///< Unknown. + CANCELED, ///< User canceled. + CANT_SUPPORT_MIMETYPE, ///< Can't show the page for this MIME type. + FAILED_FILE_IO, ///< File IO error. + CANT_CONNECT, ///< Cannot connect to the network. + CANT_LOOKUP_HOST, ///< Fail to look up host from the DNS. + FAILED_TLS_HANDSHAKE, ///< Fail to SSL/TLS handshake. + INVALID_CERTIFICATE, ///< Received certificate is invalid. + REQUEST_TIMEOUT, ///< Connection timeout. + TOO_MANY_REDIRECTS, ///< Too many redirects. + TOO_MANY_REQUESTS, ///< Too many requests during this load. + BAD_URL, ///< Malformed URL. + UNSUPPORTED_SCHEME, ///< Unsupported scheme. + AUTHENTICATION, ///< User authentication failed on the server. + INTERNAL_SERVER ///< Web server has an internal server error. }; /** * @brief WebView signal type related with page loading. */ - typedef Signal WebViewPageLoadSignalType; + using WebViewPageLoadSignalType = Signal; /** * @brief WebView signal type related with page loading error. */ - typedef Signal WebViewPageLoadErrorSignalType; + using WebViewPageLoadErrorSignalType = Signal; /** * @brief WebView signal type related with scroll edge reached. */ - typedef Signal WebViewScrollEdgeReachedSignalType; + using WebViewScrollEdgeReachedSignalType = Signal; + + /** + * @brief WebView signal type related with url changed. + */ + using WebViewUrlChangedSignalType = Signal; public: /** @@ -218,6 +180,14 @@ public: static WebView New(const std::string& locale, const std::string& timezoneId); /** + * @brief Creates an initialized WebView. + * + * @param [in] argc The count of arguments of Applications + * @param [in] argv The string array of arguments of Applications + */ + static WebView New(int argc, char** argv); + + /** * @brief Creates an uninitialized WebView. */ WebView(); @@ -276,6 +246,13 @@ public: Dali::Toolkit::WebBackForwardList* GetBackForwardList() const; /** + * @brief Get Favicon of web page. + * + * @return Handle to a fav icon + */ + Dali::Toolkit::ImageView& GetFavicon(); + + /** * @brief Loads a web page based on a given URL. * * @param [in] url The URL of the resource to load @@ -314,7 +291,7 @@ public: * @param[in] deltaX The delta x of scroll * @param[in] deltaY The delta y of scroll */ - void ScrollBy( int deltaX, int deltaY ); + void ScrollBy(int deltaX, int deltaY); /** * @brief Returns whether forward is possible. @@ -382,11 +359,54 @@ public: void AddJavaScriptMessageHandler(const std::string& exposedObjectName, std::function handler); /** + * @brief Register alert callback for javascript. + * + * @param[in] callback The callback function to be called by the JavaScript runtime. + */ + void RegisterJavaScriptAlertCallback(Dali::WebEnginePlugin::JavaScriptAlertCallback callback); + + /** + * @brief Reply for JavaScript alert. + */ + void JavaScriptAlertReply(); + + /** + * @brief Register confirm callback for javascript. + * + * @param[in] callback The callback function to be called by the JavaScript runtime. + */ + void RegisterJavaScriptConfirmCallback(Dali::WebEnginePlugin::JavaScriptConfirmCallback callback); + + /** + * @brief Reply for JavaScript confirm. + * @param[in] confirmed True if confirmed, false otherwise + */ + void JavaScriptConfirmReply(bool confirmed); + + /** + * @brief Register prompt callback for javascript. + * + * @param[in] callback The callback function to be called by the JavaScript runtime. + */ + void RegisterJavaScriptPromptCallback(Dali::WebEnginePlugin::JavaScriptPromptCallback callback); + + /** + * @brief Reply for JavaScript prompt. + * @param[in] result The result from input-field of prompt popup. + */ + void JavaScriptPromptReply(const std::string& result); + + /** * @brief Clears the history of Web. */ void ClearHistory(); /** + * @brief Clears all tiles resources of Web. + */ + void ClearAllTilesResources(); + + /** * @brief Connects to this signal to be notified when page loading is started. * * @return A signal object to connect with @@ -394,6 +414,13 @@ public: WebViewPageLoadSignalType& PageLoadStartedSignal(); /** + * @brief Connects to this signal to be notified when page loading is in progress. + * + * @return A signal object to connect with. + */ + WebViewPageLoadSignalType& PageLoadInProgressSignal(); + + /** * @brief Connects to this signal to be notified when page loading is finished. * * @return A signal object to connect with @@ -414,6 +441,13 @@ public: */ WebViewScrollEdgeReachedSignalType& ScrollEdgeReachedSignal(); + /** + * @brief Connects to this signal to be notified when url is changed. + * + * @return A signal object to connect with. + */ + WebViewUrlChangedSignalType& UrlChangedSignal(); + public: // Not intended for application developers /// @cond internal /** diff --git a/dali-toolkit/devel-api/file.list b/dali-toolkit/devel-api/file.list index f43ca09..0e1ec7d 100755 --- a/dali-toolkit/devel-api/file.list +++ b/dali-toolkit/devel-api/file.list @@ -9,6 +9,7 @@ SET( devel_api_src_files ${devel_api_src_dir}/builder/builder.cpp ${devel_api_src_dir}/builder/json-parser.cpp ${devel_api_src_dir}/builder/tree-node.cpp + ${devel_api_src_dir}/controls/accessible-impl.cpp ${devel_api_src_dir}/controls/control-devel.cpp ${devel_api_src_dir}/controls/control-wrapper.cpp ${devel_api_src_dir}/controls/control-wrapper-impl.cpp @@ -81,6 +82,7 @@ SET( devel_api_accessibility-manager_header_files ) SET( devel_api_controls_header_files + ${devel_api_src_dir}/controls/accessible-impl.h ${devel_api_src_dir}/controls/control-depth-index-ranges.h ${devel_api_src_dir}/controls/control-devel.h ${devel_api_src_dir}/controls/control-wrapper.h diff --git a/dali-toolkit/devel-api/layouting/flex-node.cpp b/dali-toolkit/devel-api/layouting/flex-node.cpp index aa46e6f..c3636dc 100644 --- a/dali-toolkit/devel-api/layouting/flex-node.cpp +++ b/dali-toolkit/devel-api/layouting/flex-node.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -162,7 +162,7 @@ SizeTuple Node::MeasureNode(float width, int widthMode, float height, int height Toolkit::Flex::SizeTuple nodeSize{8, 8}; // Default size set to 8,8 to aid bug detection. if(mImpl->mMeasureCallback && mImpl->mActor.GetHandle()) { - DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MeasureNode MeasureCallback executing on %s\n", mImpl->mActor.GetHandle().GetProperty< std::string >( Dali::Actor::Property::NAME ).c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MeasureNode MeasureCallback executing on %s\n", mImpl->mActor.GetHandle().GetProperty(Dali::Actor::Property::NAME).c_str()); mImpl->mMeasureCallback(mImpl->mActor.GetHandle(), width, widthMode, height, heightMode, &nodeSize); } DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MeasureNode nodeSize width:%f height:%f\n", nodeSize.width, nodeSize.height); diff --git a/dali-toolkit/devel-api/layouting/flex-node.h b/dali-toolkit/devel-api/layouting/flex-node.h index 5a73458..d19c90b 100644 --- a/dali-toolkit/devel-api/layouting/flex-node.h +++ b/dali-toolkit/devel-api/layouting/flex-node.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_LAYOUTING_FLEX_NODE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,7 +115,7 @@ struct SizeTuple * @note int, height measure specification mode * @note SizeTuple, return value */ -using MeasureCallback = void (*)(Dali::Actor, float , int , float , int, SizeTuple *); +using MeasureCallback = void (*)(Dali::Actor, float, int, float, int, SizeTuple*); /** * This class provides the API for calling into the Flex layout implementation. diff --git a/dali-toolkit/devel-api/shader-effects/alpha-discard-effect.cpp b/dali-toolkit/devel-api/shader-effects/alpha-discard-effect.cpp index 2e049f1..3b3933b 100644 --- a/dali-toolkit/devel-api/shader-effects/alpha-discard-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/alpha-discard-effect.cpp @@ -18,14 +18,13 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { namespace Toolkit { - Property::Map CreateAlphaDiscardEffect() { Property::Map map; diff --git a/dali-toolkit/devel-api/shader-effects/dissolve-effect.cpp b/dali-toolkit/devel-api/shader-effects/dissolve-effect.cpp index e8c1b7e..153dc5f 100644 --- a/dali-toolkit/devel-api/shader-effects/dissolve-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/dissolve-effect.cpp @@ -25,11 +25,9 @@ namespace Dali { - namespace Toolkit { - -void DissolveEffectSetCentralLine( Actor& actor, const Vector2& position, const Vector2& displacement, float initialProgress ) +void DissolveEffectSetCentralLine(Actor& actor, const Vector2& position, const Vector2& displacement, float initialProgress) { // the line passes through 'position' and has the direction of 'displacement' float coefA, coefB, coefC; //line equation: Ax+By+C=0; @@ -100,12 +98,12 @@ void DissolveEffectSetCentralLine( Actor& actor, const Vector2& position, const actor.RegisterProperty("uPercentage", initialProgress, Dali::Property::ANIMATABLE); } -Property::Map CreateDissolveEffect( bool useHighPrecision ) +Property::Map CreateDissolveEffect(bool useHighPrecision) { const char* prefixHighPrecision("precision highp float;\n"); const char* prefixMediumPrecision("precision mediump float;\n"); - const char* vertexShader = SHADER_DISSOLVE_EFFECT_VERT.data(); + const char* vertexShader = SHADER_DISSOLVE_EFFECT_VERT.data(); const char* fragmentShader = SHADER_DISSOLVE_EFFECT_FRAG.data(); Property::Map map; diff --git a/dali-toolkit/devel-api/shader-effects/dissolve-effect.h b/dali-toolkit/devel-api/shader-effects/dissolve-effect.h index 47c171f..8572a12 100644 --- a/dali-toolkit/devel-api/shader-effects/dissolve-effect.h +++ b/dali-toolkit/devel-api/shader-effects/dissolve-effect.h @@ -19,10 +19,10 @@ */ // EXTERNAL INCLUDES -#include #include #include #include +#include // INTERNAL INCLUDES #include @@ -44,7 +44,7 @@ namespace Toolkit * @param[in] displacement The direction of the central line * @param[in] initialProgress The normalised initial progress of the shader */ -DALI_TOOLKIT_API void DissolveEffectSetCentralLine( Actor& actor, const Vector2& position, const Vector2& displacement, float initialProgress ); +DALI_TOOLKIT_API void DissolveEffectSetCentralLine(Actor& actor, const Vector2& position, const Vector2& displacement, float initialProgress); /** * @brief Create a new Dissolve effect @@ -58,7 +58,7 @@ DALI_TOOLKIT_API void DissolveEffectSetCentralLine( Actor& actor, const Vector2& * @return The newly created Property::Map with the dissolve effect */ -DALI_TOOLKIT_API Property::Map CreateDissolveEffect( bool useHighPrecision = true); +DALI_TOOLKIT_API Property::Map CreateDissolveEffect(bool useHighPrecision = true); } // namespace Toolkit diff --git a/dali-toolkit/devel-api/shader-effects/distance-field-effect.cpp b/dali-toolkit/devel-api/shader-effects/distance-field-effect.cpp index 597dc7c..a05fd4a 100644 --- a/dali-toolkit/devel-api/shader-effects/distance-field-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/distance-field-effect.cpp @@ -18,19 +18,17 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - Dali::Property::Map CreateDistanceFieldEffect() { const char* fragmentShaderPrefix("#extension GL_OES_standard_derivatives : enable\n"); diff --git a/dali-toolkit/devel-api/shader-effects/image-region-effect.cpp b/dali-toolkit/devel-api/shader-effects/image-region-effect.cpp index bab97f2..2d446d3 100644 --- a/dali-toolkit/devel-api/shader-effects/image-region-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/image-region-effect.cpp @@ -18,14 +18,13 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { namespace Toolkit { - Property::Map CreateImageRegionEffect() { Property::Map map; @@ -37,6 +36,6 @@ Property::Map CreateImageRegionEffect() return map; } -} // Toolkit +} // namespace Toolkit -} // Dali +} // namespace Dali diff --git a/dali-toolkit/devel-api/shader-effects/motion-blur-effect.cpp b/dali-toolkit/devel-api/shader-effects/motion-blur-effect.cpp index 430832e..a987243 100644 --- a/dali-toolkit/devel-api/shader-effects/motion-blur-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/motion-blur-effect.cpp @@ -22,15 +22,14 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { namespace Toolkit { - -void SetMotionBlurProperties( Actor& actor, unsigned int numBlurSamples ) +void SetMotionBlurProperties(Actor& actor, unsigned int numBlurSamples) { actor.RegisterProperty("uBlurTexCoordScale", 0.125f); actor.RegisterProperty("uGeometryStretchFactor", 0.05f); @@ -48,7 +47,6 @@ void SetMotionBlurProperties( Actor& actor, unsigned int numBlurSamples ) constraint.Apply(); } - Property::Map CreateMotionBlurEffect() { Property::Map map; @@ -66,5 +64,5 @@ Property::Map CreateMotionBlurEffect() return map; } -} // Toolkit -} // Dali +} // namespace Toolkit +} // namespace Dali diff --git a/dali-toolkit/devel-api/shader-effects/motion-blur-effect.h b/dali-toolkit/devel-api/shader-effects/motion-blur-effect.h index 8201976..aed1634 100644 --- a/dali-toolkit/devel-api/shader-effects/motion-blur-effect.h +++ b/dali-toolkit/devel-api/shader-effects/motion-blur-effect.h @@ -35,7 +35,7 @@ namespace Toolkit * @param[in] actor The actor that registers the uniform properties * @param[in] numBlurSamples Number of samples used by the shader */ -DALI_TOOLKIT_API void SetMotionBlurProperties( Actor& actor, unsigned int numBlurSamples = 8 ); +DALI_TOOLKIT_API void SetMotionBlurProperties(Actor& actor, unsigned int numBlurSamples = 8); /** * @brief Create a new MotionBlurEffect diff --git a/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.cpp b/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.cpp index bdd21f7..9d736a3 100644 --- a/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.cpp @@ -24,15 +24,14 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { namespace Toolkit { - -void SetMotionStretchProperties( Actor& actor ) +void SetMotionStretchProperties(Actor& actor) { actor.RegisterProperty("uGeometryStretchFactor", 0.5f); actor.RegisterProperty("uSpeedScalingFactor", 0.5f); @@ -63,6 +62,5 @@ Property::Map CreateMotionStretchEffect() return map; } - -} // Toolkit -} // Dali +} // namespace Toolkit +} // namespace Dali diff --git a/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.h b/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.h index 5f4976d..8ad7c67 100644 --- a/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.h +++ b/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.h @@ -32,7 +32,7 @@ namespace Toolkit /** * @brief Set the properties for the motion stretch */ -DALI_TOOLKIT_API void SetMotionStretchProperties( Actor& actor ); +DALI_TOOLKIT_API void SetMotionStretchProperties(Actor& actor); /** * @brief Creates a new MotionStretchEffect diff --git a/dali-toolkit/devel-api/text/text-utils-devel.cpp b/dali-toolkit/devel-api/text/text-utils-devel.cpp old mode 100755 new mode 100644 index e5ad925..0112e32 --- a/dali-toolkit/devel-api/text/text-utils-devel.cpp +++ b/dali-toolkit/devel-api/text/text-utils-devel.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -1013,12 +1013,11 @@ Size LayoutText(const RendererParameters& textParameters, TextAbstraction::TextR // Set the layout parameters. Size textLayoutArea = Size(static_cast(textParameters.textWidth), - static_cast(textParameters.textHeight)); + static_cast(textParameters.textHeight)); // padding - Extents padding = textParameters.padding; - internalDataModel.textLayoutArea = Size(textLayoutArea.x - ( padding.start + padding.end ), textLayoutArea.y - ( padding.top + padding.bottom ) ); - + Extents padding = textParameters.padding; + internalDataModel.textLayoutArea = Size(textLayoutArea.x - (padding.start + padding.end), textLayoutArea.y - (padding.top + padding.bottom)); if(isCircularTextLayout) { diff --git a/dali-toolkit/devel-api/text/text-utils-devel.h b/dali-toolkit/devel-api/text/text-utils-devel.h old mode 100755 new mode 100644 index e4bf375..87bffdd --- a/dali-toolkit/devel-api/text/text-utils-devel.h +++ b/dali-toolkit/devel-api/text/text-utils-devel.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_TEXT_UTILS_DEVEL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,7 +89,7 @@ struct DALI_TOOLKIT_API RendererParameters // float minLineSize; ///< The line's minimum size (in points). - Extents padding; ///< The padding of the boundaries where the text is going to be laid-out. + Extents padding; ///< The padding of the boundaries where the text is going to be laid-out. }; /** diff --git a/dali-toolkit/internal/accessibility-manager/accessibility-manager-impl.cpp b/dali-toolkit/internal/accessibility-manager/accessibility-manager-impl.cpp index 80a6865..e3f4209 100644 --- a/dali-toolkit/internal/accessibility-manager/accessibility-manager-impl.cpp +++ b/dali-toolkit/internal/accessibility-manager/accessibility-manager-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,26 +19,23 @@ #include "accessibility-manager-impl.h" // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES -#include -#include #include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - AccessibilityManager::AccessibilityManager() { - mFocusOrder.push_back( {} ); // zero has a special meaning + mFocusOrder.push_back({}); // zero has a special meaning } AccessibilityManager::~AccessibilityManager() @@ -47,71 +44,71 @@ AccessibilityManager::~AccessibilityManager() void AccessibilityManager::SetAccessibilityAttribute(Actor actor, Toolkit::AccessibilityManager::AccessibilityAttribute type, const std::string& text) { - switch ( type ) + switch(type) { - case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL: - actor.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_NAME, text ); - break; - - case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT: - actor.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION, text ); - break; - - case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT: - case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE: - default: - break; + case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL: + actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_NAME, text); + break; + + case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT: + actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION, text); + break; + + case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT: + case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE: + default: + break; } } std::string AccessibilityManager::GetAccessibilityAttribute(Actor actor, Toolkit::AccessibilityManager::AccessibilityAttribute type) const { - switch ( type ) + switch(type) { - case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL: - return actor.GetProperty< std::string >( Toolkit::DevelControl::Property::ACCESSIBILITY_NAME ); + case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL: + return actor.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_NAME); - case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT: - return actor.GetProperty< std::string >( Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION ); + case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT: + return actor.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION); - case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT: - case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE: - default: - return ""; + case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT: + case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE: + default: + return ""; } } void AccessibilityManager::SetFocusOrder(Actor actor, const unsigned int order) { - if (order == 0) + if(order == 0) return; - if (order >= mFocusOrder.size()) + if(order >= mFocusOrder.size()) mFocusOrder.resize(order + 1); auto it = mFocusOrder.begin() + order; mFocusOrder.insert(it, actor); - if (order > 0) + if(order > 0) { Actor prev = mFocusOrder[order - 1]; - DevelControl::AppendAccessibilityRelation( prev, actor, Accessibility::RelationType::FLOWS_TO ); - DevelControl::AppendAccessibilityRelation( actor, prev, Accessibility::RelationType::FLOWS_FROM ); + DevelControl::AppendAccessibilityRelation(prev, actor, Accessibility::RelationType::FLOWS_TO); + DevelControl::AppendAccessibilityRelation(actor, prev, Accessibility::RelationType::FLOWS_FROM); } - if (order + 1 < mFocusOrder.size()) + if(order + 1 < mFocusOrder.size()) { Actor next = mFocusOrder[order + 1]; - DevelControl::AppendAccessibilityRelation( actor, next, Accessibility::RelationType::FLOWS_TO ); - DevelControl::AppendAccessibilityRelation( next, actor, Accessibility::RelationType::FLOWS_FROM ); + DevelControl::AppendAccessibilityRelation(actor, next, Accessibility::RelationType::FLOWS_TO); + DevelControl::AppendAccessibilityRelation(next, actor, Accessibility::RelationType::FLOWS_FROM); } } unsigned int AccessibilityManager::GetFocusOrder(Actor actor) const { - for (auto it = mFocusOrder.begin(); it != mFocusOrder.end(); ++it) + for(auto it = mFocusOrder.begin(); it != mFocusOrder.end(); ++it) { - if (actor == *it) + if(actor == *it) return it - mFocusOrder.begin(); } @@ -127,7 +124,7 @@ Actor AccessibilityManager::GetActorByFocusOrder(const unsigned int order) { Actor actor; - if (order > 0 && order < mFocusOrder.size()) + if(order > 0 && order < mFocusOrder.size()) actor = mFocusOrder[order]; return actor; @@ -152,11 +149,11 @@ Actor AccessibilityManager::GetCurrentFocusGroup() unsigned int AccessibilityManager::GetCurrentFocusOrder() { - auto actor = GetCurrentFocusActor(); + auto actor = GetCurrentFocusActor(); unsigned order = 0; - if (actor) - order = GetFocusOrder( actor ); + if(actor) + order = GetFocusOrder(actor); return order; } @@ -165,7 +162,7 @@ bool AccessibilityManager::MoveFocusForward() { unsigned current = GetCurrentFocusOrder(); - if (current + 1 < mFocusOrder.size()) + if(current + 1 < mFocusOrder.size()) return SetCurrentFocusActor(mFocusOrder[current + 1]); return false; @@ -175,7 +172,7 @@ bool AccessibilityManager::MoveFocusBackward() { unsigned current = GetCurrentFocusOrder(); - if (current > 1) // zero has a special meaning + if(current > 1) // zero has a special meaning return SetCurrentFocusActor(mFocusOrder[current - 1]); return false; @@ -184,24 +181,24 @@ bool AccessibilityManager::MoveFocusBackward() void AccessibilityManager::ClearFocus() { auto actor = GetCurrentFocusActor(); - Toolkit::DevelControl::ClearAccessibilityHighlight( actor ); + Toolkit::DevelControl::ClearAccessibilityHighlight(actor); } void AccessibilityManager::Reset() { ClearFocus(); - for (std::size_t i = 2; i < mFocusOrder.size(); ++i) + for(std::size_t i = 2; i < mFocusOrder.size(); ++i) { Actor prev = mFocusOrder[i - 1]; Actor next = mFocusOrder[i]; - DevelControl::RemoveAccessibilityRelation( prev, next, Accessibility::RelationType::FLOWS_TO ); - DevelControl::RemoveAccessibilityRelation( next, prev, Accessibility::RelationType::FLOWS_FROM ); + DevelControl::RemoveAccessibilityRelation(prev, next, Accessibility::RelationType::FLOWS_TO); + DevelControl::RemoveAccessibilityRelation(next, prev, Accessibility::RelationType::FLOWS_FROM); } mFocusOrder.clear(); - mFocusOrder.push_back( {} ); + mFocusOrder.push_back({}); } void AccessibilityManager::SetFocusGroup(Actor actor, bool isFocusGroup) @@ -243,7 +240,7 @@ bool AccessibilityManager::GetWrapMode() const void AccessibilityManager::SetFocusIndicatorActor(Actor indicator) { - Dali::Accessibility::Accessible::SetHighlightActor( indicator ); + Dali::Accessibility::Accessible::SetHighlightActor(indicator); } Actor AccessibilityManager::GetFocusIndicatorActor() diff --git a/dali-toolkit/internal/accessibility-manager/accessibility-manager-impl.h b/dali-toolkit/internal/accessibility-manager/accessibility-manager-impl.h index b55d448..97da737 100644 --- a/dali-toolkit/internal/accessibility-manager/accessibility-manager-impl.h +++ b/dali-toolkit/internal/accessibility-manager/accessibility-manager-impl.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_INTERNAL_ACCESSIBILITY_MANAGER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,22 +19,19 @@ */ // EXTERNAL INCLUDES +#include #include #include -#include // INTERNAL INCLUDES #include namespace Dali { - namespace Toolkit { - namespace Internal { - class AccessibilityManager; /** @@ -43,7 +40,6 @@ class AccessibilityManager; class AccessibilityManager : public Dali::BaseObject, public Dali::ConnectionTracker { public: - typedef Dali::Toolkit::AccessibilityManager::AccessibilityActionSignalType AccessibilityActionSignalType; typedef Dali::Toolkit::AccessibilityManager::AccessibilityActionScrollSignalType AccessibilityActionScrollSignalType; @@ -173,7 +169,6 @@ public: Actor GetFocusIndicatorActor(); public: - /** * @copydoc Toolkit::AccessibilityManager::FocusChangedSignal() */ @@ -189,8 +184,7 @@ public: */ Toolkit::AccessibilityManager::FocusedActorActivatedSignalType& FocusedActorActivatedSignal(); -public: // Signals - +public: // Signals /** * @copydoc Dali::Toolkit::AccessibilityManager::StatusChangedSignal */ @@ -400,25 +394,22 @@ public: // Signals } protected: - /** * Destructor */ virtual ~AccessibilityManager(); private: - // Undefined AccessibilityManager(const AccessibilityManager&); AccessibilityManager& operator=(const AccessibilityManager& rhs); private: - std::vector mFocusOrder; - Toolkit::AccessibilityManager::FocusChangedSignalType mFocusChangedSignal; ///< The signal to notify the focus change - Toolkit::AccessibilityManager::FocusOvershotSignalType mFocusOvershotSignal; ///< The signal to notify the focus overshooted + Toolkit::AccessibilityManager::FocusChangedSignalType mFocusChangedSignal; ///< The signal to notify the focus change + Toolkit::AccessibilityManager::FocusOvershotSignalType mFocusOvershotSignal; ///< The signal to notify the focus overshooted Toolkit::AccessibilityManager::FocusedActorActivatedSignalType mFocusedActorActivatedSignal; ///< The signal to notify the activation of focused actor // Action signals. diff --git a/dali-toolkit/internal/builder/builder-animations.cpp b/dali-toolkit/internal/builder/builder-animations.cpp index c917d06..cd20832 100644 --- a/dali-toolkit/internal/builder/builder-animations.cpp +++ b/dali-toolkit/internal/builder/builder-animations.cpp @@ -16,380 +16,373 @@ */ // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES -#include #include +#include #include namespace // unnamed namespace { - using namespace Dali; -TimePeriod GetTimePeriod( const TreeNode& child, const Toolkit::Internal::Replacement& constant ) +TimePeriod GetTimePeriod(const TreeNode& child, const Toolkit::Internal::Replacement& constant) { - OptionalFloat delay = constant.IsFloat( IsChild(child, "delay" ) ); - OptionalFloat duration = constant.IsFloat( IsChild(child, "duration" ) ); - DALI_ASSERT_ALWAYS( duration && "Time period must have at least a duration" ); + OptionalFloat delay = constant.IsFloat(IsChild(child, "delay")); + OptionalFloat duration = constant.IsFloat(IsChild(child, "duration")); + DALI_ASSERT_ALWAYS(duration && "Time period must have at least a duration"); - if( delay ) + if(delay) { - return TimePeriod( *delay, *duration ); + return TimePeriod(*delay, *duration); } else { - return TimePeriod( *duration ); + return TimePeriod(*duration); } } -Property::Value GetPropertyValue( const Property::Type& propType, const TreeNode& child ) +Property::Value GetPropertyValue(const Property::Type& propType, const TreeNode& child) { - switch ( propType ) + switch(propType) { case Property::BOOLEAN: { - return Property::Value( GetBoolean( child ) ); + return Property::Value(GetBoolean(child)); } case Property::FLOAT: { - return Property::Value( GetFloat( child ) ); + return Property::Value(GetFloat(child)); } case Property::VECTOR2: { - return Property::Value( GetVector2( child ) ); + return Property::Value(GetVector2(child)); } case Property::VECTOR3: { - return Property::Value( GetVector3( child ) ); + return Property::Value(GetVector3(child)); } case Property::VECTOR4: { - return Property::Value( GetVector4( child ) ); + return Property::Value(GetVector4(child)); } case Property::ROTATION: { - if( 4 == child.Size() ) + if(4 == child.Size()) { Vector4 v(GetVector4(child)); // angle, axis as per spec - return Property::Value( Quaternion(Radian(Degree(v[3])), - Vector3(v[0],v[1],v[2])) ); + return Property::Value(Quaternion(Radian(Degree(v[3])), + Vector3(v[0], v[1], v[2]))); } else { // degrees as per spec - Vector3 rotation = GetVector3( child ); - return Property::Value( Quaternion(Radian(Degree(rotation.x)), - Radian(Degree(rotation.y)), - Radian(Degree(rotation.z))) ); + Vector3 rotation = GetVector3(child); + return Property::Value(Quaternion(Radian(Degree(rotation.x)), + Radian(Degree(rotation.y)), + Radian(Degree(rotation.z)))); } } case Property::NONE: // fall default: { - DALI_ASSERT_ALWAYS( !"Property type incorrect" ); + DALI_ASSERT_ALWAYS(!"Property type incorrect"); } } } -AlphaFunction GetAlphaFunction( const std::string& alphaFunction ) +AlphaFunction GetAlphaFunction(const std::string& alphaFunction) { - typedef std::map< const std::string, Dali::AlphaFunction > AlphaFunctionLut; - static AlphaFunctionLut alphaFunctionLut; + typedef std::map AlphaFunctionLut; + static AlphaFunctionLut alphaFunctionLut; - if( 0 == alphaFunctionLut.size() ) + if(0 == alphaFunctionLut.size()) { // coding convention is uppercase enums - alphaFunctionLut["DEFAULT"] = AlphaFunction(AlphaFunction::DEFAULT); - alphaFunctionLut["LINEAR"] = AlphaFunction(AlphaFunction::LINEAR); - alphaFunctionLut["REVERSE"] = AlphaFunction(AlphaFunction::REVERSE); - alphaFunctionLut["EASE_IN_SQUARE"] = AlphaFunction(AlphaFunction::EASE_IN_SQUARE); - alphaFunctionLut["EASE_OUT_SQUARE"] = AlphaFunction(AlphaFunction::EASE_OUT_SQUARE); - alphaFunctionLut["EASE_IN"] = AlphaFunction(AlphaFunction::EASE_IN); - alphaFunctionLut["EASE_OUT"] = AlphaFunction(AlphaFunction::EASE_OUT); - alphaFunctionLut["EASE_IN_OUT"] = AlphaFunction(AlphaFunction::EASE_IN_OUT); - alphaFunctionLut["EASE_IN_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_SINE); - alphaFunctionLut["EASE_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_OUT_SINE); - alphaFunctionLut["EASE_IN_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_OUT_SINE); - alphaFunctionLut["BOUNCE"] = AlphaFunction(AlphaFunction::BOUNCE); - alphaFunctionLut["SIN"] = AlphaFunction(AlphaFunction::SIN); - alphaFunctionLut["EASE_OUT_BACK"] = AlphaFunction(AlphaFunction::EASE_OUT_BACK); + alphaFunctionLut["DEFAULT"] = AlphaFunction(AlphaFunction::DEFAULT); + alphaFunctionLut["LINEAR"] = AlphaFunction(AlphaFunction::LINEAR); + alphaFunctionLut["REVERSE"] = AlphaFunction(AlphaFunction::REVERSE); + alphaFunctionLut["EASE_IN_SQUARE"] = AlphaFunction(AlphaFunction::EASE_IN_SQUARE); + alphaFunctionLut["EASE_OUT_SQUARE"] = AlphaFunction(AlphaFunction::EASE_OUT_SQUARE); + alphaFunctionLut["EASE_IN"] = AlphaFunction(AlphaFunction::EASE_IN); + alphaFunctionLut["EASE_OUT"] = AlphaFunction(AlphaFunction::EASE_OUT); + alphaFunctionLut["EASE_IN_OUT"] = AlphaFunction(AlphaFunction::EASE_IN_OUT); + alphaFunctionLut["EASE_IN_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_SINE); + alphaFunctionLut["EASE_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_OUT_SINE); + alphaFunctionLut["EASE_IN_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_OUT_SINE); + alphaFunctionLut["BOUNCE"] = AlphaFunction(AlphaFunction::BOUNCE); + alphaFunctionLut["SIN"] = AlphaFunction(AlphaFunction::SIN); + alphaFunctionLut["EASE_OUT_BACK"] = AlphaFunction(AlphaFunction::EASE_OUT_BACK); } - const AlphaFunctionLut::const_iterator iter( alphaFunctionLut.find( alphaFunction ) ); + const AlphaFunctionLut::const_iterator iter(alphaFunctionLut.find(alphaFunction)); - if( iter != alphaFunctionLut.end() ) + if(iter != alphaFunctionLut.end()) { return iter->second; } else { - DALI_ASSERT_ALWAYS( iter != alphaFunctionLut.end() && "Unknown Alpha Constant" ); + DALI_ASSERT_ALWAYS(iter != alphaFunctionLut.end() && "Unknown Alpha Constant"); return Dali::AlphaFunction::DEFAULT; } } } // unnamed namespace - namespace Dali { - namespace Toolkit { - namespace Internal { - -Animation CreateAnimation( const TreeNode& child, const Replacement& constant, Dali::Actor searchRoot, Builder* const builder ) +Animation CreateAnimation(const TreeNode& child, const Replacement& constant, Dali::Actor searchRoot, Builder* const builder) { float durationSum = 0.f; Dali::Actor searchActor = searchRoot ? searchRoot : Dali::Stage::GetCurrent().GetRootLayer(); - Animation animation( Animation::New( 0.f ) ); + Animation animation(Animation::New(0.f)); // duration needs to be set before AnimateTo calls for correct operation when AnimateTo has no "timePeriod". - OptionalFloat duration = constant.IsFloat( IsChild(child, "duration" ) ); + OptionalFloat duration = constant.IsFloat(IsChild(child, "duration")); - if( duration ) + if(duration) { - animation.SetDuration( *duration ); + animation.SetDuration(*duration); } - if( OptionalBoolean looping = constant.IsBoolean( IsChild(child, "loop" ) ) ) + if(OptionalBoolean looping = constant.IsBoolean(IsChild(child, "loop"))) { - animation.SetLooping( *looping ); + animation.SetLooping(*looping); } - if( OptionalString endAction = constant.IsString( IsChild(child, "endAction" ) ) ) + if(OptionalString endAction = constant.IsString(IsChild(child, "endAction"))) { if("BAKE" == *endAction) { - animation.SetEndAction( Animation::BAKE ); + animation.SetEndAction(Animation::BAKE); } else if("DISCARD" == *endAction) { - animation.SetEndAction( Animation::DISCARD ); + animation.SetEndAction(Animation::DISCARD); } else if("BAKE_FINAL" == *endAction) { - animation.SetEndAction( Animation::BAKE_FINAL ); + animation.SetEndAction(Animation::BAKE_FINAL); } } - if( OptionalString endAction = constant.IsString( IsChild(child, "disconnectAction" ) ) ) + if(OptionalString endAction = constant.IsString(IsChild(child, "disconnectAction"))) { if("BAKE" == *endAction) { - animation.SetDisconnectAction( Animation::BAKE ); + animation.SetDisconnectAction(Animation::BAKE); } else if("DISCARD" == *endAction) { - animation.SetDisconnectAction( Animation::DISCARD ); + animation.SetDisconnectAction(Animation::DISCARD); } else if("BAKE_FINAL" == *endAction) { - animation.SetDisconnectAction( Animation::BAKE_FINAL ); + animation.SetDisconnectAction(Animation::BAKE_FINAL); } } - OptionalChild propertiesNode = IsChild(child, "properties" ); + OptionalChild propertiesNode = IsChild(child, "properties"); if(propertiesNode) { const TreeNode::ConstIterator endIter = (*propertiesNode).CEnd(); - for( TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter ) + for(TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& pKeyChild = *iter; - OptionalString actorName( constant.IsString( IsChild(pKeyChild.second, "actor" ) ) ); - OptionalString property( constant.IsString( IsChild(pKeyChild.second, "property" ) ) ); - DALI_ASSERT_ALWAYS( actorName && "Animation must specify actor name" ); + OptionalString actorName(constant.IsString(IsChild(pKeyChild.second, "actor"))); + OptionalString property(constant.IsString(IsChild(pKeyChild.second, "property"))); + DALI_ASSERT_ALWAYS(actorName && "Animation must specify actor name"); - Handle targetHandle = searchActor.FindChildByName( *actorName ); - DALI_ASSERT_ALWAYS( targetHandle && "Actor must exist for property" ); + Handle targetHandle = searchActor.FindChildByName(*actorName); + DALI_ASSERT_ALWAYS(targetHandle && "Actor must exist for property"); Property::Value propValue; Property::Index propIndex = Property::INVALID_INDEX; - if( property ) + if(property) { - propIndex = targetHandle.GetPropertyIndex( *property ); + propIndex = targetHandle.GetPropertyIndex(*property); // if the property is not found from the (actor) handle, try to downcast it to renderable actor // to allow animating shader uniforms - if( propIndex == Property::INVALID_INDEX ) + if(propIndex == Property::INVALID_INDEX) { - DALI_SCRIPT_WARNING( "Cannot find property on object\n" ); - continue; + DALI_SCRIPT_WARNING("Cannot find property on object\n"); + continue; } } // these are the defaults - AlphaFunction alphaFunction( AlphaFunction::DEFAULT ); - TimePeriod timePeriod( 0.f ); + AlphaFunction alphaFunction(AlphaFunction::DEFAULT); + TimePeriod timePeriod(0.f); - OptionalChild timeChild = IsChild( pKeyChild.second, "timePeriod" ); + OptionalChild timeChild = IsChild(pKeyChild.second, "timePeriod"); - if( timeChild ) + if(timeChild) { - timePeriod = GetTimePeriod( *timeChild, constant ); + timePeriod = GetTimePeriod(*timeChild, constant); } - durationSum = std::max( durationSum, timePeriod.delaySeconds + timePeriod.durationSeconds ); + durationSum = std::max(durationSum, timePeriod.delaySeconds + timePeriod.durationSeconds); - if( OptionalString alphaChild = constant.IsString( IsChild(pKeyChild.second, "alphaFunction" ) ) ) + if(OptionalString alphaChild = constant.IsString(IsChild(pKeyChild.second, "alphaFunction"))) { - alphaFunction = GetAlphaFunction( *alphaChild ); + alphaFunction = GetAlphaFunction(*alphaChild); } - if( OptionalChild keyFrameChild = IsChild(pKeyChild.second, "keyFrames") ) + if(OptionalChild keyFrameChild = IsChild(pKeyChild.second, "keyFrames")) { - DALI_ASSERT_ALWAYS( property && "Animation must specify a property name" ); - Property prop = Property( targetHandle, propIndex ); + DALI_ASSERT_ALWAYS(property && "Animation must specify a property name"); + Property prop = Property(targetHandle, propIndex); KeyFrames keyframes = KeyFrames::New(); const TreeNode::ConstIterator endIter = (*keyFrameChild).CEnd(); - for( TreeNode::ConstIterator iter = (*keyFrameChild).CBegin(); endIter != iter; ++iter ) + for(TreeNode::ConstIterator iter = (*keyFrameChild).CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& kfKeyChild = *iter; - OptionalFloat kfProgress = constant.IsFloat( IsChild(kfKeyChild.second, "progress" ) ); - DALI_ASSERT_ALWAYS( kfProgress && "Key frame entry must have 'progress'" ); + OptionalFloat kfProgress = constant.IsFloat(IsChild(kfKeyChild.second, "progress")); + DALI_ASSERT_ALWAYS(kfProgress && "Key frame entry must have 'progress'"); - OptionalChild kfValue = IsChild( kfKeyChild.second, "value" ); - DALI_ASSERT_ALWAYS( kfValue && "Key frame entry must have 'value'" ); + OptionalChild kfValue = IsChild(kfKeyChild.second, "value"); + DALI_ASSERT_ALWAYS(kfValue && "Key frame entry must have 'value'"); try { - propValue = GetPropertyValue( prop.object.GetPropertyType(prop.propertyIndex), *kfValue ); + propValue = GetPropertyValue(prop.object.GetPropertyType(prop.propertyIndex), *kfValue); } catch(...) { - DALI_LOG_WARNING( "Property:'%s' type does not match value type '%s'\n", - (*property).c_str(), - PropertyTypes::GetName(prop.object.GetPropertyType(prop.propertyIndex)) ); + DALI_LOG_WARNING("Property:'%s' type does not match value type '%s'\n", + (*property).c_str(), + PropertyTypes::GetName(prop.object.GetPropertyType(prop.propertyIndex))); throw; } - AlphaFunction kfAlphaFunction( AlphaFunction::DEFAULT ); - if( OptionalString alphaFuncStr = constant.IsString( IsChild(pKeyChild.second, "alphaFunction") ) ) + AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT); + if(OptionalString alphaFuncStr = constant.IsString(IsChild(pKeyChild.second, "alphaFunction"))) { - kfAlphaFunction = GetAlphaFunction( *alphaFuncStr ); + kfAlphaFunction = GetAlphaFunction(*alphaFuncStr); } - keyframes.Add( *kfProgress, propValue, kfAlphaFunction ); + keyframes.Add(*kfProgress, propValue, kfAlphaFunction); } - if( timeChild ) + if(timeChild) { - animation.AnimateBetween( prop, keyframes, alphaFunction, timePeriod ); + animation.AnimateBetween(prop, keyframes, alphaFunction, timePeriod); } else { - animation.AnimateBetween( prop, keyframes, alphaFunction ); + animation.AnimateBetween(prop, keyframes, alphaFunction); } } - else if( OptionalString pathChild = IsString(pKeyChild.second, "path") ) + else if(OptionalString pathChild = IsString(pKeyChild.second, "path")) { //Get path Path path = builder->GetPath(*pathChild); - if( path ) + if(path) { //Get forward vector if specified - Vector3 forward( 0.0f, 0.0f, 0.0f ); - OptionalVector3 forwardProperty = constant.IsVector3( IsChild(pKeyChild.second, "forward" ) ); - if( forwardProperty ) + Vector3 forward(0.0f, 0.0f, 0.0f); + OptionalVector3 forwardProperty = constant.IsVector3(IsChild(pKeyChild.second, "forward")); + if(forwardProperty) { forward = *forwardProperty; } - Actor actor = Actor::DownCast( targetHandle ); - if( actor ) + Actor actor = Actor::DownCast(targetHandle); + if(actor) { - if( timeChild ) + if(timeChild) { - animation.Animate( actor, path, forward, alphaFunction, timePeriod ); + animation.Animate(actor, path, forward, alphaFunction, timePeriod); } else { - animation.Animate( actor, path, forward, alphaFunction ); + animation.Animate(actor, path, forward, alphaFunction); } - } } else { //Path not found - DALI_SCRIPT_WARNING( "Cannot find animation path '%s'\n", (*pathChild).c_str() ); + DALI_SCRIPT_WARNING("Cannot find animation path '%s'\n", (*pathChild).c_str()); } } else { - DALI_ASSERT_ALWAYS( property && "Animation must specify a property name" ); + DALI_ASSERT_ALWAYS(property && "Animation must specify a property name"); - Property prop = Property( targetHandle, propIndex ); + Property prop = Property(targetHandle, propIndex); try { - propValue = GetPropertyValue( prop.object.GetPropertyType(prop.propertyIndex), *IsChild(pKeyChild.second, "value") ); + propValue = GetPropertyValue(prop.object.GetPropertyType(prop.propertyIndex), *IsChild(pKeyChild.second, "value")); } catch(...) { - DALI_LOG_WARNING( "Property:'%s' type does not match value type '%s'\n", (*property).c_str(), - PropertyTypes::GetName( prop.object.GetPropertyType(prop.propertyIndex) ) ); + DALI_LOG_WARNING("Property:'%s' type does not match value type '%s'\n", (*property).c_str(), PropertyTypes::GetName(prop.object.GetPropertyType(prop.propertyIndex))); throw; } - if( OptionalBoolean relative = constant.IsBoolean( IsChild(pKeyChild.second, "relative") ) ) + if(OptionalBoolean relative = constant.IsBoolean(IsChild(pKeyChild.second, "relative"))) { - if( timeChild ) + if(timeChild) { - animation.AnimateBy( prop, propValue, alphaFunction, timePeriod ); + animation.AnimateBy(prop, propValue, alphaFunction, timePeriod); } else { - animation.AnimateBy( prop, propValue, alphaFunction ); + animation.AnimateBy(prop, propValue, alphaFunction); } } else { - if( timeChild ) + if(timeChild) { - animation.AnimateTo( prop, propValue, alphaFunction, timePeriod ); + animation.AnimateTo(prop, propValue, alphaFunction, timePeriod); } else { - animation.AnimateTo( prop, propValue, alphaFunction ); + animation.AnimateTo(prop, propValue, alphaFunction); } } } } } - if( !duration ) + if(!duration) { - animation.SetDuration( durationSum ); + animation.SetDuration(durationSum); } return animation; } -Animation CreateAnimation( const TreeNode& child, Builder* const builder ) +Animation CreateAnimation(const TreeNode& child, Builder* const builder) { Replacement replacement; - return CreateAnimation( child, replacement, Stage::GetCurrent().GetRootLayer(), builder ); + return CreateAnimation(child, replacement, Stage::GetCurrent().GetRootLayer(), builder); } } // namespace Internal @@ -397,4 +390,3 @@ Animation CreateAnimation( const TreeNode& child, Builder* const builder ) } // namespace Toolkit } // namespace Dali - diff --git a/dali-toolkit/internal/builder/builder-declarations.h b/dali-toolkit/internal/builder/builder-declarations.h index 09a5fd1..963869b 100644 --- a/dali-toolkit/internal/builder/builder-declarations.h +++ b/dali-toolkit/internal/builder/builder-declarations.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_BUILDER_DECLARATIONS_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,12 +20,12 @@ // EXTERNAL INCLUDES #include +#include +#include #include #include #include #include -#include -#include // INTERNAL INCLUDES #include @@ -34,19 +34,19 @@ typedef Dali::Toolkit::TreeNode TreeNode; typedef TreeNode::ConstIterator TreeConstIter; -typedef OptionalValue OptionalChild; -typedef OptionalValue OptionalString; -typedef OptionalValue OptionalFloat; -typedef OptionalValue OptionalInteger; -typedef OptionalValue OptionalUnsignedInt; -typedef OptionalValue OptionalBoolean; -typedef OptionalValue OptionalVector2; -typedef OptionalValue OptionalVector3; -typedef OptionalValue OptionalVector4; -typedef OptionalValue OptionalString; -typedef OptionalValue OptionalMatrix; -typedef OptionalValue OptionalMatrix3; +typedef OptionalValue OptionalChild; +typedef OptionalValue OptionalString; +typedef OptionalValue OptionalFloat; +typedef OptionalValue OptionalInteger; +typedef OptionalValue OptionalUnsignedInt; +typedef OptionalValue OptionalBoolean; +typedef OptionalValue OptionalVector2; +typedef OptionalValue OptionalVector3; +typedef OptionalValue OptionalVector4; +typedef OptionalValue OptionalString; +typedef OptionalValue OptionalMatrix; +typedef OptionalValue OptionalMatrix3; typedef OptionalValue > OptionalRect; -typedef OptionalValue OptionalExtents; +typedef OptionalValue OptionalExtents; #endif // DALI_TOOLKIT_BUILDER_DECLARATIONS_H diff --git a/dali-toolkit/internal/builder/builder-filesystem.h b/dali-toolkit/internal/builder/builder-filesystem.h old mode 100755 new mode 100644 index 2222d1b..5e032a0 --- a/dali-toolkit/internal/builder/builder-filesystem.h +++ b/dali-toolkit/internal/builder/builder-filesystem.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_INTERNAL_BUILDER_FILESYSTEM_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,24 +19,24 @@ */ // EXTERNAL INCLUDES -#include #include #include +#include #include #include -inline std::string GetFileContents(const std::string &fn) +inline std::string GetFileContents(const std::string& fn) { - std::streampos bufferSize = 0; + std::streampos bufferSize = 0; Dali::Vector fileBuffer; - if( !Dali::FileLoader::ReadFile( fn, bufferSize, fileBuffer, Dali::FileLoader::FileType::BINARY ) ) + if(!Dali::FileLoader::ReadFile(fn, bufferSize, fileBuffer, Dali::FileLoader::FileType::BINARY)) { - return std::string(); + return std::string(); } - return std::string( &fileBuffer[0], bufferSize ); + return std::string(&fileBuffer[0], bufferSize); } #endif // DALI_TOOLKIT_INTERNAL_BUILDER_FILESYSTEM_H diff --git a/dali-toolkit/internal/builder/builder-get-is.inl.h b/dali-toolkit/internal/builder/builder-get-is.inl.h index 01dab59..0a7f6d5 100644 --- a/dali-toolkit/internal/builder/builder-get-is.inl.h +++ b/dali-toolkit/internal/builder/builder-get-is.inl.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_INTERNAL_BUILDER_GET_IS_INL /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,12 +23,12 @@ inline OptionalChild IsChild(const TreeNode* node, const std::string& childName) { - if( node ) + if(node) { const TreeNode* c = node->GetChild(childName); - if( NULL != c ) + if(NULL != c) { - return OptionalChild( *c ); + return OptionalChild(*c); } else { @@ -43,12 +43,12 @@ inline OptionalChild IsChild(const TreeNode* node, const std::string& childName) inline OptionalChild IsChildIgnoreCase(const TreeNode* node, const std::string& childName) { - if( node ) + if(node) { const TreeNode* c = node->GetChildIgnoreCase(childName); - if( NULL != c ) + if(NULL != c) { - return OptionalChild( *c ); + return OptionalChild(*c); } else { @@ -73,7 +73,7 @@ inline OptionalChild IsChildIgnoreCase(const TreeNode& node, const std::string& inline OptionalString IsString(const OptionalChild& node) { - if( node && (*node).GetType() == TreeNode::STRING ) + if(node && (*node).GetType() == TreeNode::STRING) { return OptionalString((*node).GetString()); } @@ -87,36 +87,36 @@ inline OptionalFloat IsFloat(const OptionalChild& node) { OptionalFloat ret; - if( node ) + if(node) { - if( (*node).GetType() == TreeNode::FLOAT ) + if((*node).GetType() == TreeNode::FLOAT) { ret = (*node).GetFloat(); } - else if( (*node).GetType() == TreeNode::INTEGER ) + else if((*node).GetType() == TreeNode::INTEGER) { // JSON has number not float/int but JsonParser discriminates. // Here we don't care so we allow coercion - ret = static_cast( (*node).GetInteger() ); + ret = static_cast((*node).GetInteger()); } } return ret; } -inline OptionalInteger IsInteger(const OptionalChild &node) +inline OptionalInteger IsInteger(const OptionalChild& node) { OptionalInteger ret; - if( node ) + if(node) { - if( (*node).GetType() == TreeNode::INTEGER ) + if((*node).GetType() == TreeNode::INTEGER) { ret = (*node).GetInteger(); } - else if( (*node).GetType() == TreeNode::FLOAT ) + else if((*node).GetType() == TreeNode::FLOAT) { - ret = static_cast( (*node).GetFloat() ); + ret = static_cast((*node).GetFloat()); } } @@ -125,7 +125,7 @@ inline OptionalInteger IsInteger(const OptionalChild &node) inline OptionalBoolean IsBoolean(const OptionalChild& node) { - if( node && (*node).GetType() == TreeNode::BOOLEAN ) + if(node && (*node).GetType() == TreeNode::BOOLEAN) { return OptionalBoolean(1 == (*node).GetInteger()); } @@ -135,18 +135,17 @@ inline OptionalBoolean IsBoolean(const OptionalChild& node) } } - // copy N Numbers -template +template inline bool CopyNumbers(TreeNode::ConstIterator iter, int N, T& vector) { for(int i = 0; i < N; ++i) { - if( (*iter).second.GetType() == TreeNode::FLOAT) + if((*iter).second.GetType() == TreeNode::FLOAT) { vector[i] = (*iter).second.GetFloat(); } - else if( (*iter).second.GetType() == TreeNode::INTEGER ) + else if((*iter).second.GetType() == TreeNode::INTEGER) { vector[i] = static_cast((*iter).second.GetInteger()); } @@ -164,10 +163,10 @@ inline OptionalVector4 IsVector4(const OptionalChild& node) { OptionalVector4 ret; - if( node && (TreeNode::ARRAY == (*node).GetType()) && (*node).Size() >= 4 ) + if(node && (TreeNode::ARRAY == (*node).GetType()) && (*node).Size() >= 4) { Dali::Vector4 v; - if( CopyNumbers((*node).CBegin(), 4, v) ) + if(CopyNumbers((*node).CBegin(), 4, v)) { ret = OptionalVector4(v); } @@ -180,10 +179,10 @@ inline OptionalVector3 IsVector3(const OptionalChild& node) { OptionalVector3 ret; - if( node && (TreeNode::ARRAY == (*node).GetType()) && (*node).Size() >= 3 ) + if(node && (TreeNode::ARRAY == (*node).GetType()) && (*node).Size() >= 3) { Dali::Vector3 v; - if( CopyNumbers((*node).CBegin(), 3, v) ) + if(CopyNumbers((*node).CBegin(), 3, v)) { ret = OptionalVector3(v); } @@ -196,10 +195,10 @@ inline OptionalVector2 IsVector2(const OptionalChild& node) { OptionalVector2 ret; - if( node && (TreeNode::ARRAY == (*node).GetType()) && (*node).Size() >= 2 ) + if(node && (TreeNode::ARRAY == (*node).GetType()) && (*node).Size() >= 2) { Dali::Vector2 v; - if( CopyNumbers((*node).CBegin(), 2, v) ) + if(CopyNumbers((*node).CBegin(), 2, v)) { ret = OptionalVector2(v); } @@ -208,14 +207,14 @@ inline OptionalVector2 IsVector2(const OptionalChild& node) return ret; } -inline OptionalMatrix IsMatrix(const OptionalChild &node) +inline OptionalMatrix IsMatrix(const OptionalChild& node) { OptionalMatrix ret; - if( node && (TreeNode::ARRAY == (*node).GetType()) && (*node).Size() >= 16 ) + if(node && (TreeNode::ARRAY == (*node).GetType()) && (*node).Size() >= 16) { float v[16]; - if( CopyNumbers((*node).CBegin(), 16, v) ) + if(CopyNumbers((*node).CBegin(), 16, v)) { ret = OptionalMatrix(Dali::Matrix(v)); } @@ -228,14 +227,12 @@ inline OptionalMatrix3 IsMatrix3(const OptionalChild& node) { OptionalMatrix3 ret; - if( node && (TreeNode::ARRAY == (*node).GetType()) && (*node).Size() >= 9 ) + if(node && (TreeNode::ARRAY == (*node).GetType()) && (*node).Size() >= 9) { float v[9]; - if( CopyNumbers((*node).CBegin(), 9, v) ) + if(CopyNumbers((*node).CBegin(), 9, v)) { - ret = OptionalMatrix3(Dali::Matrix3(v[0], v[1], v[2], - v[3], v[4], v[5], - v[6], v[7], v[8] )); + ret = OptionalMatrix3(Dali::Matrix3(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8])); } } @@ -250,8 +247,8 @@ inline OptionalRect IsRect(const OptionalChild& node) if((*node).Size() >= 4) { TreeNode::ConstIterator iter((*node).CBegin()); - int v[4]; - if( CopyNumbers((*node).CBegin(), 4, v) ) + int v[4]; + if(CopyNumbers((*node).CBegin(), 4, v)) { ret = OptionalRect(Dali::Rect(v[0], v[1], v[2], v[3])); } @@ -268,8 +265,8 @@ inline OptionalExtents IsExtents(const OptionalChild& node) if((*node).Size() >= 4) { TreeNode::ConstIterator iter((*node).CBegin()); - int v[4]; - if( CopyNumbers((*node).CBegin(), 4, v) ) + int v[4]; + if(CopyNumbers((*node).CBegin(), 4, v)) { extents = OptionalExtents(Dali::Extents(v[0], v[1], v[2], v[3])); } @@ -281,164 +278,162 @@ inline OptionalExtents IsExtents(const OptionalChild& node) // // // -inline OptionalString IsString( const TreeNode& parent, const std::string& childName) +inline OptionalString IsString(const TreeNode& parent, const std::string& childName) { - return IsString( IsChild(&parent, childName) ); + return IsString(IsChild(&parent, childName)); } -inline OptionalFloat IsFloat( const TreeNode& parent, const std::string& childName) +inline OptionalFloat IsFloat(const TreeNode& parent, const std::string& childName) { - return IsFloat( IsChild(&parent, childName) ); + return IsFloat(IsChild(&parent, childName)); } -inline OptionalInteger IsInteger( const TreeNode& parent, const std::string& childName) +inline OptionalInteger IsInteger(const TreeNode& parent, const std::string& childName) { - return IsInteger( IsChild(&parent, childName) ); + return IsInteger(IsChild(&parent, childName)); } -inline OptionalBoolean IsBoolean( const TreeNode& parent, const std::string& childName) +inline OptionalBoolean IsBoolean(const TreeNode& parent, const std::string& childName) { - return IsBoolean( IsChild(parent, childName) ); + return IsBoolean(IsChild(parent, childName)); } -inline OptionalVector4 IsVector4(const TreeNode &parent, const std::string& childName) +inline OptionalVector4 IsVector4(const TreeNode& parent, const std::string& childName) { - return IsVector4( IsChild(parent, childName) ); + return IsVector4(IsChild(parent, childName)); } -inline OptionalVector3 IsVector3(const TreeNode &parent, const std::string& childName) +inline OptionalVector3 IsVector3(const TreeNode& parent, const std::string& childName) { - return IsVector3( IsChild(parent, childName) ); + return IsVector3(IsChild(parent, childName)); } -inline OptionalVector2 IsVector2(const TreeNode &parent, const std::string& childName) +inline OptionalVector2 IsVector2(const TreeNode& parent, const std::string& childName) { - return IsVector2( IsChild(parent, childName) ); + return IsVector2(IsChild(parent, childName)); } -inline OptionalMatrix IsMatrix(const TreeNode &parent, const std::string& childName) +inline OptionalMatrix IsMatrix(const TreeNode& parent, const std::string& childName) { - return IsMatrix( IsChild(parent, childName) ); + return IsMatrix(IsChild(parent, childName)); } -inline OptionalMatrix3 IsMatrix3(const TreeNode &parent, const std::string& childName) +inline OptionalMatrix3 IsMatrix3(const TreeNode& parent, const std::string& childName) { - return IsMatrix3( IsChild(&parent, childName) ); + return IsMatrix3(IsChild(&parent, childName)); } -inline OptionalRect IsRect(const TreeNode &parent, const std::string& childName) +inline OptionalRect IsRect(const TreeNode& parent, const std::string& childName) { - return IsRect( IsChild(&parent, childName) ); + return IsRect(IsChild(&parent, childName)); } -inline OptionalExtents IsExtents(const TreeNode &parent, const std::string& childName) +inline OptionalExtents IsExtents(const TreeNode& parent, const std::string& childName) { - return IsExtents( IsChild(&parent, childName) ); + return IsExtents(IsChild(&parent, childName)); } // // // -inline OptionalString IsString( const TreeNode& node ) +inline OptionalString IsString(const TreeNode& node) { - return IsString( OptionalChild( node ) ); + return IsString(OptionalChild(node)); } -inline OptionalFloat IsFloat( const TreeNode& node ) +inline OptionalFloat IsFloat(const TreeNode& node) { - return IsFloat( OptionalChild( node ) ); + return IsFloat(OptionalChild(node)); } -inline OptionalInteger IsInteger( const TreeNode& node ) +inline OptionalInteger IsInteger(const TreeNode& node) { - return IsInteger( OptionalChild( node ) ); + return IsInteger(OptionalChild(node)); } -inline OptionalBoolean IsBoolean( const TreeNode& node ) +inline OptionalBoolean IsBoolean(const TreeNode& node) { - return IsBoolean( OptionalChild( node ) ); + return IsBoolean(OptionalChild(node)); } -inline OptionalVector4 IsVector4(const TreeNode &node ) +inline OptionalVector4 IsVector4(const TreeNode& node) { - return IsVector4( OptionalChild( node ) ); + return IsVector4(OptionalChild(node)); } -inline OptionalVector3 IsVector3(const TreeNode &node ) +inline OptionalVector3 IsVector3(const TreeNode& node) { - return IsVector3( OptionalChild( node ) ); + return IsVector3(OptionalChild(node)); } -inline OptionalVector2 IsVector2(const TreeNode &node ) +inline OptionalVector2 IsVector2(const TreeNode& node) { - return IsVector2( OptionalChild( node ) ); + return IsVector2(OptionalChild(node)); } -inline OptionalMatrix IsMatrix(const TreeNode &node ) +inline OptionalMatrix IsMatrix(const TreeNode& node) { - return IsMatrix( OptionalChild( node ) ); + return IsMatrix(OptionalChild(node)); } -inline OptionalMatrix3 IsMatrix3(const TreeNode &node ) +inline OptionalMatrix3 IsMatrix3(const TreeNode& node) { - return IsMatrix3( OptionalChild( node ) ); + return IsMatrix3(OptionalChild(node)); } -inline OptionalRect IsRect(const TreeNode &node ) +inline OptionalRect IsRect(const TreeNode& node) { - return IsRect( OptionalChild( node ) ); + return IsRect(OptionalChild(node)); } -inline OptionalExtents IsExtents(const TreeNode &node ) +inline OptionalExtents IsExtents(const TreeNode& node) { - return IsExtents( OptionalChild( node ) ); + return IsExtents(OptionalChild(node)); } // // // -inline Dali::Vector4 GetVector4(const TreeNode &child) +inline Dali::Vector4 GetVector4(const TreeNode& child) { - OptionalVector4 v( IsVector4( OptionalChild( child ) ) ); + OptionalVector4 v(IsVector4(OptionalChild(child))); DALI_ASSERT_ALWAYS(v); return *v; } -inline Dali::Vector3 GetVector3(const TreeNode &child) +inline Dali::Vector3 GetVector3(const TreeNode& child) { - OptionalVector3 v( IsVector3( OptionalChild( child ) ) ); + OptionalVector3 v(IsVector3(OptionalChild(child))); DALI_ASSERT_ALWAYS(v); return *v; } -inline Dali::Vector2 GetVector2(const TreeNode &child) +inline Dali::Vector2 GetVector2(const TreeNode& child) { - OptionalVector2 v( IsVector2( OptionalChild( child ) ) ); + OptionalVector2 v(IsVector2(OptionalChild(child))); DALI_ASSERT_ALWAYS(v); return *v; } -inline float GetFloat(const TreeNode &child) +inline float GetFloat(const TreeNode& child) { - OptionalFloat v( IsFloat( OptionalChild( child ) ) ); + OptionalFloat v(IsFloat(OptionalChild(child))); DALI_ASSERT_ALWAYS(v); return *v; } -inline bool GetBoolean(const TreeNode &child) +inline bool GetBoolean(const TreeNode& child) { - OptionalBoolean v( IsBoolean( OptionalChild( child ) ) ); + OptionalBoolean v(IsBoolean(OptionalChild(child))); DALI_ASSERT_ALWAYS(v); return *v; } -inline int GetInteger(const TreeNode &child) +inline int GetInteger(const TreeNode& child) { - OptionalInteger v( IsInteger( OptionalChild( child ) ) ); + OptionalInteger v(IsInteger(OptionalChild(child))); DALI_ASSERT_ALWAYS(v); return *v; } - - #endif // DALI_TOOLKIT_INTERNAL_BUILDER_GET_IS_INL diff --git a/dali-toolkit/internal/builder/builder-impl-debug.cpp b/dali-toolkit/internal/builder/builder-impl-debug.cpp index 2e89d71..d543669 100644 --- a/dali-toolkit/internal/builder/builder-impl-debug.cpp +++ b/dali-toolkit/internal/builder/builder-impl-debug.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,11 @@ */ #ifdef DEBUG_ENABLED +#include #include #include -#include -#include #include +#include namespace Dali { @@ -27,16 +27,16 @@ namespace Toolkit { namespace Internal { - -void LogTree( const Toolkit::JsonParser& parser ) +void LogTree(const Toolkit::JsonParser& parser) { - if( OptionalChild constants = IsChild(parser.GetRoot(), "constants") ) + if(OptionalChild constants = IsChild(parser.GetRoot(), "constants")) { for(TreeNode::ConstIterator iter = (*constants).CBegin(); - iter != (*constants).CEnd(); ++iter) + iter != (*constants).CEnd(); + ++iter) { - if( ( (*iter).first && strcmp( (*iter).first, "DUMP_TREE" ) == 0 ) || - ( (*iter).second.GetType() == TreeNode::STRING && strcmp( (*iter).second.GetString(), "DUMP_TREE" ) == 0 ) ) + if(((*iter).first && strcmp((*iter).first, "DUMP_TREE") == 0) || + ((*iter).second.GetType() == TreeNode::STRING && strcmp((*iter).second.GetString(), "DUMP_TREE") == 0)) { std::ostringstream oss; parser.Write(oss, 2); @@ -46,7 +46,7 @@ void LogTree( const Toolkit::JsonParser& parser ) } } -std::string PropertyValueToString( const Property::Value& value ) +std::string PropertyValueToString(const Property::Value& value) { std::ostringstream oss; oss << value; @@ -54,8 +54,8 @@ std::string PropertyValueToString( const Property::Value& value ) return oss.str(); } -} // Internal -} // Toolkit -} // Dali +} // namespace Internal +} // namespace Toolkit +} // namespace Dali #endif // DEBUG_ENABLED diff --git a/dali-toolkit/internal/builder/builder-impl-debug.h b/dali-toolkit/internal/builder/builder-impl-debug.h index 8d30929..14c1c17 100644 --- a/dali-toolkit/internal/builder/builder-impl-debug.h +++ b/dali-toolkit/internal/builder/builder-impl-debug.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_INTERNAL_BUILDER_IMPL_DEBUG_H /* - * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,10 @@ * limitations under the License. */ -#include #include +#include -#if defined( DEBUG_ENABLED ) +#if defined(DEBUG_ENABLED) namespace Dali { @@ -28,36 +28,33 @@ namespace Toolkit { namespace Internal { - -#define DUMP_PARSE_TREE(parser) LogTree(parser) -#define DUMP_TEST_MAPPINGS(parser) \ - OptionalChild mappings = IsChild( parser.GetRoot(), KEYNAME_MAPPINGS ); \ - if( mappings ) \ - { \ - std::ostringstream oss; \ - oss << "Mappings: {" << std::endl; \ - for( TreeNode::ConstIterator iter = (*mappings).CBegin(); iter != (*mappings).CEnd(); ++iter ) \ - { \ - Property::Value value; \ - bool converted = GetPropertyMap(*mappings, (*iter).first, Property::NONE, value ); \ - if( converted ) \ - { \ - oss << " " << (*iter).first << ":" << value << std::endl; \ - } \ - } \ - oss << "}" << std::endl; \ - DALI_LOG_INFO( gFilterScript, Debug::Verbose, oss.str().c_str() ); \ +#define DUMP_PARSE_TREE(parser) LogTree(parser) +#define DUMP_TEST_MAPPINGS(parser) \ + OptionalChild mappings = IsChild(parser.GetRoot(), KEYNAME_MAPPINGS); \ + if(mappings) \ + { \ + std::ostringstream oss; \ + oss << "Mappings: {" << std::endl; \ + for(TreeNode::ConstIterator iter = (*mappings).CBegin(); iter != (*mappings).CEnd(); ++iter) \ + { \ + Property::Value value; \ + bool converted = GetPropertyMap(*mappings, (*iter).first, Property::NONE, value); \ + if(converted) \ + { \ + oss << " " << (*iter).first << ":" << value << std::endl; \ + } \ + } \ + oss << "}" << std::endl; \ + DALI_LOG_INFO(gFilterScript, Debug::Verbose, oss.str().c_str()); \ } +void LogTree(const Toolkit::JsonParser& mParser); -void LogTree( const Toolkit::JsonParser& mParser ); - -std::string PropertyValueToString( const Property::Value& value ); - +std::string PropertyValueToString(const Property::Value& value); -} // Internal -} // Toolkit -} // Dali +} // namespace Internal +} // namespace Toolkit +} // namespace Dali #else diff --git a/dali-toolkit/internal/builder/builder-impl.cpp b/dali-toolkit/internal/builder/builder-impl.cpp index 8bcdff1..9ddab28 100644 --- a/dali-toolkit/internal/builder/builder-impl.cpp +++ b/dali-toolkit/internal/builder/builder-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,22 +22,23 @@ #include #include +#include +#include +#include +#include #include #include #include #include #include #include +#include #include -#include -#include -#include -#include // INTERNAL INCLUDES -#include #include #include +#include #include #include @@ -49,28 +50,24 @@ namespace Dali { - namespace Toolkit { - namespace Internal { class Replacement; -extern Animation CreateAnimation(const TreeNode& child, const Replacement& replacements, const Dali::Actor searchRoot, Builder* const builder ); +extern Animation CreateAnimation(const TreeNode& child, const Replacement& replacements, const Dali::Actor searchRoot, Builder* const builder); -extern Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); - -extern Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); +extern Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); +extern Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); #if defined(DEBUG_ENABLED) -Integration::Log::Filter* gFilterScript = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_SCRIPT"); +Integration::Log::Filter* gFilterScript = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_SCRIPT"); #endif namespace { - #define TOKEN_STRING(x) #x const std::string KEYNAME_ACTORS = "actors"; @@ -88,23 +85,22 @@ const std::string KEYNAME_TRANSITIONS = "transitions"; const std::string KEYNAME_TYPE = "type"; const std::string KEYNAME_VISUALS = "visuals"; -const std::string PROPERTIES = "properties"; +const std::string PROPERTIES = "properties"; const std::string ANIMATABLE_PROPERTIES = "animatableProperties"; typedef std::vector TreeNodeList; - -bool GetMappingKey( const std::string& str, std::string& key ) +bool GetMappingKey(const std::string& str, std::string& key) { - bool result = false; - std::string test( str ); - if( ! test.empty() ) + bool result = false; + std::string test(str); + if(!test.empty()) { - if( test.at(0) == '<' ) + if(test.at(0) == '<') { - if( test.at(test.length()-1) == '>' ) + if(test.at(test.length() - 1) == '>') { - key = test.substr( 1, test.length()-2 ); + key = test.substr(1, test.length() - 2); result = true; } } @@ -119,27 +115,27 @@ bool GetMappingKey( const std::string& str, std::string& key ) * style The style array to begin the collection from * styleList The style list to add nodes to apply */ -void CollectAllStyles( const TreeNode& stylesCollection, const TreeNode& style, TreeNodeList& styleList ) +void CollectAllStyles(const TreeNode& stylesCollection, const TreeNode& style, TreeNodeList& styleList) { // style is an array of style names - if( TreeNode::ARRAY == style.GetType() ) + if(TreeNode::ARRAY == style.GetType()) { for(TreeNode::ConstIterator iter = style.CBegin(); iter != style.CEnd(); ++iter) { - if( OptionalString styleName = IsString( (*iter).second ) ) + if(OptionalString styleName = IsString((*iter).second)) { - if( OptionalChild node = IsChildIgnoreCase( stylesCollection, *styleName) ) + if(OptionalChild node = IsChildIgnoreCase(stylesCollection, *styleName)) { - styleList.push_back( &(*node) ); + styleList.push_back(&(*node)); - OptionalChild subStyle = IsChild( *node, KEYNAME_INHERIT ); - if( ! subStyle ) + OptionalChild subStyle = IsChild(*node, KEYNAME_INHERIT); + if(!subStyle) { - subStyle = IsChild( *node, KEYNAME_STYLES ); + subStyle = IsChild(*node, KEYNAME_STYLES); } - if( subStyle ) + if(subStyle) { - CollectAllStyles( stylesCollection, *subStyle, styleList ); + CollectAllStyles(stylesCollection, *subStyle, styleList); } } } @@ -147,74 +143,75 @@ void CollectAllStyles( const TreeNode& stylesCollection, const TreeNode& style, } } - -} // namespace anon - +} // namespace Builder::Builder() -: mSlotDelegate( this ) +: mSlotDelegate(this) { mParser = Dali::Toolkit::JsonParser::New(); - Property::Map defaultDirs; - defaultDirs[TOKEN_STRING(DALI_IMAGE_DIR)] = AssetManager::GetDaliImagePath(); - defaultDirs[TOKEN_STRING(DALI_SOUND_DIR)] = AssetManager::GetDaliSoundPath(); - defaultDirs[TOKEN_STRING(DALI_STYLE_DIR)] = AssetManager::GetDaliStylePath(); - defaultDirs[TOKEN_STRING(DALI_STYLE_IMAGE_DIR)] = AssetManager::GetDaliStyleImagePath(); + Property::Map defaultConstants; + defaultConstants[TOKEN_STRING(DALI_IMAGE_DIR)] = AssetManager::GetDaliImagePath(); + defaultConstants[TOKEN_STRING(DALI_SOUND_DIR)] = AssetManager::GetDaliSoundPath(); + defaultConstants[TOKEN_STRING(DALI_STYLE_DIR)] = AssetManager::GetDaliStylePath(); + defaultConstants[TOKEN_STRING(DALI_STYLE_IMAGE_DIR)] = AssetManager::GetDaliStyleImagePath(); + defaultConstants[TOKEN_STRING(DALI_SHADER_VERSION_PREFIX)] = Shader::GetShaderVersionPrefix(); + defaultConstants[TOKEN_STRING(DALI_VERTEX_SHADER_PREFIX)] = Shader::GetVertexShaderPrefix(); + defaultConstants[TOKEN_STRING(DALI_FRAGMENT_SHADER_PREFIX)] = Shader::GetFragmentShaderPrefix(); - AddConstants( defaultDirs ); + AddConstants(defaultConstants); } -void Builder::LoadFromString( std::string const& data, Dali::Toolkit::Builder::UIFormat format ) +void Builder::LoadFromString(std::string const& data, Dali::Toolkit::Builder::UIFormat format) { // parser to get constants and includes only Dali::Toolkit::JsonParser parser = Dali::Toolkit::JsonParser::New(); - if( !parser.Parse( data ) ) + if(!parser.Parse(data)) { - DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n", - parser.GetErrorLineNumber(), - parser.GetErrorColumn(), - parser.GetErrorDescription().c_str() ); + DALI_LOG_WARNING("JSON Parse Error:%d:%d:'%s'\n", + parser.GetErrorLineNumber(), + parser.GetErrorColumn(), + parser.GetErrorDescription().c_str()); DALI_ASSERT_ALWAYS(!"Cannot parse JSON"); } else { // load constant map (allows the user to override the constants in the json after loading) - LoadConstants( *parser.GetRoot(), mReplacementMap ); + LoadConstants(*parser.GetRoot(), mReplacementMap); // load configuration map - LoadConfiguration( *parser.GetRoot(), mConfigurationMap ); + LoadConfiguration(*parser.GetRoot(), mConfigurationMap); // merge includes - if( OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES) ) + if(OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES)) { - Replacement replacer( mReplacementMap ); + Replacement replacer(mReplacementMap); for(TreeNode::ConstIterator iter = (*includes).CBegin(); iter != (*includes).CEnd(); ++iter) { - OptionalString filename = replacer.IsString( (*iter).second ); + OptionalString filename = replacer.IsString((*iter).second); - if( filename ) + if(filename) { #if defined(DEBUG_ENABLED) DALI_SCRIPT_VERBOSE("Loading Include '%s'\n", (*filename).c_str()); #endif - LoadFromString( GetFileContents(*filename) ); + LoadFromString(GetFileContents(*filename)); } } } - if( mParser.Parse( data ) ) + if(mParser.Parse(data)) { // Drop the styles and get them to be rebuilt against the new parse tree as required. mStyles.Clear(); } else { - DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n", - mParser.GetErrorLineNumber(), - mParser.GetErrorColumn(), - mParser.GetErrorDescription().c_str() ); + DALI_LOG_WARNING("JSON Parse Error:%d:%d:'%s'\n", + mParser.GetErrorLineNumber(), + mParser.GetErrorColumn(), + mParser.GetErrorDescription().c_str()); DALI_ASSERT_ALWAYS(!"Cannot parse JSON"); } @@ -226,12 +223,12 @@ void Builder::LoadFromString( std::string const& data, Dali::Toolkit::Builder::U DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Cannot parse JSON"); } -void Builder::AddConstants( const Property::Map& map ) +void Builder::AddConstants(const Property::Map& map) { - mReplacementMap.Merge( map ); + mReplacementMap.Merge(map); } -void Builder::AddConstant( const std::string& key, const Property::Value& value ) +void Builder::AddConstant(const std::string& key, const Property::Value& value) { mReplacementMap[key] = value; } @@ -246,10 +243,10 @@ const Property::Map& Builder::GetConstants() const return mReplacementMap; } -const Property::Value& Builder::GetConstant( const std::string& key ) const +const Property::Value& Builder::GetConstant(const std::string& key) const { - Property::Value* match = mReplacementMap.Find( key ); - if( match ) + Property::Value* match = mReplacementMap.Find(key); + if(match) { return (*match); } @@ -260,107 +257,107 @@ const Property::Value& Builder::GetConstant( const std::string& key ) const } } -Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor ) +Animation Builder::CreateAnimation(const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor) { Replacement replacement(map, mReplacementMap); - return CreateAnimation( animationName, replacement, sourceActor); + return CreateAnimation(animationName, replacement, sourceActor); } -Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map ) +Animation Builder::CreateAnimation(const std::string& animationName, const Property::Map& map) { Replacement replacement(map, mReplacementMap); - return CreateAnimation( animationName, replacement, Stage::GetCurrent().GetRootLayer() ); + return CreateAnimation(animationName, replacement, Stage::GetCurrent().GetRootLayer()); } -Animation Builder::CreateAnimation( const std::string& animationName, Dali::Actor sourceActor ) +Animation Builder::CreateAnimation(const std::string& animationName, Dali::Actor sourceActor) { - Replacement replacement( mReplacementMap ); + Replacement replacement(mReplacementMap); - return CreateAnimation( animationName, replacement, sourceActor ); + return CreateAnimation(animationName, replacement, sourceActor); } -Animation Builder::CreateAnimation( const std::string& animationName ) +Animation Builder::CreateAnimation(const std::string& animationName) { - Replacement replacement( mReplacementMap ); + Replacement replacement(mReplacementMap); - return CreateAnimation( animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer() ); + return CreateAnimation(animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer()); } -BaseHandle Builder::Create( const std::string& templateName ) +BaseHandle Builder::Create(const std::string& templateName) { - Replacement replacement( mReplacementMap ); - return Create( templateName, replacement ); + Replacement replacement(mReplacementMap); + return Create(templateName, replacement); } -BaseHandle Builder::Create( const std::string& templateName, const Property::Map& map ) +BaseHandle Builder::Create(const std::string& templateName, const Property::Map& map) { - Replacement replacement( map, mReplacementMap ); - return Create( templateName, replacement ); + Replacement replacement(map, mReplacementMap); + return Create(templateName, replacement); } -BaseHandle Builder::CreateFromJson( const std::string& json ) +BaseHandle Builder::CreateFromJson(const std::string& json) { BaseHandle ret; // merge in new template, hoping no one else has one named '@temp@' std::string newTemplate = - std::string("{\"templates\":{\"@temp@\":") + \ - json + \ + std::string("{\"templates\":{\"@temp@\":") + + json + std::string("}}"); - if( mParser.Parse(newTemplate) ) + if(mParser.Parse(newTemplate)) { - Replacement replacement( mReplacementMap ); - ret = Create( "@temp@", replacement ); + Replacement replacement(mReplacementMap); + ret = Create("@temp@", replacement); } return ret; } -bool Builder::ApplyFromJson( Handle& handle, const std::string& json ) +bool Builder::ApplyFromJson(Handle& handle, const std::string& json) { bool ret = false; // merge new style, hoping no one else has one named '@temp@' std::string newStyle = - std::string("{\"styles\":{\"@temp@\":") + \ - json + \ + std::string("{\"styles\":{\"@temp@\":") + + json + std::string("}}"); - if( mParser.Parse(newStyle) ) + if(mParser.Parse(newStyle)) { - Replacement replacement( mReplacementMap ); - ret = ApplyStyle( "@temp@", handle, replacement ); + Replacement replacement(mReplacementMap); + ret = ApplyStyle("@temp@", handle, replacement); } return ret; } -bool Builder::ApplyStyle( const std::string& styleName, Handle& handle ) +bool Builder::ApplyStyle(const std::string& styleName, Handle& handle) { - Replacement replacer( mReplacementMap ); - return ApplyStyle( styleName, handle, replacer ); + Replacement replacer(mReplacementMap); + return ApplyStyle(styleName, handle, replacer); } -bool Builder::LookupStyleName( const std::string& styleName ) +bool Builder::LookupStyleName(const std::string& styleName) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); - OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES ); - OptionalChild style = IsChildIgnoreCase( *styles, styleName ); + OptionalChild styles = IsChild(*mParser.GetRoot(), KEYNAME_STYLES); + OptionalChild style = IsChildIgnoreCase(*styles, styleName); - if( styles && style ) + if(styles && style) { return true; } return false; } -const StylePtr Builder::GetStyle( const std::string& styleName ) +const StylePtr Builder::GetStyle(const std::string& styleName) { - const StylePtr* style = mStyles.FindConst( styleName ); + const StylePtr* style = mStyles.FindConst(styleName); - if( style==NULL ) + if(style == NULL) { return StylePtr(NULL); } @@ -370,50 +367,50 @@ const StylePtr Builder::GetStyle( const std::string& styleName ) } } -void Builder::AddActors( Actor toActor ) +void Builder::AddActors(Actor toActor) { // 'stage' is the default/by convention section to add from - AddActors( "stage", toActor ); + AddActors("stage", toActor); } -void Builder::AddActors( const std::string §ionName, Actor toActor ) +void Builder::AddActors(const std::string& sectionName, Actor toActor) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); Property::Map overrideMap; - Replacement replacements(overrideMap, mReplacementMap); + Replacement replacements(overrideMap, mReplacementMap); OptionalChild add = IsChild(*mParser.GetRoot(), sectionName); - if( add ) + if(add) { - for( TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter) { // empty actor adds directly to the stage - BaseHandle baseHandle = DoCreate( *mParser.GetRoot(), (*iter).second, Actor(), replacements ); - Actor actor = Actor::DownCast(baseHandle); + BaseHandle baseHandle = DoCreate(*mParser.GetRoot(), (*iter).second, Actor(), replacements); + Actor actor = Actor::DownCast(baseHandle); if(actor) { - toActor.Add( actor ); + toActor.Add(actor); } } // if were adding the 'stage' section then also check for a render task called stage // to add automatically - if( "stage" == sectionName ) + if("stage" == sectionName) { - if( OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks") ) + if(OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks")) { - if( OptionalChild tasks = IsChild(*renderTasks, "stage") ) + if(OptionalChild tasks = IsChild(*renderTasks, "stage")) { - CreateRenderTask( "stage" ); + CreateRenderTask("stage"); } } } } } -void Builder::CreateRenderTask( const std::string &name ) +void Builder::CreateRenderTask(const std::string& name) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); @@ -430,10 +427,10 @@ void Builder::CreateRenderTask( const std::string &name ) // to setup task zero and onwards. Although this does overwrite // the properties of the current task. // - if( OptionalChild renderTask = IsChild(*tasks, name ) ) + if(OptionalChild renderTask = IsChild(*tasks, name)) { - RenderTaskList list = stage.GetRenderTaskList(); - unsigned int start = list.GetTaskCount(); + RenderTaskList list = stage.GetRenderTaskList(); + unsigned int start = list.GetTaskCount(); RenderTask task; if(0 == start) @@ -445,61 +442,61 @@ void Builder::CreateRenderTask( const std::string &name ) } TreeNode::ConstIterator iter = (*renderTask).CBegin(); - task = list.GetTask( start - 1 ); + task = list.GetTask(start - 1); - SetupTask( task, (*iter).second, constant ); + SetupTask(task, (*iter).second, constant); ++iter; - for(; iter != (*renderTask).CEnd(); ++iter ) + for(; iter != (*renderTask).CEnd(); ++iter) { task = list.CreateTask(); - SetupTask( task, (*iter).second, constant ); + SetupTask(task, (*iter).second, constant); } } } } -Path Builder::GetPath( const std::string& name ) +Path Builder::GetPath(const std::string& name) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); Path ret; - PathLut::const_iterator iter( mPathLut.find( name ) ); - if( iter != mPathLut.end() ) + PathLut::const_iterator iter(mPathLut.find(name)); + if(iter != mPathLut.end()) { ret = iter->second; } else { - if( OptionalChild paths = IsChild( *mParser.GetRoot(), "paths") ) + if(OptionalChild paths = IsChild(*mParser.GetRoot(), "paths")) { - if( OptionalChild path = IsChild( *paths, name ) ) + if(OptionalChild path = IsChild(*paths, name)) { //points property - if( OptionalChild pointsProperty = IsChild( *path, "points") ) + if(OptionalChild pointsProperty = IsChild(*path, "points")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { ret = Path::New(); - ret.SetProperty( Path::Property::POINTS, points); + ret.SetProperty(Path::Property::POINTS, points); //controlPoints property - if( OptionalChild pointsProperty = IsChild( *path, "controlPoints") ) + if(OptionalChild pointsProperty = IsChild(*path, "controlPoints")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { - ret.SetProperty( Path::Property::CONTROL_POINTS, points); + ret.SetProperty(Path::Property::CONTROL_POINTS, points); } } else { //Curvature float curvature(0.25f); - if( OptionalFloat pointsProperty = IsFloat( *path, "curvature") ) + if(OptionalFloat pointsProperty = IsFloat(*path, "curvature")) { curvature = *pointsProperty; } @@ -507,31 +504,30 @@ Path Builder::GetPath( const std::string& name ) } //Add the new path to the hash table for paths - mPathLut[ name ] = ret; + mPathLut[name] = ret; } } else { //Interpolation points not specified - DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str()); } } - } } return ret; } -PathConstrainer Builder::GetPathConstrainer( const std::string& name ) +PathConstrainer Builder::GetPathConstrainer(const std::string& name) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); //Search the pathConstrainer in the LUT - size_t count( mPathConstrainerLut.size() ); - for( size_t i(0); i!=count; ++i ) + size_t count(mPathConstrainerLut.size()); + for(size_t i(0); i != count; ++i) { - if( mPathConstrainerLut[i].name == name ) + if(mPathConstrainerLut[i].name == name) { //PathConstrainer has already been created return mPathConstrainerLut[i].pathConstrainer; @@ -540,62 +536,62 @@ PathConstrainer Builder::GetPathConstrainer( const std::string& name ) //Create a new PathConstrainer PathConstrainer ret; - if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") ) + if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers")) { - if( OptionalChild pathConstrainer = IsChild( *constrainers, name ) ) + if(OptionalChild pathConstrainer = IsChild(*constrainers, name)) { OptionalString constrainerType(IsString(IsChild(*pathConstrainer, "type"))); if(!constrainerType) { - DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str()); } - else if( *constrainerType == "PathConstrainer") + else if(*constrainerType == "PathConstrainer") { //points property - if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "points") ) + if(OptionalChild pointsProperty = IsChild(*pathConstrainer, "points")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { ret = PathConstrainer::New(); - ret.SetProperty( PathConstrainer::Property::POINTS, points); + ret.SetProperty(PathConstrainer::Property::POINTS, points); //controlPoints property - if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "controlPoints") ) + if(OptionalChild pointsProperty = IsChild(*pathConstrainer, "controlPoints")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { - ret.SetProperty( PathConstrainer::Property::CONTROL_POINTS, points); + ret.SetProperty(PathConstrainer::Property::CONTROL_POINTS, points); } //Forward vector - OptionalVector3 forward( IsVector3( IsChild(*pathConstrainer, "forward" ) ) ); - if( forward ) + OptionalVector3 forward(IsVector3(IsChild(*pathConstrainer, "forward"))); + if(forward) { - ret.SetProperty( PathConstrainer::Property::FORWARD, *forward); + ret.SetProperty(PathConstrainer::Property::FORWARD, *forward); } //Add the new constrainer to the vector of PathConstrainer - PathConstrainerEntry entry = {name,ret}; - mPathConstrainerLut.push_back( entry ); + PathConstrainerEntry entry = {name, ret}; + mPathConstrainerLut.push_back(entry); } else { //Control points not specified - DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str()); } } } else { //Interpolation points not specified - DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str()); } } else { - DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str() ); + DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str()); } } } @@ -603,21 +599,20 @@ PathConstrainer Builder::GetPathConstrainer( const std::string& name ) return ret; } - -bool Builder::IsPathConstrainer( const std::string& name ) +bool Builder::IsPathConstrainer(const std::string& name) { - size_t count( mPathConstrainerLut.size() ); - for( size_t i(0); i!=count; ++i ) + size_t count(mPathConstrainerLut.size()); + for(size_t i(0); i != count; ++i) { - if( mPathConstrainerLut[i].name == name ) + if(mPathConstrainerLut[i].name == name) { return true; } } - if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") ) + if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers")) { - if( OptionalChild constrainer = IsChild( *constrainers, name ) ) + if(OptionalChild constrainer = IsChild(*constrainers, name)) { OptionalString constrainerType(IsString(IsChild(*constrainer, "type"))); if(!constrainerType) @@ -626,22 +621,22 @@ bool Builder::IsPathConstrainer( const std::string& name ) } else { - return *constrainerType == "PathConstrainer"; + return *constrainerType == "PathConstrainer"; } } } return false; } -Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name ) +Dali::LinearConstrainer Builder::GetLinearConstrainer(const std::string& name) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); //Search the LinearConstrainer in the LUT - size_t count( mLinearConstrainerLut.size() ); - for( size_t i(0); i!=count; ++i ) + size_t count(mLinearConstrainerLut.size()); + for(size_t i(0); i != count; ++i) { - if( mLinearConstrainerLut[i].name == name ) + if(mLinearConstrainerLut[i].name == name) { //LinearConstrainer has already been created return mLinearConstrainerLut[i].linearConstrainer; @@ -650,49 +645,49 @@ Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name ) //Create a new LinearConstrainer LinearConstrainer ret; - if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") ) + if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers")) { - if( OptionalChild linearConstrainer = IsChild( *constrainers, name ) ) + if(OptionalChild linearConstrainer = IsChild(*constrainers, name)) { OptionalString constrainerType(IsString(IsChild(*linearConstrainer, "type"))); if(!constrainerType) { - DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str()); } - else if( *constrainerType == "LinearConstrainer") + else if(*constrainerType == "LinearConstrainer") { //points property - if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "value") ) + if(OptionalChild pointsProperty = IsChild(*linearConstrainer, "value")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { ret = Dali::LinearConstrainer::New(); - ret.SetProperty( LinearConstrainer::Property::VALUE, points); + ret.SetProperty(LinearConstrainer::Property::VALUE, points); //controlPoints property - if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "progress") ) + if(OptionalChild pointsProperty = IsChild(*linearConstrainer, "progress")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { - ret.SetProperty( LinearConstrainer::Property::PROGRESS, points); + ret.SetProperty(LinearConstrainer::Property::PROGRESS, points); } } //Add the new constrainer to vector of LinearConstrainer - LinearConstrainerEntry entry = {name,ret}; - mLinearConstrainerLut.push_back( entry ); + LinearConstrainerEntry entry = {name, ret}; + mLinearConstrainerLut.push_back(entry); } } else { //Interpolation points not specified - DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str()); } } else { - DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str() ); + DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str()); } } } @@ -700,21 +695,21 @@ Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name ) return ret; } -bool Builder::IsLinearConstrainer( const std::string& name ) +bool Builder::IsLinearConstrainer(const std::string& name) { // Search the LinearConstrainer in the LUT - size_t count( mLinearConstrainerLut.size() ); - for( size_t i(0); i!=count; ++i ) + size_t count(mLinearConstrainerLut.size()); + for(size_t i(0); i != count; ++i) { - if( mLinearConstrainerLut[i].name == name ) + if(mLinearConstrainerLut[i].name == name) { return true; } } - if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") ) + if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers")) { - if( OptionalChild constrainer = IsChild( *constrainers, name ) ) + if(OptionalChild constrainer = IsChild(*constrainers, name)) { OptionalString constrainerType(IsString(IsChild(*constrainer, "type"))); if(!constrainerType) @@ -723,7 +718,7 @@ bool Builder::IsLinearConstrainer( const std::string& name ) } else { - return *constrainerType == "LinearConstrainer"; + return *constrainerType == "LinearConstrainer"; } } } @@ -744,54 +739,55 @@ Builder::~Builder() { } -void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap ) +void Builder::LoadConfiguration(const TreeNode& root, Property::Map& intoMap) { Replacement replacer(intoMap); - if( OptionalChild constants = IsChild(root, "config") ) + if(OptionalChild constants = IsChild(root, "config")) { for(TreeNode::ConstIterator iter = (*constants).CBegin(); - iter != (*constants).CEnd(); ++iter) + iter != (*constants).CEnd(); + ++iter) { Dali::Property::Value property; - if( (*iter).second.GetName() ) + if((*iter).second.GetName()) { - DeterminePropertyFromNode( (*iter).second, property, replacer ); + DeterminePropertyFromNode((*iter).second, property, replacer); // If config is string, find constant and replace it to original value. - if( (*iter).second.GetType() == TreeNode::STRING ) + if((*iter).second.GetType() == TreeNode::STRING) { std::string stringConfigValue; - if( property.Get( stringConfigValue ) ) + if(property.Get(stringConfigValue)) { std::size_t pos = 0; - while( pos < stringConfigValue.size() ) + while(pos < stringConfigValue.size()) { // If we can't find "{","}" pair in stringConfigValue, will out loop. - std::size_t leftPos = stringConfigValue.find( "{", pos ); - if( leftPos != std::string::npos ) + std::size_t leftPos = stringConfigValue.find("{", pos); + if(leftPos != std::string::npos) { - std::size_t rightPos = stringConfigValue.find( "}", pos+1 ); + std::size_t rightPos = stringConfigValue.find("}", pos + 1); - if( rightPos != std::string::npos ) + if(rightPos != std::string::npos) { // If we find "{","}" pair but can't find matched constant // try to find other "{","}" pair after current left position. - pos = leftPos+1; + pos = leftPos + 1; - for( uint32_t i = 0; i < mReplacementMap.Count() ; i++ ) + for(uint32_t i = 0; i < mReplacementMap.Count(); i++) { Property::Key constant = mReplacementMap.GetKeyAt(i); // Compare string which is between "{" and "}" with constant string // If they are same, change string in stringConfigValue to mapped constant value. - if ( 0 == stringConfigValue.compare( leftPos+1, rightPos-leftPos-1, constant.stringKey ) ) + if(0 == stringConfigValue.compare(leftPos + 1, rightPos - leftPos - 1, constant.stringKey)) { std::string replaceString; - mReplacementMap.GetValue(i).Get( replaceString ); + mReplacementMap.GetValue(i).Get(replaceString); - stringConfigValue.replace( leftPos, rightPos-leftPos+1, replaceString ); + stringConfigValue.replace(leftPos, rightPos - leftPos + 1, replaceString); pos = leftPos + replaceString.size(); break; } @@ -809,87 +805,88 @@ void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap ) pos = stringConfigValue.size(); } } - property = Property::Value( stringConfigValue ); + property = Property::Value(stringConfigValue); } } - intoMap[ (*iter).second.GetName() ] = property; + intoMap[(*iter).second.GetName()] = property; } } } } -void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap ) +void Builder::LoadConstants(const TreeNode& root, Property::Map& intoMap) { Replacement replacer(intoMap); - if( OptionalChild constants = IsChild(root, "constants") ) + if(OptionalChild constants = IsChild(root, "constants")) { for(TreeNode::ConstIterator iter = (*constants).CBegin(); - iter != (*constants).CEnd(); ++iter) + iter != (*constants).CEnd(); + ++iter) { Dali::Property::Value property; - if( (*iter).second.GetName() ) + if((*iter).second.GetName()) { #if defined(DEBUG_ENABLED) DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName()); #endif - DeterminePropertyFromNode( (*iter).second, property, replacer ); - intoMap[ (*iter).second.GetName() ] = property; + DeterminePropertyFromNode((*iter).second, property, replacer); + intoMap[(*iter).second.GetName()] = property; } } } #if defined(DEBUG_ENABLED) - Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" ); - if( iter && iter->GetType() == Property::STRING ) + Property::Value* iter = intoMap.Find("CONFIG_SCRIPT_LOG_LEVEL"); + if(iter && iter->GetType() == Property::STRING) { - std::string logLevel( iter->Get< std::string >() ); - if( logLevel == "NoLogging" ) + std::string logLevel(iter->Get()); + if(logLevel == "NoLogging") { - gFilterScript->SetLogLevel( Integration::Log::NoLogging ); + gFilterScript->SetLogLevel(Integration::Log::NoLogging); } - else if( logLevel == "Concise" ) + else if(logLevel == "Concise") { - gFilterScript->SetLogLevel( Integration::Log::Concise ); + gFilterScript->SetLogLevel(Integration::Log::Concise); } - else if( logLevel == "General" ) + else if(logLevel == "General") { - gFilterScript->SetLogLevel( Integration::Log::General ); + gFilterScript->SetLogLevel(Integration::Log::General); } - else if( logLevel == "Verbose" ) + else if(logLevel == "Verbose") { - gFilterScript->SetLogLevel( Integration::Log::Verbose ); + gFilterScript->SetLogLevel(Integration::Log::Verbose); } } #endif } -Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor ) +Animation Builder::CreateAnimation(const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); Animation anim; - if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") ) + if(OptionalChild animations = IsChild(*mParser.GetRoot(), "animations")) { - if( OptionalChild animation = IsChild(*animations, animationName) ) + if(OptionalChild animation = IsChild(*animations, animationName)) { - anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this ); + anim = Dali::Toolkit::Internal::CreateAnimation(*animation, replacement, sourceActor, this); } else { - DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() ); + DALI_SCRIPT_WARNING("Request for Animation called '%s' failed\n", animationName.c_str()); } } else { - DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() ); + DALI_SCRIPT_WARNING("Request for Animation called '%s' failed (no animation section)\n", animationName.c_str()); } return anim; } -BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant ) +BaseHandle Builder::Create(const std::string& templateName, const Replacement& constant) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); @@ -897,7 +894,7 @@ BaseHandle Builder::Create( const std::string& templateName, const Replacement& OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES); - if( !templates ) + if(!templates) { DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n"); } @@ -910,7 +907,7 @@ BaseHandle Builder::Create( const std::string& templateName, const Replacement& } else { - OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) ); + OptionalString type = constant.IsString(IsChild(*childTemplate, KEYNAME_TYPE)); if(!type) { @@ -918,7 +915,7 @@ BaseHandle Builder::Create( const std::string& templateName, const Replacement& } else { - baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant ); + baseHandle = DoCreate(*mParser.GetRoot(), *childTemplate, Actor(), constant); } } } @@ -931,31 +928,30 @@ BaseHandle Builder::Create( const std::string& templateName, const Replacement& * If parent given and an actor type was created then add it to the parent and * recursively add nodes children. */ -BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node, - Actor parent, const Replacement& replacements ) +BaseHandle Builder::DoCreate(const TreeNode& root, const TreeNode& node, Actor parent, const Replacement& replacements) { - BaseHandle baseHandle; - TypeInfo typeInfo; + BaseHandle baseHandle; + TypeInfo typeInfo; const TreeNode* templateNode = NULL; - if( OptionalString typeName = IsString(node, KEYNAME_TYPE) ) + if(OptionalString typeName = IsString(node, KEYNAME_TYPE)) { - typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName ); + typeInfo = TypeRegistry::Get().GetTypeInfo(*typeName); - if( !typeInfo ) + if(!typeInfo) { // a template name is also allowed inplace of the type name - OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES); + OptionalChild templates = IsChild(root, KEYNAME_TEMPLATES); - if( templates ) + if(templates) { - if( OptionalChild isTemplate = IsChild( *templates, *typeName ) ) + if(OptionalChild isTemplate = IsChild(*templates, *typeName)) { templateNode = &(*isTemplate); - if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) ) + if(OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE)) { - typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName ); + typeInfo = TypeRegistry::Get().GetTypeInfo(*templateTypeName); } } } @@ -968,13 +964,12 @@ BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node, } else { - baseHandle = typeInfo.CreateInstance(); - Handle handle = Handle::DownCast(baseHandle); - Actor actor = Actor::DownCast(handle); + baseHandle = typeInfo.CreateInstance(); + Handle handle = Handle::DownCast(baseHandle); + Actor actor = Actor::DownCast(handle); if(handle) { - DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str()); #if defined(DEBUG_ENABLED) @@ -986,52 +981,52 @@ BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node, if(actor) { - DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetProperty< int >( Actor::Property::ID )); + DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetProperty(Actor::Property::ID)); } - Toolkit::Control control = Toolkit::Control::DownCast(handle); + Toolkit::Control control = Toolkit::Control::DownCast(handle); if(control) { - DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetProperty< int >( Actor::Property::ID )); + DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetProperty(Actor::Property::ID)); } #endif // DEBUG_ENABLED - if( templateNode ) + if(templateNode) { - ApplyProperties( root, *templateNode, handle, replacements ); + ApplyProperties(root, *templateNode, handle, replacements); - if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) ) + if(OptionalChild actors = IsChild(*templateNode, KEYNAME_ACTORS)) { - for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter ) + for(TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter) { - DoCreate( root, (*iter).second, actor, replacements ); + DoCreate(root, (*iter).second, actor, replacements); } } } - if( actor ) + if(actor) { // add children of all the styles - if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) ) + if(OptionalChild actors = IsChild(node, KEYNAME_ACTORS)) { - for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter ) + for(TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter) { - DoCreate( root, (*iter).second, actor, replacements ); + DoCreate(root, (*iter).second, actor, replacements); } } // apply style on top as they need the children to exist - ApplyAllStyleProperties( root, node, actor, replacements ); + ApplyAllStyleProperties(root, node, actor, replacements); // then add to parent - if( parent ) + if(parent) { - parent.Add( actor ); + parent.Add(actor); } } else { - ApplyProperties( root, node, handle, replacements ); + ApplyProperties(root, node, handle, replacements); } } else @@ -1043,46 +1038,46 @@ BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node, return baseHandle; } -void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant ) +void Builder::SetupTask(RenderTask& task, const TreeNode& node, const Replacement& constant) { const Stage& stage = Stage::GetCurrent(); - Layer root = stage.GetRootLayer(); + Layer root = stage.GetRootLayer(); - if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) ) + if(OptionalString s = constant.IsString(IsChild(node, "sourceActor"))) { Actor actor = root.FindChildByName(*s); if(actor) { - task.SetSourceActor( actor ); + task.SetSourceActor(actor); } else { - DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() ); + DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str()); } } - if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) ) + if(OptionalString s = constant.IsString(IsChild(node, "cameraActor"))) { - CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) ); + CameraActor actor = CameraActor::DownCast(root.FindChildByName(*s)); if(actor) { - task.SetCameraActor( actor ); + task.SetCameraActor(actor); } else { - DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() ); + DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str()); } } - if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) ) + if(OptionalString s = constant.IsString(IsChild(node, "screenToFrameBufferFunction"))) { if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s) { - task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION ); + task.SetScreenToFrameBufferFunction(RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION); } else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s) { - task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION ); + task.SetScreenToFrameBufferFunction(RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION); } else { @@ -1091,21 +1086,21 @@ void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replaceme } // other setup is via the property system - SetProperties( node, task, constant ); + SetProperties(node, task, constant); } -bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement ) +bool Builder::ApplyStyle(const std::string& styleName, Handle& handle, const Replacement& replacement) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); - OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES ); + OptionalChild styles = IsChild(*mParser.GetRoot(), KEYNAME_STYLES); - std::string styleNameLower(styleName); - OptionalChild style = IsChildIgnoreCase( *styles, styleNameLower ); + std::string styleNameLower(styleName); + OptionalChild style = IsChildIgnoreCase(*styles, styleNameLower); - if( styles && style ) + if(styles && style) { - ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement ); + ApplyAllStyleProperties(*mParser.GetRoot(), *style, handle, replacement); return true; } else @@ -1114,38 +1109,37 @@ bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Re } } -void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node, - Dali::Handle& handle, const Replacement& constant ) +void Builder::ApplyAllStyleProperties(const TreeNode& root, const TreeNode& node, Dali::Handle& handle, const Replacement& constant) { const char* styleName = node.GetName(); StylePtr style = Style::New(); StylePtr* matchedStyle = NULL; - if( styleName ) + if(styleName) { - matchedStyle = mStyles.Find( styleName ); - if( ! matchedStyle ) + matchedStyle = mStyles.Find(styleName); + if(!matchedStyle) { - OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES); + OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES); OptionalChild inheritFromNode = IsChild(node, KEYNAME_INHERIT); - if( !inheritFromNode ) + if(!inheritFromNode) { - inheritFromNode = IsChild( node, KEYNAME_STYLES ); + inheritFromNode = IsChild(node, KEYNAME_STYLES); } - if( styleNodes ) + if(styleNodes) { - if( inheritFromNode ) + if(inheritFromNode) { TreeNodeList additionalStyleNodes; - CollectAllStyles( *styleNodes, *inheritFromNode, additionalStyleNodes ); + CollectAllStyles(*styleNodes, *inheritFromNode, additionalStyleNodes); #if defined(DEBUG_ENABLED) for(TreeNode::ConstIterator iter = (*inheritFromNode).CBegin(); iter != (*inheritFromNode).CEnd(); ++iter) { - if( OptionalString styleName = IsString( (*iter).second ) ) + if(OptionalString styleName = IsString((*iter).second)) { DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str()); } @@ -1155,123 +1149,123 @@ void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& nod // a style may have other styles, which has other styles etc so we apply in reverse by convention. for(TreeNodeList::reverse_iterator iter = additionalStyleNodes.rbegin(); iter != additionalStyleNodes.rend(); ++iter) { - RecordStyle( style, *(*iter), handle, constant ); - ApplySignals( root, *(*iter), handle ); - ApplyStylesByActor( root, *(*iter), handle, constant ); + RecordStyle(style, *(*iter), handle, constant); + ApplySignals(root, *(*iter), handle); + ApplyStylesByActor(root, *(*iter), handle, constant); } } - RecordStyle( style, node, handle, constant ); - mStyles.Add( styleName, style ); // shallow copy + RecordStyle(style, node, handle, constant); + mStyles.Add(styleName, style); // shallow copy matchedStyle = &style; } } } - if( matchedStyle ) + if(matchedStyle) { - StylePtr style( *matchedStyle ); + StylePtr style(*matchedStyle); Dictionary instancedProperties; - style->ApplyVisualsAndPropertiesRecursively( handle, instancedProperties ); + style->ApplyVisualsAndPropertiesRecursively(handle, instancedProperties); } else // If there were no styles, instead set properties { - SetProperties( node, handle, constant ); + SetProperties(node, handle, constant); } - ApplySignals( root, node, handle ); - ApplyStylesByActor( root, node, handle, constant ); + ApplySignals(root, node, handle); + ApplyStylesByActor(root, node, handle, constant); } -void Builder::RecordStyle( StylePtr style, - const TreeNode& node, - Dali::Handle& handle, - const Replacement& replacements ) +void Builder::RecordStyle(StylePtr style, + const TreeNode& node, + Dali::Handle& handle, + const Replacement& replacements) { // With repeated calls, accumulate inherited states, visuals and properties // but override any with same name - for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter) { const TreeNode::KeyNodePair& keyValue = *iter; - std::string key( keyValue.first ); - if( key == KEYNAME_STATES ) + std::string key(keyValue.first); + if(key == KEYNAME_STATES) { const TreeNode& states = keyValue.second; - if( states.GetType() != TreeNode::OBJECT ) + if(states.GetType() != TreeNode::OBJECT) { - DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str() ); + DALI_LOG_WARNING("RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str()); continue; } - for( TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter) { const TreeNode& stateNode = (*iter).second; - const char* stateName = stateNode.GetName(); - if( stateNode.GetType() != TreeNode::OBJECT ) + const char* stateName = stateNode.GetName(); + if(stateNode.GetType() != TreeNode::OBJECT) { - DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", stateName ); + DALI_LOG_WARNING("RecordStyle() Node \"%s\" is not a JSON object\n", stateName); continue; } - StylePtr* stylePtr = style->subStates.Find( stateName ); - if( stylePtr ) + StylePtr* stylePtr = style->subStates.Find(stateName); + if(stylePtr) { StylePtr style(*stylePtr); - RecordStyle( style, stateNode, handle, replacements ); + RecordStyle(style, stateNode, handle, replacements); } else { StylePtr subState = Style::New(); - RecordStyle( subState, stateNode, handle, replacements ); - style->subStates.Add( stateName, subState ); + RecordStyle(subState, stateNode, handle, replacements); + style->subStates.Add(stateName, subState); } } } - else if( key == KEYNAME_VISUALS ) + else if(key == KEYNAME_VISUALS) { - for( TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter) { // Each key in this table should be a property name matching a visual. const TreeNode::KeyNodePair& visual = *iter; - Dali::Property::Value property(Property::MAP); - if( DeterminePropertyFromNode( visual.second, Property::MAP, property, replacements ) ) + Dali::Property::Value property(Property::MAP); + if(DeterminePropertyFromNode(visual.second, Property::MAP, property, replacements)) { - Property::Map* mapPtr = style->visuals.Find( visual.first ); - if( mapPtr ) + Property::Map* mapPtr = style->visuals.Find(visual.first); + if(mapPtr) { // Override existing visuals mapPtr->Clear(); - mapPtr->Merge( *property.GetMap() ); + mapPtr->Merge(*property.GetMap()); } else { Property::Map* map = property.GetMap(); - if( map ) + if(map) { - style->visuals.Add( visual.first, *map ); + style->visuals.Add(visual.first, *map); } } } } } - else if( key == KEYNAME_ENTRY_TRANSITION ) + else if(key == KEYNAME_ENTRY_TRANSITION) { - RecordTransitionData( keyValue, style->entryTransition, replacements ); + RecordTransitionData(keyValue, style->entryTransition, replacements); } - else if( key == KEYNAME_EXIT_TRANSITION ) + else if(key == KEYNAME_EXIT_TRANSITION) { - RecordTransitionData( keyValue, style->exitTransition, replacements ); + RecordTransitionData(keyValue, style->exitTransition, replacements); } - else if( key == KEYNAME_TRANSITIONS ) + else if(key == KEYNAME_TRANSITIONS) { - RecordTransitions( keyValue, style->transitions, replacements ); + RecordTransitions(keyValue, style->transitions, replacements); } - else if( key == KEYNAME_TYPE || - key == KEYNAME_ACTORS || - key == KEYNAME_SIGNALS || - key == KEYNAME_STYLES || - key == KEYNAME_MAPPINGS || - key == KEYNAME_INHERIT ) + else if(key == KEYNAME_TYPE || + key == KEYNAME_ACTORS || + key == KEYNAME_SIGNALS || + key == KEYNAME_STYLES || + key == KEYNAME_MAPPINGS || + key == KEYNAME_INHERIT) { continue; } @@ -1279,16 +1273,16 @@ void Builder::RecordStyle( StylePtr style, { Property::Index index; Property::Value value; - if( MapToTargetProperty( handle, key, keyValue.second, replacements, index, value ) ) + if(MapToTargetProperty(handle, key, keyValue.second, replacements, index, value)) { - Property::Value* existingValuePtr = style->properties.Find( index ); - if( existingValuePtr != NULL ) + Property::Value* existingValuePtr = style->properties.Find(index); + if(existingValuePtr != NULL) { *existingValuePtr = value; // Overwrite existing property. } else { - style->properties.Add( index, value ); + style->properties.Add(index, value); } } } @@ -1297,108 +1291,104 @@ void Builder::RecordStyle( StylePtr style, void Builder::RecordTransitions( const TreeNode::KeyNodePair& keyValue, - Property::Array& value, - const Replacement& replacements ) + Property::Array& value, + const Replacement& replacements) { //@todo add new transitions to style.transitions // override existing transitions. A transition matches on target & property name const TreeNode& node = keyValue.second; - if( node.GetType() == TreeNode::ARRAY ) + if(node.GetType() == TreeNode::ARRAY) { Dali::Property::Value property(Property::ARRAY); - if( DeterminePropertyFromNode( node, Property::ARRAY, property, replacements ) ) + if(DeterminePropertyFromNode(node, Property::ARRAY, property, replacements)) { value = *property.GetArray(); } } - else if( node.GetType() == TreeNode::OBJECT ) + else if(node.GetType() == TreeNode::OBJECT) { Dali::Property::Value property(Property::MAP); - if( DeterminePropertyFromNode( node, Property::MAP, property, replacements ) ) + if(DeterminePropertyFromNode(node, Property::MAP, property, replacements)) { Property::Array propertyArray; - propertyArray.Add( property ); + propertyArray.Add(property); value = propertyArray; } } else { - DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first ); + DALI_LOG_WARNING("RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first); } } void Builder::RecordTransitionData( const TreeNode::KeyNodePair& keyValue, - Toolkit::TransitionData& transitionData, - const Replacement& replacements ) + Toolkit::TransitionData& transitionData, + const Replacement& replacements) { const TreeNode& node = keyValue.second; - if( node.GetType() == TreeNode::ARRAY ) + if(node.GetType() == TreeNode::ARRAY) { Dali::Property::Value property(Property::ARRAY); - if( DeterminePropertyFromNode( keyValue.second, Property::ARRAY, property, replacements ) ) + if(DeterminePropertyFromNode(keyValue.second, Property::ARRAY, property, replacements)) { - transitionData = Toolkit::TransitionData::New( *property.GetArray() ); + transitionData = Toolkit::TransitionData::New(*property.GetArray()); } } - else if( node.GetType() == TreeNode::OBJECT ) + else if(node.GetType() == TreeNode::OBJECT) { Dali::Property::Value property(Property::MAP); - if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) ) + if(DeterminePropertyFromNode(keyValue.second, Property::MAP, property, replacements)) { - transitionData = Toolkit::TransitionData::New( *property.GetMap() ); + transitionData = Toolkit::TransitionData::New(*property.GetMap()); } } } - // Set properties from node on handle. -void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node, - Dali::Handle& handle, const Replacement& constant ) +void Builder::ApplyProperties(const TreeNode& root, const TreeNode& node, Dali::Handle& handle, const Replacement& constant) { - SetProperties( node, handle, constant ); - ApplySignals( root, node, handle ); + SetProperties(node, handle, constant); + ApplySignals(root, node, handle); } -void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle ) +void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle) { Actor actor = Actor::DownCast(handle); - if( actor ) + if(actor) { // add signals - SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this ); - SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this ); + SetupSignalAction(mSlotDelegate.GetConnectionTracker(), root, node, actor, this); + SetupPropertyNotification(mSlotDelegate.GetConnectionTracker(), root, node, actor, this); } } - // Appling by style helper // use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node -void Builder::ApplyStylesByActor( const TreeNode& root, const TreeNode& node, - Dali::Handle& handle, const Replacement& constant ) +void Builder::ApplyStylesByActor(const TreeNode& root, const TreeNode& node, Dali::Handle& handle, const Replacement& constant) { - if( Dali::Actor actor = Dali::Actor::DownCast( handle ) ) + if(Dali::Actor actor = Dali::Actor::DownCast(handle)) { - if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) ) + if(const TreeNode* actors = node.GetChild(KEYNAME_ACTORS)) { // in a style the actor subtree properties referenced by actor name - for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter ) + for(TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter) { Dali::Actor foundActor; - if( (*iter).first ) + if((*iter).first) { - foundActor = actor.FindChildByName( (*iter).first ); + foundActor = actor.FindChildByName((*iter).first); } - if( !foundActor ) + if(!foundActor) { DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first); } else { DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first); - ApplyProperties( root, (*iter).second, foundActor, constant ); + ApplyProperties(root, (*iter).second, foundActor, constant); } } } @@ -1408,28 +1398,28 @@ void Builder::ApplyStylesByActor( const TreeNode& root, const TreeNode& node, /* * Sets the handle properties found in the tree node */ -void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant ) +void Builder::SetProperties(const TreeNode& node, Handle& handle, const Replacement& constant) { - if( handle ) + if(handle) { - for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter) { const TreeNode::KeyNodePair& keyChild = *iter; - std::string key( keyChild.first ); + std::string key(keyChild.first); // ignore special fields; - if( key == KEYNAME_TYPE || - key == KEYNAME_ACTORS || - key == KEYNAME_SIGNALS || - key == KEYNAME_STYLES || - key == KEYNAME_MAPPINGS || - key == KEYNAME_INHERIT || - key == KEYNAME_STATES || - key == KEYNAME_VISUALS || - key == KEYNAME_ENTRY_TRANSITION || - key == KEYNAME_EXIT_TRANSITION || - key == KEYNAME_TRANSITIONS ) + if(key == KEYNAME_TYPE || + key == KEYNAME_ACTORS || + key == KEYNAME_SIGNALS || + key == KEYNAME_STYLES || + key == KEYNAME_MAPPINGS || + key == KEYNAME_INHERIT || + key == KEYNAME_STATES || + key == KEYNAME_VISUALS || + key == KEYNAME_ENTRY_TRANSITION || + key == KEYNAME_EXIT_TRANSITION || + key == KEYNAME_TRANSITIONS) { continue; } @@ -1437,12 +1427,12 @@ void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replace Property::Index index; Property::Value value; - bool mapped = MapToTargetProperty( handle, key, keyChild.second, constant, index, value ); - if( mapped ) + bool mapped = MapToTargetProperty(handle, key, keyChild.second, constant, index, value); + if(mapped) { - DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() ); + DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str()); - handle.SetProperty( index, value ); + handle.SetProperty(index, value); } // Add custom properties @@ -1463,33 +1453,33 @@ bool Builder::MapToTargetProperty( const TreeNode& node, const Replacement& constant, Property::Index& index, - Property::Value& value ) + Property::Value& value) { bool mapped = false; - index = propertyObject.GetPropertyIndex( key ); - if( Property::INVALID_INDEX != index ) + index = propertyObject.GetPropertyIndex(key); + if(Property::INVALID_INDEX != index) { Property::Type type = propertyObject.GetPropertyType(index); // if node.value is a mapping, get the property value from the "mappings" table - if( node.GetType() == TreeNode::STRING ) + if(node.GetType() == TreeNode::STRING) { std::string mappingKey; - if( GetMappingKey( node.GetString(), mappingKey) ) + if(GetMappingKey(node.GetString(), mappingKey)) { - OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS ); - mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value ); + OptionalChild mappingRoot = IsChild(mParser.GetRoot(), KEYNAME_MAPPINGS); + mapped = GetPropertyMap(*mappingRoot, mappingKey.c_str(), type, value); } } - if( ! mapped ) + if(!mapped) { - mapped = DeterminePropertyFromNode( node, type, value, constant ); - if( ! mapped ) + mapped = DeterminePropertyFromNode(node, type, value, constant); + if(!mapped) { // Just determine the property from the node and if it's valid, let the property object handle it - DeterminePropertyFromNode( node, value, constant ); - mapped = ( value.GetType() != Property::NONE ); + DeterminePropertyFromNode(node, value, constant); + mapped = (value.GetType() != Property::NONE); } } } @@ -1500,35 +1490,35 @@ bool Builder::MapToTargetProperty( return mapped; } -bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value ) +bool Builder::GetPropertyMap(const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value) { KeyStack keyStack; - return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value ); + return RecursePropertyMap(mappingRoot, keyStack, theKey, propertyType, value); } -bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value ) +bool Builder::RecursePropertyMap(const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value) { - Replacement replacer( mReplacementMap ); - bool result = false; + Replacement replacer(mReplacementMap); + bool result = false; - keyStack.push_back( theKey ); + keyStack.push_back(theKey); - for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter) { - std::string aKey( (*iter).first ); - if( aKey.compare( theKey ) == 0 ) + std::string aKey((*iter).first); + if(aKey.compare(theKey) == 0) { - if( propertyType == Property::NONE ) + if(propertyType == Property::NONE) { - DeterminePropertyFromNode( (*iter).second, value, replacer ); + DeterminePropertyFromNode((*iter).second, value, replacer); result = true; } else { - result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer ); + result = DeterminePropertyFromNode((*iter).second, propertyType, value, replacer); } - if( result ) + if(result) { ConvertChildValue(mappingRoot, keyStack, value); } @@ -1540,39 +1530,39 @@ bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStac return result; } -bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child ) +bool Builder::ConvertChildValue(const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child) { bool result = false; - switch( child.GetType() ) + switch(child.GetType()) { case Property::STRING: { std::string value; - if( child.Get( value ) ) + if(child.Get(value)) { std::string key; - if( GetMappingKey( value, key ) ) + if(GetMappingKey(value, key)) { // Check key for cycles: - result=true; - for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter ) + result = true; + for(KeyStack::iterator iter = keyStack.begin(); iter != keyStack.end(); ++iter) { - if( key.compare(*iter) == 0 ) + if(key.compare(*iter) == 0) { // key is already in stack; stop. DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str()); - child = Property::Value(""); - result=false; + child = Property::Value(""); + result = false; break; } } - if( result ) + if(result) { // The following call will overwrite the child with the value // from the mapping. - RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child ); + RecursePropertyMap(mappingRoot, keyStack, key.c_str(), Property::NONE, child); result = true; } } @@ -1583,9 +1573,9 @@ bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack case Property::MAP: { Property::Map* map = child.GetMap(); - if( map ) + if(map) { - for( Property::Map::SizeType i=0; i < map->Count(); ++i ) + for(Property::Map::SizeType i = 0; i < map->Count(); ++i) { Property::Value& child = map->GetValue(i); ConvertChildValue(mappingRoot, keyStack, child); @@ -1597,9 +1587,9 @@ bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack case Property::ARRAY: { Property::Array* array = child.GetArray(); - if( array ) + if(array) { - for( Property::Array::SizeType i=0; i < array->Count(); ++i ) + for(Property::Array::SizeType i = 0; i < array->Count(); ++i) { Property::Value& child = array->GetElementAt(i); ConvertChildValue(mappingRoot, keyStack, child); @@ -1616,28 +1606,26 @@ bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack return result; } -void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant, - const std::string& childName, Property::AccessMode accessMode ) +void Builder::SetCustomProperties(const TreeNode& node, Handle& handle, const Replacement& constant, const std::string& childName, Property::AccessMode accessMode) { // Add custom properties - if( OptionalChild customPropertiesChild = IsChild(node, childName) ) + if(OptionalChild customPropertiesChild = IsChild(node, childName)) { - const TreeNode& customPropertiesNode = *customPropertiesChild; - const TreeConstIter endIter = customPropertiesNode.CEnd(); - for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter ) + const TreeNode& customPropertiesNode = *customPropertiesChild; + const TreeConstIter endIter = customPropertiesNode.CEnd(); + for(TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& keyChild = *iter; - std::string key( keyChild.first ); - Property::Value value; - DeterminePropertyFromNode( keyChild.second, value, constant ); + std::string key(keyChild.first); + Property::Value value; + DeterminePropertyFromNode(keyChild.second, value, constant); // Register/Set property. - handle.RegisterProperty( key, value, accessMode ); + handle.RegisterProperty(key, value, accessMode); } } } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/builder/builder-impl.h b/dali-toolkit/internal/builder/builder-impl.h index 049b3ce..59ff5de 100644 --- a/dali-toolkit/internal/builder/builder-impl.h +++ b/dali-toolkit/internal/builder/builder-impl.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_INTERNAL_BUILDER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,48 +19,45 @@ */ // EXTERNAL INCLUDES -#include -#include -#include -#include +#include #include +#include #include #include #include -#include +#include +#include +#include // INTERNAL INCLUDES -#include #include +#include #include #include // Warning messages usually displayed #define DALI_SCRIPT_WARNING(format, ...) \ - DALI_LOG_WARNING("Script:" format, ## __VA_ARGS__) + DALI_LOG_WARNING("Script:" format, ##__VA_ARGS__) // Info messages are usually debug build #define DALI_SCRIPT_INFO(format, ...) \ - DALI_LOG_INFO(Dali::Toolkit::Internal::gFilterScript, Debug::General, "Script:" format, ## __VA_ARGS__) + DALI_LOG_INFO(Dali::Toolkit::Internal::gFilterScript, Debug::General, "Script:" format, ##__VA_ARGS__) // Info Verbose need to be swiched on in gFilterScript filter constructor (by default set to General) #define DALI_SCRIPT_VERBOSE(format, ...) \ - DALI_LOG_INFO(Dali::Toolkit::Internal::gFilterScript, Debug::Verbose, "Script:" format, ## __VA_ARGS__) + DALI_LOG_INFO(Dali::Toolkit::Internal::gFilterScript, Debug::Verbose, "Script:" format, ##__VA_ARGS__) namespace Dali { - namespace Toolkit { - class TreeNode; +class TreeNode; } namespace Toolkit { - namespace Internal { - #if defined(DEBUG_ENABLED) extern Dali::Integration::Log::Filter* gFilterScript; #endif @@ -74,24 +71,23 @@ class Replacement; class Builder : public Dali::BaseObject { public: - Builder(); /** * @copydoc Toolkit::Builder::LoadFromString */ - void LoadFromString( const std::string &data, - Dali::Toolkit::Builder::UIFormat rep = Dali::Toolkit::Builder::JSON ); + void LoadFromString(const std::string& data, + Dali::Toolkit::Builder::UIFormat rep = Dali::Toolkit::Builder::JSON); /** * @copydoc Toolkit::Builder::AddConstants */ - void AddConstants( const Property::Map& map ); + void AddConstants(const Property::Map& map); /** * @copydoc Toolkit::Builder::AddConstant */ - void AddConstant( const std::string& key, const Property::Value& value ); + void AddConstant(const std::string& key, const Property::Value& value); /** * @copydoc Toolkit::Builder::GetConfigurations @@ -106,52 +102,52 @@ public: /** * @copydoc Toolkit::Builder::GetConstant */ - const Property::Value& GetConstant( const std::string& key ) const; + const Property::Value& GetConstant(const std::string& key) const; /** * @copydoc Toolkit::Builder::CreateAnimation( const std::string& animationName ); */ - Animation CreateAnimation( const std::string& animationName ); + Animation CreateAnimation(const std::string& animationName); /** * @copydoc Toolkit::Builder::CreateAnimation( const std::string& animationName, const Property::Map& map ); */ - Animation CreateAnimation( const std::string& animationName, const Property::Map& map ); + Animation CreateAnimation(const std::string& animationName, const Property::Map& map); /** * @copydoc Toolkit::Builder::CreateAnimation( const std::string&,Dali::Actor); */ - Animation CreateAnimation( const std::string& animationName, Dali::Actor sourceActor ); + Animation CreateAnimation(const std::string& animationName, Dali::Actor sourceActor); /** * @copydoc Toolkit::Builder::CreateAnimation( const std::string&,const Property::Map&, Dali::Actor); */ - Animation CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor ); + Animation CreateAnimation(const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor); /** * @copydoc Toolkit::Builder::Create( const std::string& templateName ); */ - BaseHandle Create( const std::string& templateName ); + BaseHandle Create(const std::string& templateName); /** * @copydoc Toolkit::Builder::Create( const std::string& templateName, const Property::Map& map ); */ - BaseHandle Create( const std::string& templateName, const Property::Map& map ); + BaseHandle Create(const std::string& templateName, const Property::Map& map); /** * @copydoc Toolkit::Builder::CreateFromJson( const std::string& json ); */ - BaseHandle CreateFromJson( const std::string& json ); + BaseHandle CreateFromJson(const std::string& json); /** * @copydoc Toolkit::Builder::ApplyFromJson( Handle& handle, const std::string& json ); */ - bool ApplyFromJson( Handle& handle, const std::string& json ); + bool ApplyFromJson(Handle& handle, const std::string& json); /** * @copydoc Toolkit::Builder::ApplyStyle */ - bool ApplyStyle( const std::string& styleName, Handle& handle ); + bool ApplyStyle(const std::string& styleName, Handle& handle); /** * Lookup the stylename in builder. If it's found in the parse tree, @@ -159,7 +155,7 @@ public: * @param[in] styleName The style name to search for * @return true if the stylename exists */ - bool LookupStyleName( const std::string& styleName ); + bool LookupStyleName(const std::string& styleName); /** * Lookup the stylename in the recorded Styles - if it exists, @@ -169,32 +165,32 @@ public: * @param[in] styleName The stylename to search for * @return A const pointer to the style object */ - const StylePtr GetStyle( const std::string& styleName ); + const StylePtr GetStyle(const std::string& styleName); /** * @copydoc Toolkit::Builder::AddActors */ - void AddActors( Actor toActor ); + void AddActors(Actor toActor); /** * @copydoc Toolkit::Builder::AddActors */ - void AddActors( const std::string §ionName, Actor toActor ); + void AddActors(const std::string& sectionName, Actor toActor); /** * @copydoc Toolkit::Builder::CreateRenderTask */ - void CreateRenderTask( const std::string &name ); + void CreateRenderTask(const std::string& name); /** * @copydoc Toolkit::Builder::GetPath */ - Path GetPath( const std::string &name ); + Path GetPath(const std::string& name); /** * @copydoc Toolkit::Builder::GetPathConstrainer */ - Dali::PathConstrainer GetPathConstrainer( const std::string& name ); + Dali::PathConstrainer GetPathConstrainer(const std::string& name); /* * Check if a given constrainer is of type PathConstrainer @@ -202,12 +198,12 @@ public: * @return True if constainer is of type PathConstrainer, False otherwise * */ - bool IsPathConstrainer( const std::string& name ); + bool IsPathConstrainer(const std::string& name); /** * @copydoc Toolkit::Builder::GetLinearConstrainer */ - Dali::LinearConstrainer GetLinearConstrainer( const std::string& name ); + Dali::LinearConstrainer GetLinearConstrainer(const std::string& name); /* * Check if a given constrainer is of type LinearConstrainer @@ -215,7 +211,7 @@ public: * @return True if constainer is of type LinearConstrainer, False otherwise * */ - bool IsLinearConstrainer( const std::string& name ); + bool IsLinearConstrainer(const std::string& name); /** * @copydoc Toolkit::Builder::QuitSignal @@ -227,17 +223,23 @@ public: */ void EmitQuitSignal(); - protected: - ~Builder() override; private: - typedef std::vector KeyStack; - typedef std::vector< TreeNode::KeyNodePair > MappingsLut; - typedef struct{ std::string name; Dali::LinearConstrainer linearConstrainer; } LinearConstrainerEntry; + typedef std::vector KeyStack; + typedef std::vector MappingsLut; + typedef struct + { + std::string name; + Dali::LinearConstrainer linearConstrainer; + } LinearConstrainerEntry; typedef std::vector LinearConstrainerLut; - typedef struct{ std::string name; Dali::PathConstrainer pathConstrainer; } PathConstrainerEntry; + typedef struct + { + std::string name; + Dali::PathConstrainer pathConstrainer; + } PathConstrainerEntry; typedef std::vector PathConstrainerLut; typedef std::map PathLut; @@ -248,77 +250,77 @@ private: // Undefined Builder& operator=(const Builder& rhs); - void LoadConstants( const TreeNode& root, Property::Map& intoMap ); - - void LoadConfiguration( const TreeNode& root, Property::Map& intoMap ); + void LoadConstants(const TreeNode& root, Property::Map& intoMap); - Animation CreateAnimation( const std::string& animationName, - const Replacement& replacement, - Dali::Actor sourceActor ); + void LoadConfiguration(const TreeNode& root, Property::Map& intoMap); - BaseHandle Create( const std::string& templateName, - const Replacement& constant ); + Animation CreateAnimation(const std::string& animationName, + const Replacement& replacement, + Dali::Actor sourceActor); - BaseHandle DoCreate( const TreeNode& root, - const TreeNode& node, - Actor parent, - const Replacement& replacements ); + BaseHandle Create(const std::string& templateName, + const Replacement& constant); - void SetupTask( RenderTask& task, - const Toolkit::TreeNode& node, - const Replacement& replacement ); + BaseHandle DoCreate(const TreeNode& root, + const TreeNode& node, + Actor parent, + const Replacement& replacements); - bool ApplyStyle( const std::string& styleName, - Handle& handle, - const Replacement& replacement); + void SetupTask(RenderTask& task, + const Toolkit::TreeNode& node, + const Replacement& replacement); - void ApplyAllStyleProperties( const TreeNode& root, - const TreeNode& node, - Dali::Handle& handle, - const Replacement& constant ); + bool ApplyStyle(const std::string& styleName, + Handle& handle, + const Replacement& replacement); - void RecordStyles( const char* styleName, - const TreeNode& node, - Dali::Handle& handle, - const Replacement& replacements ); + void ApplyAllStyleProperties(const TreeNode& root, + const TreeNode& node, + Dali::Handle& handle, + const Replacement& constant); - void RecordStyle( StylePtr style, + void RecordStyles(const char* styleName, const TreeNode& node, Dali::Handle& handle, - const Replacement& replacements ); + const Replacement& replacements); - void RecordTransitions( const TreeNode::KeyNodePair& keyValue, - Property::Array& transitions, - const Replacement& replacements ); + void RecordStyle(StylePtr style, + const TreeNode& node, + Dali::Handle& handle, + const Replacement& replacements); - void RecordTransitionData( const TreeNode::KeyNodePair& keyNode, - Toolkit::TransitionData& transitionData, - const Replacement& replacements ); + void RecordTransitions(const TreeNode::KeyNodePair& keyValue, + Property::Array& transitions, + const Replacement& replacements); - void ApplyProperties( const TreeNode& root, - const TreeNode& node, - Dali::Handle& handle, - const Replacement& constant ); + void RecordTransitionData(const TreeNode::KeyNodePair& keyNode, + Toolkit::TransitionData& transitionData, + const Replacement& replacements); - void ApplySignals( const TreeNode& root, - const TreeNode& node, - Dali::Handle& handle ); + void ApplyProperties(const TreeNode& root, + const TreeNode& node, + Dali::Handle& handle, + const Replacement& constant); - void ApplyStylesByActor( const TreeNode& root, - const TreeNode& node, - Dali::Handle& handle, - const Replacement& constant ); + void ApplySignals(const TreeNode& root, + const TreeNode& node, + Dali::Handle& handle); - void SetProperties( const TreeNode& node, - Handle& handle, - const Replacement& constant ); + void ApplyStylesByActor(const TreeNode& root, + const TreeNode& node, + Dali::Handle& handle, + const Replacement& constant); - bool MapToTargetProperty( Handle& propertyObject, - const std::string& key, - const TreeNode& node, - const Replacement& constant, - Property::Index& index, - Property::Value& value ); + void SetProperties(const TreeNode& node, + Handle& handle, + const Replacement& constant); + + bool MapToTargetProperty(Handle& propertyObject, + const std::string& key, + const TreeNode& node, + const Replacement& constant, + Property::Index& index, + Property::Value& value); /** * Find the key in the mapping table, if it's present, then generate @@ -330,16 +332,16 @@ private: * @param[in] propertyType The property type if known, or NONE * @param[in,out] value The string value to test and write back to. */ - bool GetPropertyMap( const TreeNode& mappingRoot, - const char* theKey, - Property::Type propertyType, - Property::Value& value ); + bool GetPropertyMap(const TreeNode& mappingRoot, + const char* theKey, + Property::Type propertyType, + Property::Value& value); - void SetCustomProperties( const TreeNode& node, - Handle& handle, - const Replacement& constant, - const std::string& childName, - Property::AccessMode accessMode ); + void SetCustomProperties(const TreeNode& node, + Handle& handle, + const Replacement& constant, + const std::string& childName, + Property::AccessMode accessMode); /** * Find the key in the mapping table, if it's present, then generate @@ -352,12 +354,11 @@ private: * @param[in] propertyType The property type if known, or NONE * @param[in,out] value The string value to test and write back to. */ - bool RecursePropertyMap( const TreeNode& mappingRoot, - KeyStack& keyStack, - const char* theKey, - Property::Type propertyType, - Property::Value& value ); - + bool RecursePropertyMap(const TreeNode& mappingRoot, + KeyStack& keyStack, + const char* theKey, + Property::Type propertyType, + Property::Value& value); /** * Tests if the value is a string delimited by <>. If it is, then it attempts to @@ -367,9 +368,9 @@ private: * @param[in,out] value The string value to test and write back to. * @return true if the value was converted, false otherwise. */ - bool ConvertChildValue( const TreeNode& mappingRoot, - KeyStack& keyStack, - Property::Value& value ); + bool ConvertChildValue(const TreeNode& mappingRoot, + KeyStack& keyStack, + Property::Value& value); private: Toolkit::JsonParser mParser; diff --git a/dali-toolkit/internal/builder/builder-set-property.cpp b/dali-toolkit/internal/builder/builder-set-property.cpp index 367c527..d00ca12 100644 --- a/dali-toolkit/internal/builder/builder-set-property.cpp +++ b/dali-toolkit/internal/builder/builder-set-property.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,26 +16,23 @@ */ // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES -#include #include -#include +#include #include +#include #include namespace Dali { - namespace Toolkit { - namespace Internal { - /** * A property value type can be forced when its unknown by a disambiguation convention in the json * ie "myarray": [1,2,3,4] ; would be a vector but @@ -45,61 +42,61 @@ namespace Internal * @param replacement The user overriding constant map * @return True if child contained a disambiguated string that could be converted. */ -bool Disambiguated(const TreeNode& child, +bool Disambiguated(const TreeNode& child, Dali::Property::Value& value, - const Replacement& replacement ) + const Replacement& replacement) { - OptionalString childType = IsString( IsChild(child, "typeCast") ); - OptionalChild childValue = IsChild(child, "value"); + OptionalString childType = IsString(IsChild(child, "typeCast")); + OptionalChild childValue = IsChild(child, "value"); - if( childType && childValue && (2 == child.Size()) ) + if(childType && childValue && (2 == child.Size())) { // this case allows disambiguation but normally the type is guessed // 2 == child.count() is an extra check as the user could have a user dictionary/map with // type-cast and value keys. If they do then a work around is to add a bogus key to not run this case. if(*childType == "boolean") { - return DeterminePropertyFromNode( *childValue, Dali::Property::BOOLEAN, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::BOOLEAN, value, replacement); } else if(*childType == "float") { - return DeterminePropertyFromNode( *childValue, Dali::Property::FLOAT, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::FLOAT, value, replacement); } else if(*childType == "vector2") { - return DeterminePropertyFromNode( *childValue, Dali::Property::VECTOR2, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::VECTOR2, value, replacement); } else if(*childType == "vector3") { - return DeterminePropertyFromNode( *childValue, Dali::Property::VECTOR3, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::VECTOR3, value, replacement); } else if(*childType == "vector4") { - return DeterminePropertyFromNode( *childValue, Dali::Property::VECTOR4, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::VECTOR4, value, replacement); } else if(*childType == "rotation") { - return DeterminePropertyFromNode( *childValue, Dali::Property::ROTATION, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::ROTATION, value, replacement); } else if(*childType == "rect") { - return DeterminePropertyFromNode( *childValue, Dali::Property::RECTANGLE, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::RECTANGLE, value, replacement); } else if(*childType == "string") { - return DeterminePropertyFromNode( *childValue, Dali::Property::STRING, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::STRING, value, replacement); } else if(*childType == "map") { - return DeterminePropertyFromNode( *childValue, Dali::Property::MAP, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::MAP, value, replacement); } else if(*childType == "array") { - return DeterminePropertyFromNode( *childValue, Dali::Property::ARRAY, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::ARRAY, value, replacement); } else if(*childType == "extents") { - return DeterminePropertyFromNode( *childValue, Dali::Property::EXTENTS, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::EXTENTS, value, replacement); } } @@ -107,15 +104,13 @@ bool Disambiguated(const TreeNode& child, return false; } - -bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Property::Value& value) +bool DeterminePropertyFromNode(const TreeNode& node, Property::Type type, Property::Value& value) { Replacement noReplacement; - return DeterminePropertyFromNode( node, type, value, noReplacement ); + return DeterminePropertyFromNode(node, type, value, noReplacement); } -bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Property::Value& value, - const Replacement& replacer ) +bool DeterminePropertyFromNode(const TreeNode& node, Property::Type type, Property::Value& value, const Replacement& replacer) { bool done = false; @@ -123,110 +118,110 @@ bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Prope { case Property::BOOLEAN: { - if( OptionalBoolean v = replacer.IsBoolean(node) ) + if(OptionalBoolean v = replacer.IsBoolean(node)) { value = *v; - done = true; + done = true; } break; } case Property::FLOAT: { - if( OptionalFloat v = replacer.IsFloat(node) ) + if(OptionalFloat v = replacer.IsFloat(node)) { value = *v; - done = true; + done = true; } break; } case Property::INTEGER: { - if( OptionalInteger v = replacer.IsInteger(node) ) + if(OptionalInteger v = replacer.IsInteger(node)) { value = *v; - done = true; + done = true; } break; } case Property::VECTOR2: { - if( OptionalVector2 v = replacer.IsVector2(node) ) + if(OptionalVector2 v = replacer.IsVector2(node)) { value = *v; - done = true; + done = true; } break; } case Property::VECTOR3: { - if( OptionalVector3 v = replacer.IsVector3(node) ) + if(OptionalVector3 v = replacer.IsVector3(node)) { value = *v; - done = true; + done = true; } break; } case Property::VECTOR4: { - if( OptionalVector4 v = replacer.IsVector4(node) ) + if(OptionalVector4 v = replacer.IsVector4(node)) { value = *v; - done = true; + done = true; } - else if( OptionalString s = replacer.IsString(node) ) + else if(OptionalString s = replacer.IsString(node)) { Vector4 color; - done = ConvertStringToColor( *s, color ); + done = ConvertStringToColor(*s, color); value = color; } - else if( TreeNode::OBJECT == node.GetType() ) + else if(TreeNode::OBJECT == node.GetType()) { // check for "r", "g" and "b" child color component nodes - OptionalInteger r = replacer.IsInteger( IsChild(node, "r") ); - OptionalInteger g = replacer.IsInteger( IsChild(node, "g") ); - OptionalInteger b = replacer.IsInteger( IsChild(node, "b") ); - if( r && g && b ) + OptionalInteger r = replacer.IsInteger(IsChild(node, "r")); + OptionalInteger g = replacer.IsInteger(IsChild(node, "g")); + OptionalInteger b = replacer.IsInteger(IsChild(node, "b")); + if(r && g && b) { - float red( (*r) * (1.0f/255.0f) ); - float green( (*g) * (1.0f/255.0f) ); - float blue( (*b) * (1.0f/255.0f) ); + float red((*r) * (1.0f / 255.0f)); + float green((*g) * (1.0f / 255.0f)); + float blue((*b) * (1.0f / 255.0f)); // check for optional "a" (alpha) node, default to fully opaque if it is not found. - float alpha( 1.0f ); - OptionalInteger a = replacer.IsInteger( IsChild(node, "a") ); - if( a ) + float alpha(1.0f); + OptionalInteger a = replacer.IsInteger(IsChild(node, "a")); + if(a) { - alpha = (*a) * (1.0f/255.0f); + alpha = (*a) * (1.0f / 255.0f); } - value = Vector4( red, green, blue, alpha ); - done = true; + value = Vector4(red, green, blue, alpha); + done = true; } } break; } case Property::MATRIX3: { - if( OptionalMatrix3 v = replacer.IsMatrix3(node) ) + if(OptionalMatrix3 v = replacer.IsMatrix3(node)) { value = *v; - done = true; + done = true; } break; } case Property::MATRIX: { - if( OptionalMatrix v = replacer.IsMatrix(node) ) + if(OptionalMatrix v = replacer.IsMatrix(node)) { value = *v; - done = true; + done = true; } break; } case Property::RECTANGLE: { - if( OptionalRect v = replacer.IsRect(node) ) + if(OptionalRect v = replacer.IsRect(node)) { value = *v; - done = true; + done = true; } break; } @@ -234,99 +229,99 @@ bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Prope { if(4 == node.Size()) { - if( OptionalVector4 ov = replacer.IsVector4(node) ) + if(OptionalVector4 ov = replacer.IsVector4(node)) { const Vector4& v = *ov; // angle, axis as per spec value = Quaternion(Radian(Degree(v[3])), - Vector3(v[0],v[1],v[2])); - done = true; + Vector3(v[0], v[1], v[2])); + done = true; } } else { // degrees Euler as per spec - if( OptionalVector3 v = replacer.IsVector3(node) ) + if(OptionalVector3 v = replacer.IsVector3(node)) { value = Quaternion(Radian(Degree((*v).x)), Radian(Degree((*v).y)), Radian(Degree((*v).z))); - done = true; + done = true; } } break; } case Property::STRING: { - if( OptionalString v = replacer.IsString(node) ) + if(OptionalString v = replacer.IsString(node)) { value = *v; - done = true; + done = true; } break; } case Property::ARRAY: { - if( replacer.IsArray( node, value ) ) + if(replacer.IsArray(node, value)) { done = true; } else if(node.Size()) { - value = Property::Value(Property::ARRAY); + value = Property::Value(Property::ARRAY); Property::Array* array = value.GetArray(); - unsigned int i = 0; + unsigned int i = 0; TreeNode::ConstIterator iter(node.CBegin()); - if( array ) + if(array) { - for( ; i < node.Size(); ++i, ++iter) + for(; i < node.Size(); ++i, ++iter) { Property::Value childValue; - DeterminePropertyFromNode( (*iter).second, childValue, replacer ); - array->PushBack( childValue ); + DeterminePropertyFromNode((*iter).second, childValue, replacer); + array->PushBack(childValue); } - done = ( array->Count() == node.Size() ); + done = (array->Count() == node.Size()); } } break; } case Property::MAP: { - if( replacer.IsMap( node, value ) ) + if(replacer.IsMap(node, value)) { done = true; } else if(node.Size()) { - value = Property::Value(Property::MAP); + value = Property::Value(Property::MAP); Property::Map* map = value.GetMap(); - unsigned int i = 0; + unsigned int i = 0; TreeNode::ConstIterator iter(node.CBegin()); - if( map ) + if(map) { - for( ; i < node.Size(); ++i, ++iter) + for(; i < node.Size(); ++i, ++iter) { Property::Value childValue; - DeterminePropertyFromNode( (*iter).second, childValue, replacer ); - map->Insert( (*iter).first, childValue ); + DeterminePropertyFromNode((*iter).second, childValue, replacer); + map->Insert((*iter).first, childValue); } - done = ( map->Count() == node.Size() ); + done = (map->Count() == node.Size()); } } break; } case Property::EXTENTS: { - if( OptionalExtents v = replacer.IsExtents(node) ) + if(OptionalExtents v = replacer.IsExtents(node)) { value = *v; - done = true; + done = true; } break; } @@ -339,22 +334,20 @@ bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Prope return done; } -void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value ) +void DeterminePropertyFromNode(const TreeNode& node, Property::Value& value) { Replacement replacer; - DeterminePropertyFromNode( node, value, replacer ); + DeterminePropertyFromNode(node, value, replacer); } -void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value, - const Replacement& replacer ) +void DeterminePropertyFromNode(const TreeNode& node, Property::Value& value, const Replacement& replacer) { - TreeNode::NodeType nodeType = node.GetType(); // Some values are ambiguous as we have no Property::Type but can be disambiguated in the JSON. // Currently Rotations and Rectangle must always be disambiguated when a type isn't available - if( !Disambiguated( node, value, replacer ) ) + if(!Disambiguated(node, value, replacer)) { bool done = false; @@ -365,75 +358,75 @@ void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value, // 4) If no match still; Create as array. // First handle nodes with children. - if( node.Size() ) + if(node.Size()) { // Handle array types. - if( nodeType == TreeNode::ARRAY ) + if(nodeType == TreeNode::ARRAY) { // our current heuristic for deciding an array is actually a vector and not say a map // is to check if the values are all floats bool allNumbers = true; - for( TreeConstIter iter = node.CBegin(); iter != node.CEnd(); ++iter ) + for(TreeConstIter iter = node.CBegin(); iter != node.CEnd(); ++iter) { - OptionalFloat checkFloat = IsFloat( ( *iter ).second ); - if( !checkFloat ) + OptionalFloat checkFloat = IsFloat((*iter).second); + if(!checkFloat) { allNumbers = false; break; } } - if( allNumbers ) + if(allNumbers) { // prefer finding vectors over presuming composite Property::Array... - if( OptionalMatrix v = IsMatrix( node ) ) + if(OptionalMatrix v = IsMatrix(node)) { value = *v; - done = true; + done = true; } - else if( OptionalMatrix3 v = IsMatrix3( node ) ) + else if(OptionalMatrix3 v = IsMatrix3(node)) { value = *v; - done = true; + done = true; } - else if( OptionalVector4 v = IsVector4( node ) ) + else if(OptionalVector4 v = IsVector4(node)) { value = *v; - done = true; + done = true; } - else if( OptionalVector3 v = IsVector3( node ) ) + else if(OptionalVector3 v = IsVector3(node)) { value = *v; - done = true; + done = true; } - else if( OptionalVector2 v = IsVector2( node ) ) + else if(OptionalVector2 v = IsVector2(node)) { value = *v; - done = true; + done = true; } - else if( 4 == node.Size() ) + else if(4 == node.Size()) { - if( OptionalVector4 v = IsVector4( node ) ) + if(OptionalVector4 v = IsVector4(node)) { value = *v; - done = true; + done = true; } } } } } // if node.size() - else if( ( nodeType != TreeNode::OBJECT ) && ( nodeType != TreeNode::ARRAY ) ) + else if((nodeType != TreeNode::OBJECT) && (nodeType != TreeNode::ARRAY)) { // no children so either one of bool, float, integer, string - OptionalBoolean aBool = replacer.IsBoolean( node ); - OptionalInteger anInt = replacer.IsInteger( node ); - OptionalFloat aFloat = replacer.IsFloat( node ); - OptionalString aString = replacer.IsString( node ); + OptionalBoolean aBool = replacer.IsBoolean(node); + OptionalInteger anInt = replacer.IsInteger(node); + OptionalFloat aFloat = replacer.IsFloat(node); + OptionalString aString = replacer.IsString(node); - if( aBool ) + if(aBool) { // a bool is also an int but here we presume int - if( anInt ) + if(anInt) { value = *anInt; } @@ -448,11 +441,11 @@ void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value, // {"value":"123"} // {"value":123} // This means we can't have a string with purely numeric content without disambiguation. - if( aFloat ) + if(aFloat) { value = *aFloat; } - else if( anInt ) + else if(anInt) { value = *anInt; } @@ -466,27 +459,27 @@ void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value, } // if( node.size() ) // If we have not created a value so far, attempt to create a Map or Array. - if( !done ) + if(!done) { // We are guaranteed to have at least one entry as this has been checked already. TreeConstIter containerIterator = node.CBegin(); - TreeConstIter containerEnd = node.CEnd(); + TreeConstIter containerEnd = node.CEnd(); // The TreeNode::OBJECT type implies a Property::Map. - if( nodeType == TreeNode::OBJECT ) + if(nodeType == TreeNode::OBJECT) { // We have a key, treat container as a Map. - value = Property::Value( Property::MAP ); + value = Property::Value(Property::MAP); Property::Map* map = value.GetMap(); - if( map ) + if(map) { // Iterate through container to add all entries. - for( ; containerIterator != containerEnd; ++containerIterator ) + for(; containerIterator != containerEnd; ++containerIterator) { Property::Value childValue; - DeterminePropertyFromNode( ( *containerIterator ).second, childValue, replacer ); - map->Insert( ( *containerIterator ).first, childValue ); + DeterminePropertyFromNode((*containerIterator).second, childValue, replacer); + map->Insert((*containerIterator).first, childValue); } } } @@ -495,25 +488,24 @@ void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value, // We don't have a key, treat container as an array. // Note: We don't check if the node type is array here, as we want to cope with unknowns by creating an array also. // This is the fall-back if no other types could be created. - value = Property::Value( Property::ARRAY ); + value = Property::Value(Property::ARRAY); Property::Array* array = value.GetArray(); - if( array ) + if(array) { // Iterate through container to add all entries. - for( ; containerIterator != containerEnd; ++containerIterator ) + for(; containerIterator != containerEnd; ++containerIterator) { Property::Value childValue; - DeterminePropertyFromNode( ( *containerIterator ).second, childValue, replacer ); - array->PushBack( childValue ); + DeterminePropertyFromNode((*containerIterator).second, childValue, replacer); + array->PushBack(childValue); } } } } // if !done - } // if !Disambiguated() + } // if !Disambiguated() } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/builder/builder-set-property.h b/dali-toolkit/internal/builder/builder-set-property.h index a9ae431..b5f523a 100644 --- a/dali-toolkit/internal/builder/builder-set-property.h +++ b/dali-toolkit/internal/builder/builder-set-property.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_INTERNAL_BUILDER_SET_PROPERTY_H /* - * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ namespace Toolkit { namespace Internal { - /** * Set a property value from a tree node. * This function determines the type of the property from the format of the string in the node. @@ -31,8 +30,8 @@ namespace Internal * @param node The node string to convert from * @param value The property value to set */ -void DeterminePropertyFromNode( const TreeNode& node, - Property::Value& value ); +void DeterminePropertyFromNode(const TreeNode& node, + Property::Value& value); /** * Set a property value from a tree node as DeterminePropertyFromNode() above @@ -42,9 +41,9 @@ void DeterminePropertyFromNode( const TreeNode& node, * @param value The property value to set * @param replacement The overriding replacement map (if any) */ -void DeterminePropertyFromNode( const TreeNode& node, - Property::Value& value, - const Replacement& replacement ); +void DeterminePropertyFromNode(const TreeNode& node, + Property::Value& value, + const Replacement& replacement); /** * Set a property value as the given type from a tree node. @@ -53,9 +52,9 @@ void DeterminePropertyFromNode( const TreeNode& node, * @param value The property value to set * @return true if the string could be converted to the correct type. */ -bool DeterminePropertyFromNode( const TreeNode& node, - Property::Type type, - Property::Value& value ); +bool DeterminePropertyFromNode(const TreeNode& node, + Property::Type type, + Property::Value& value); /** * Set a property value as the given type from a tree node as DeterminePropertyFromNode() above @@ -65,14 +64,13 @@ bool DeterminePropertyFromNode( const TreeNode& node, * @param replacement The overriding replacement map (if any) * @return true if the string could be converted to the correct type. */ -bool DeterminePropertyFromNode( const TreeNode& node, - Property::Type type, - Property::Value& value, - const Replacement& replacement ); - +bool DeterminePropertyFromNode(const TreeNode& node, + Property::Type type, + Property::Value& value, + const Replacement& replacement); -} // Internal namespace -} // Toolkit namespace -} // Dali namespace +} // namespace Internal +} // namespace Toolkit +} // namespace Dali #endif //DALI_TOOLKIT_INTERNAL_BUILDER_SET_PROPERTY_H diff --git a/dali-toolkit/internal/builder/builder-signals.cpp b/dali-toolkit/internal/builder/builder-signals.cpp index d38e1d4..c4af9d4 100644 --- a/dali-toolkit/internal/builder/builder-signals.cpp +++ b/dali-toolkit/internal/builder/builder-signals.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,18 @@ */ // EXTERNAL INCLUDES +#include #include #include -#include #include -#include +#include #include #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { @@ -35,11 +35,11 @@ namespace Toolkit { namespace Internal { -extern Animation CreateAnimation( const TreeNode& child, Dali::Toolkit::Internal::Builder* const builder ); -extern void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value ); -} -} -} +extern Animation CreateAnimation(const TreeNode& child, Dali::Toolkit::Internal::Builder* const builder); +extern void DeterminePropertyFromNode(const TreeNode& node, Property::Value& value); +} // namespace Internal +} // namespace Toolkit +} // namespace Dali namespace { @@ -52,9 +52,9 @@ using namespace Dali; // Action on child actor. The child is found by name struct ChildActorAction { - std::string actorName; - std::string actionName; - std::string childName; + std::string actorName; + std::string actionName; + std::string childName; Property::Map parameters; void operator()(void) @@ -80,8 +80,8 @@ struct ChildActorAction // Action to set a property struct PropertySetAction { - std::string actorName; - std::string propertyName; + std::string actorName; + std::string propertyName; Property::Value value; void operator()(void) @@ -92,15 +92,15 @@ struct PropertySetAction { Property::Index idx = actor.GetPropertyIndex(propertyName); - if( idx != Property::INVALID_INDEX ) + if(idx != Property::INVALID_INDEX) { - if( actor.GetPropertyType(idx) != value.GetType() ) + if(actor.GetPropertyType(idx) != value.GetType()) { DALI_SCRIPT_WARNING("Set property action has different type for property '%s'\n", propertyName.c_str()); } else { - actor.SetProperty( idx, value ); + actor.SetProperty(idx, value); } } else @@ -114,8 +114,8 @@ struct PropertySetAction // Generic action on a handle (Animation & Actor) struct GenericAction { - std::string actorName; - std::string actionName; + std::string actorName; + std::string actionName; Property::Map parameters; void operator()(void) @@ -125,7 +125,6 @@ struct GenericAction { actor.DoAction(actionName, parameters); } - }; }; @@ -142,12 +141,12 @@ struct QuitAction // Delay an animation play; ie wait as its not on stage yet struct DelayedAnimationPlay { - OptionalChild animNode; - Dali::IntrusivePtr builder; + OptionalChild animNode; + Dali::IntrusivePtr builder; void operator()(void) { - Animation anim = Toolkit::Internal::CreateAnimation(*animNode, builder.Get() ); + Animation anim = Toolkit::Internal::CreateAnimation(*animNode, builder.Get()); if(anim) { anim.Play(); @@ -158,16 +157,16 @@ struct DelayedAnimationPlay // Delay a pathConstrainer apply struct DelayedConstrainerApply { - std::string constrainerName; + std::string constrainerName; std::vector targetActorNames; std::vector sourceActorNames; std::vector targetPropertyNames; std::vector sourcePropertyNames; - std::vector ranges; - std::vector wrapRanges; + std::vector ranges; + std::vector wrapRanges; - Dali::IntrusivePtr builder; + Dali::IntrusivePtr builder; /* * Helper function to get the parameters to apply each constraint @@ -177,43 +176,43 @@ struct DelayedConstrainerApply * @param[out] sourceActor Source actor for the constraint * @param[out] sourcePropertyIndex Source property index for the constraint */ - bool GetApplyParameters( size_t i, - Actor& targetActor, Property::Index& targetPropertyIndex, - Actor& sourceActor, Property::Index& sourcePropertyIndex) + bool GetApplyParameters(size_t i, + Actor& targetActor, + Property::Index& targetPropertyIndex, + Actor& sourceActor, + Property::Index& sourcePropertyIndex) { - - targetActor = Stage::GetCurrent().GetRootLayer().FindChildByName(targetActorNames[i]); + targetActor = Stage::GetCurrent().GetRootLayer().FindChildByName(targetActorNames[i]); targetPropertyIndex = Property::INVALID_INDEX; if(targetActor) { targetPropertyIndex = targetActor.GetPropertyIndex(targetPropertyNames[i]); - if( targetPropertyIndex == Property::INVALID_INDEX ) + if(targetPropertyIndex == Property::INVALID_INDEX) { - DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", targetPropertyNames[i].c_str(), targetActorNames[i].c_str() ); + DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", targetPropertyNames[i].c_str(), targetActorNames[i].c_str()); return false; } } else { - DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str() ); + DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str()); return false; } - - sourceActor = Stage::GetCurrent().GetRootLayer().FindChildByName(sourceActorNames[i]); + sourceActor = Stage::GetCurrent().GetRootLayer().FindChildByName(sourceActorNames[i]); sourcePropertyIndex = Property::INVALID_INDEX; if(sourceActor) { sourcePropertyIndex = sourceActor.GetPropertyIndex(sourcePropertyNames[i]); - if( sourcePropertyIndex == Property::INVALID_INDEX ) + if(sourcePropertyIndex == Property::INVALID_INDEX) { - DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", sourcePropertyNames[i].c_str(), sourceActorNames[i].c_str() ); + DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", sourcePropertyNames[i].c_str(), sourceActorNames[i].c_str()); return false; } } else { - DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str() ); + DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str()); return false; } return true; @@ -221,24 +220,23 @@ struct DelayedConstrainerApply void operator()(void) { - Actor sourceActor, targetActor; + Actor sourceActor, targetActor; Property::Index targetPropertyIndex(Property::INVALID_INDEX); Property::Index sourcePropertyIndex(Property::INVALID_INDEX); - size_t actorCount( targetActorNames.size() ); - if( builder.Get()->IsPathConstrainer( constrainerName )) + size_t actorCount(targetActorNames.size()); + if(builder.Get()->IsPathConstrainer(constrainerName)) { PathConstrainer constrainer = builder.Get()->GetPathConstrainer(constrainerName); - if( constrainer ) + if(constrainer) { - for(size_t i(0); iIsLinearConstrainer( constrainerName ) ) + else if(builder.Get()->IsLinearConstrainer(constrainerName)) { - Dali::LinearConstrainer constrainer( builder.Get()->GetLinearConstrainer(constrainerName)); - if( constrainer ) + Dali::LinearConstrainer constrainer(builder.Get()->GetLinearConstrainer(constrainerName)); + if(constrainer) { - for(size_t i(0); i targetActorNames; - Dali::IntrusivePtr builder; + std::string constrainerName; + std::vector targetActorNames; + Dali::IntrusivePtr builder; void operator()(void) { - size_t actorCount( targetActorNames.size() ); - if( builder.Get()->IsPathConstrainer( constrainerName )) + size_t actorCount(targetActorNames.size()); + if(builder.Get()->IsPathConstrainer(constrainerName)) { PathConstrainer constrainer = builder.Get()->GetPathConstrainer(constrainerName); - if( constrainer ) + if(constrainer) { - for(size_t i(0); iIsLinearConstrainer( constrainerName )) + else if(builder.Get()->IsLinearConstrainer(constrainerName)) { LinearConstrainer constrainer = builder.Get()->GetLinearConstrainer(constrainerName); - if( constrainer ) + if(constrainer) { - for(size_t i(0); i( Dali::Toolkit::Internal::DeterminePropertyFromNode( child, ret ) ); + static_cast(Dali::Toolkit::Internal::DeterminePropertyFromNode(child, ret)); } else if(1 == nChildren) { // {"property": {"quaternion":[1,2,3,4]} } // {"property": {"angle":22, "axis": [1,2,3]} } - OptionalChild quaternion = IsChild(&child, "quaternion"); - OptionalChild axis = IsChild(&child, "axis"); - OptionalChild angle = IsChild(&child, "angle"); + OptionalChild quaternion = IsChild(&child, "quaternion"); + OptionalChild axis = IsChild(&child, "axis"); + OptionalChild angle = IsChild(&child, "angle"); if(quaternion) { @@ -382,14 +379,13 @@ Property::Value GetPropertyValue(const TreeNode &child) return ret; } - /* * Gets Parmeter list from child * params is be cleared before insertion */ void GetParameters(const TreeNode& child, Property::Map& params) { - if( OptionalChild c = IsChild(child, "parameters") ) + if(OptionalChild c = IsChild(child, "parameters")) { const TreeNode& node = *c; @@ -397,18 +393,21 @@ void GetParameters(const TreeNode& child, Property::Map& params) for(TreeNode::ConstIterator iter(node.CBegin()); iter != node.CEnd(); ++iter) { - params[ (*iter).first ] = GetPropertyValue( (*iter).second ); + params[(*iter).first] = GetPropertyValue((*iter).second); } } } // Shim for the property notifcation signal -template +template struct PropertyNotifcationSignalShim { T mFunctor; - PropertyNotifcationSignalShim(T& functor) : mFunctor(functor) {} + PropertyNotifcationSignalShim(T& functor) + : mFunctor(functor) + { + } void operator()(PropertyNotification& /* source */) { @@ -417,105 +416,115 @@ struct PropertyNotifcationSignalShim }; // Specializations for the different signal connection calls between actor & PropertyNotification -template -struct SignalConnector {}; +template +struct SignalConnector +{ +}; // Actor specialization -template <> -struct SignalConnector { - Actor& mActor; +template<> +struct SignalConnector +{ + Actor& mActor; ConnectionTracker* mTracker; const std::string& mName; SignalConnector(ConnectionTracker* tracker, Actor& actor, const std::string& name) - : mActor(actor), mTracker(tracker), mName(name) {} + : mActor(actor), + mTracker(tracker), + mName(name) + { + } - template + template void Connect(T& functor) { - mActor.ConnectSignal( mTracker, mName, functor); + mActor.ConnectSignal(mTracker, mName, functor); } }; // PropertyNotification specialization -template <> +template<> struct SignalConnector { PropertyNotification& mNotification; - ConnectionTracker* mTracker; + ConnectionTracker* mTracker; - SignalConnector(ConnectionTracker* tracker, PropertyNotification ¬ification) - : mNotification(notification), mTracker(tracker) {} + SignalConnector(ConnectionTracker* tracker, PropertyNotification& notification) + : mNotification(notification), + mTracker(tracker) + { + } - template + template void Connect(T& functor) { - mNotification.NotifySignal().Connect( mTracker, PropertyNotifcationSignalShim(functor) ); + mNotification.NotifySignal().Connect(mTracker, PropertyNotifcationSignalShim(functor)); } }; /** * Set an action functor on a signal */ -template -void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder, SignalConnector& connector) +template +void SetActionOnSignal(const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder, SignalConnector& connector) { - OptionalString childActorName(IsString( IsChild(&child, "childActor")) ); - OptionalString actorName(IsString( IsChild(&child, "actor")) ); - OptionalString propertyName(IsString( IsChild(&child, "property")) ); - OptionalChild valueChild( IsChild(&child, "value") ); + OptionalString childActorName(IsString(IsChild(&child, "childActor"))); + OptionalString actorName(IsString(IsChild(&child, "actor"))); + OptionalString propertyName(IsString(IsChild(&child, "property"))); + OptionalChild valueChild(IsChild(&child, "value")); - OptionalString actionName = IsString( IsChild(&child, "action") ); + OptionalString actionName = IsString(IsChild(&child, "action")); DALI_ASSERT_ALWAYS(actionName && "Signal must have an action"); if(childActorName) { ChildActorAction action; - action.actorName = *actorName; - action.childName = *childActorName; - action.actionName = *actionName; + action.actorName = *actorName; + action.childName = *childActorName; + action.actionName = *actionName; GetParameters(child, action.parameters); - connector.Connect( action ); + connector.Connect(action); } else if(actorName) { - if(propertyName && valueChild && ("set" == *actionName) ) + if(propertyName && valueChild && ("set" == *actionName)) { PropertySetAction action; - action.actorName = *actorName; - action.propertyName = *propertyName; + action.actorName = *actorName; + action.propertyName = *propertyName; // actor may not exist yet so we can't check the property type - Dali::Toolkit::Internal::DeterminePropertyFromNode( *valueChild, action.value ); - connector.Connect( action ); + Dali::Toolkit::Internal::DeterminePropertyFromNode(*valueChild, action.value); + connector.Connect(action); } else { GenericAction action; - action.actorName = *actorName; - action.actionName = *actionName; + action.actorName = *actorName; + action.actionName = *actionName; GetParameters(child, action.parameters); - connector.Connect( action ); + connector.Connect(action); } } else if("quit" == *actionName) { QuitAction action; action.builder = builder; - connector.Connect( action ); + connector.Connect(action); } else if("play" == *actionName) { - OptionalChild animations = IsChild( root, "animations" ); - OptionalString animationName = IsString( IsChild(child, "animation") ); - if( animations && animationName ) + OptionalChild animations = IsChild(root, "animations"); + OptionalString animationName = IsString(IsChild(child, "animation")); + if(animations && animationName) { - if( OptionalChild animNode = IsChild(*animations, *animationName) ) + if(OptionalChild animNode = IsChild(*animations, *animationName)) { DelayedAnimationPlay action; action.animNode = animNode; - action.builder = builder; + action.builder = builder; // @todo; put constants into the map - connector.Connect( action ); + connector.Connect(action); } else { @@ -527,32 +536,32 @@ void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, DALI_SCRIPT_WARNING("Cannot find animations section\n"); } } - else if("applyConstraint" == *actionName ) + else if("applyConstraint" == *actionName) { - OptionalString constrainerName = IsString( IsChild(child, "constrainer") ); - if( !constrainerName ) + OptionalString constrainerName = IsString(IsChild(child, "constrainer")); + if(!constrainerName) { DALI_SCRIPT_WARNING("Need to specify a constrainer\n"); } else { DelayedConstrainerApply action; - action.constrainerName = *constrainerName; - action.builder = builder; + action.constrainerName = *constrainerName; + action.builder = builder; OptionalChild propertiesNode = IsChild(child, "properties"); if(propertiesNode) { const TreeNode::ConstIterator endIter = (*propertiesNode).CEnd(); - for( TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter ) + for(TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& pKeyChild = *iter; - OptionalString sourceActorName(IsString(IsChild(pKeyChild.second, "source"))); + OptionalString sourceActorName(IsString(IsChild(pKeyChild.second, "source"))); if(!sourceActorName) { DALI_SCRIPT_WARNING("Need to specify source actor to apply the constraint\n"); continue; } - OptionalString sourcePropertyName( IsString( IsChild(pKeyChild.second, "sourceProperty" ) ) ); + OptionalString sourcePropertyName(IsString(IsChild(pKeyChild.second, "sourceProperty"))); if(!sourcePropertyName) { DALI_SCRIPT_WARNING("Need to specify source property to apply the constraint\n"); @@ -566,7 +575,7 @@ void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, continue; } - OptionalString targetPropertyName( IsString( IsChild(pKeyChild.second, "targetProperty" ) ) ); + OptionalString targetPropertyName(IsString(IsChild(pKeyChild.second, "targetProperty"))); if(!targetPropertyName) { DALI_SCRIPT_WARNING("Need to specify target property name to apply the constraint\n"); @@ -580,7 +589,7 @@ void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, continue; } - Vector2 wrap(-std::numeric_limits::max(), std::numeric_limits::max()); + Vector2 wrap(-std::numeric_limits::max(), std::numeric_limits::max()); OptionalVector2 wrapRange(IsVector2(IsChild(pKeyChild.second, "wrap"))); if(wrapRange) { @@ -598,27 +607,26 @@ void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, } } } - else if("removeConstraints" == *actionName ) + else if("removeConstraints" == *actionName) { - OptionalString constrainerName = IsString( IsChild(child, "constrainer") ); - if( !constrainerName ) + OptionalString constrainerName = IsString(IsChild(child, "constrainer")); + if(!constrainerName) { DALI_SCRIPT_WARNING("Need to specify a constrainer\n"); } else { - DelayedConstrainerRemove action; - action.constrainerName = *constrainerName; - action.builder = builder; + action.constrainerName = *constrainerName; + action.builder = builder; OptionalChild propertiesNode = IsChild(child, "properties"); if(propertiesNode) { const TreeNode::ConstIterator endIter = (*propertiesNode).CEnd(); - for( TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter ) + for(TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& pKeyChild = *iter; - OptionalString targetActorName(IsString(IsChild(pKeyChild.second, "target"))); + OptionalString targetActorName(IsString(IsChild(pKeyChild.second, "target"))); if(targetActorName) { action.targetActorNames.push_back(*targetActorName); @@ -637,28 +645,27 @@ void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, { // no named actor; presume self GenericAction action; - action.actorName = actor.GetProperty< std::string >( Dali::Actor::Property::NAME ); - action.actionName = *actionName; + action.actorName = actor.GetProperty(Dali::Actor::Property::NAME); + action.actionName = *actionName; GetParameters(child, action.parameters); - connector.Connect( action ); + connector.Connect(action); } } - /** * Get a notification condition argument0 as 'arg0' 'value' or 'min' */ -float GetConditionArg0(const TreeNode &child) +float GetConditionArg0(const TreeNode& child) { - OptionalFloat f = IsFloat( IsChild(child, "arg0") ); + OptionalFloat f = IsFloat(IsChild(child, "arg0")); // allowing some human preferable alternatives if(!f) { - f = IsFloat( IsChild(child, "value") ); + f = IsFloat(IsChild(child, "value")); } if(!f) { - f = IsFloat( IsChild(child, "min") ); + f = IsFloat(IsChild(child, "min")); } DALI_ASSERT_ALWAYS(f && "Notification condition for arg0 not specified"); @@ -669,13 +676,13 @@ float GetConditionArg0(const TreeNode &child) /** * Get a notification condition argument1 as 'arg1' or 'max' */ -float GetConditionArg1(const TreeNode &child) +float GetConditionArg1(const TreeNode& child) { - OptionalFloat f = IsFloat( IsChild(child, "arg1") ); + OptionalFloat f = IsFloat(IsChild(child, "arg1")); // allowing some human preferable alternatives if(!f) { - f = IsFloat( IsChild(child, "max") ); + f = IsFloat(IsChild(child, "max")); } DALI_ASSERT_ALWAYS(f && "Notification condition for arg1 not specified"); @@ -683,9 +690,7 @@ float GetConditionArg1(const TreeNode &child) return *f; } - - -}; // anon namespace +}; // namespace namespace Dali { @@ -693,28 +698,27 @@ namespace Toolkit { namespace Internal { - -Actor SetupSignalAction(const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder ); -Actor SetupPropertyNotification(const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder ); +Actor SetupSignalAction(const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); +Actor SetupPropertyNotification(const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); /** * Setup signals and actions on an actor */ -Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder ) +Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder) { DALI_ASSERT_ALWAYS(actor); if(OptionalChild signalsChild = IsChild(child, "signals")) { - const TreeNode& signalsNode = *signalsChild; - const TreeConstIter endIter = signalsNode.CEnd(); - for( TreeConstIter iter = signalsNode.CBegin(); endIter != iter; ++iter ) + const TreeNode& signalsNode = *signalsChild; + const TreeConstIter endIter = signalsNode.CEnd(); + for(TreeConstIter iter = signalsNode.CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& key_child = *iter; - DALI_SCRIPT_INFO(" Creating Signal for: %s\n", actor.GetProperty< std::string >( Dali::Actor::Property::NAME ).c_str()); + DALI_SCRIPT_INFO(" Creating Signal for: %s\n", actor.GetProperty(Dali::Actor::Property::NAME).c_str()); - OptionalString name( IsString( IsChild( key_child.second, "name")) ); + OptionalString name(IsString(IsChild(key_child.second, "name"))); DALI_ASSERT_ALWAYS(name && "Signal must have a name"); SignalConnector connector(tracker, actor, *name); @@ -728,61 +732,66 @@ Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const /** * Setup Property notifications for an actor */ -Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder ) +Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder) { DALI_ASSERT_ALWAYS(actor); - if(OptionalChild notificationsChild = IsChild(child,"notifications")) + if(OptionalChild notificationsChild = IsChild(child, "notifications")) { - const TreeNode& notificationsNode = *notificationsChild; - const TreeNode::ConstIterator endIter = notificationsNode.CEnd(); - for( TreeNode::ConstIterator iter = notificationsNode.CBegin(); endIter != iter; ++iter ) + const TreeNode& notificationsNode = *notificationsChild; + const TreeNode::ConstIterator endIter = notificationsNode.CEnd(); + for(TreeNode::ConstIterator iter = notificationsNode.CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& key_child = *iter; - OptionalString prop(IsString( IsChild(key_child.second, "property")) ); + OptionalString prop(IsString(IsChild(key_child.second, "property"))); DALI_ASSERT_ALWAYS(prop && "Notification signal must specify a property"); Property::Index prop_index = actor.GetPropertyIndex(*prop); DALI_ASSERT_ALWAYS(prop_index != Property::INVALID_INDEX && "Notification signal specifies an unknown property"); - OptionalString cond(IsString( IsChild(key_child.second, "condition"))); + OptionalString cond(IsString(IsChild(key_child.second, "condition"))); DALI_ASSERT_ALWAYS(cond && "Notification signal must specify a condition"); if("False" == *cond) { - PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop), - LessThanCondition(1.f) ); + PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop), + LessThanCondition(1.f)); + SignalConnector connector(tracker, notification); SetActionOnSignal(root, key_child.second, actor, builder, connector); } else if("LessThan" == *cond) { - PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop), - LessThanCondition(GetConditionArg0(key_child.second)) ); + PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop), + LessThanCondition(GetConditionArg0(key_child.second))); + SignalConnector connector(tracker, notification); SetActionOnSignal(root, key_child.second, actor, builder, connector); } else if("GreaterThan" == *cond) { - PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop), - GreaterThanCondition(GetConditionArg0(key_child.second)) ); + PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop), + GreaterThanCondition(GetConditionArg0(key_child.second))); + SignalConnector connector(tracker, notification); SetActionOnSignal(root, key_child.second, actor, builder, connector); } else if("Inside" == *cond) { - PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop), - InsideCondition(GetConditionArg0(key_child.second), - GetConditionArg1(key_child.second)) ); + PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop), + InsideCondition(GetConditionArg0(key_child.second), + GetConditionArg1(key_child.second))); + SignalConnector connector(tracker, notification); SetActionOnSignal(root, key_child.second, actor, builder, connector); } else if("Outside" == *cond) { - PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop), - OutsideCondition(GetConditionArg0(key_child.second), - GetConditionArg1(key_child.second)) ); + PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop), + OutsideCondition(GetConditionArg0(key_child.second), + GetConditionArg1(key_child.second))); + SignalConnector connector(tracker, notification); SetActionOnSignal(root, key_child.second, actor, builder, connector); } @@ -797,7 +806,6 @@ Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root } // AddPropertyNotification - } // namespace Internal } // namespace Toolkit } // namespace Dali diff --git a/dali-toolkit/internal/builder/dictionary.h b/dali-toolkit/internal/builder/dictionary.h index a3036d9..b570c04 100644 --- a/dali-toolkit/internal/builder/dictionary.h +++ b/dali-toolkit/internal/builder/dictionary.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_INTERNAL_BUILDER_DICTIONARY_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,6 @@ namespace Toolkit { namespace Internal { - /** * The Dictionary template class enables a means of storing key-value * pairs where the keys are strings and the value can be a complex @@ -41,7 +40,7 @@ namespace Internal using DictionaryKeys = std::vector; -inline void Merge( DictionaryKeys& toDict, const DictionaryKeys& fromDict ) +inline void Merge(DictionaryKeys& toDict, const DictionaryKeys& fromDict) { for(const auto& element : fromDict) { @@ -53,7 +52,6 @@ inline void Merge( DictionaryKeys& toDict, const DictionaryKeys& fromDict ) } } - template class Dictionary { @@ -64,7 +62,7 @@ private: struct Element { std::string key; - EntryType entry; + EntryType entry; Element(std::string name, EntryType entry) : key(std::move(name)), entry(std::move(entry)) @@ -82,9 +80,9 @@ private: auto FindElement(std::string_view key) { - return std::find_if(container.begin(), container.end(), [key](auto& e){ - return bool(key == e.key); - }); + return std::find_if(container.begin(), container.end(), [key](auto& e) { + return bool(key == e.key); + }); } public: @@ -138,12 +136,12 @@ public: if(iter != End()) { - container.erase( iter ); + container.erase(iter); } } } - void Merge( const Dictionary& dictionary ) + void Merge(const Dictionary& dictionary) { for(const auto& element : dictionary.container) { @@ -166,7 +164,7 @@ public: */ const EntryType* FindConst(std::string_view key) const { - if( ! key.empty() ) + if(!key.empty()) { auto iter = FindElementCaseInsensitive(key); @@ -184,7 +182,7 @@ public: */ EntryType* Find(std::string_view key) const { - if( ! key.empty() ) + if(!key.empty()) { auto iter = FindElementCaseInsensitive(key); @@ -209,7 +207,7 @@ public: return container.cend(); } - void GetKeys( DictionaryKeys& keys ) const + void GetKeys(DictionaryKeys& keys) const { keys.clear(); for(const auto& element : container) @@ -224,10 +222,8 @@ public: } }; - - -}//Internal -}//Toolkit -}//Dali +} // namespace Internal +} // namespace Toolkit +} // namespace Dali #endif // DALI_TOOLKIT_INTERNAL_BUILDER_DICTIONARY_H diff --git a/dali-toolkit/internal/builder/json-parser-impl.cpp b/dali-toolkit/internal/builder/json-parser-impl.cpp index fdec738..d1fe2ae 100644 --- a/dali-toolkit/internal/builder/json-parser-impl.cpp +++ b/dali-toolkit/internal/builder/json-parser-impl.cpp @@ -22,59 +22,54 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - const char ERROR_DESCRIPTION_NONE[] = "No Error"; -template +template inline IteratorType Advance(IteratorType& iter, EndIteratorType& end, int n) { - for(int i =0; i < n; ++i) + for(int i = 0; i < n; ++i) { ++iter; } return iter; } -} // anon namespace - +} // namespace JsonParser::JsonParser() - : mRoot(NULL), - mErrorDescription(ERROR_DESCRIPTION_NONE), - mErrorPosition(0), - mErrorLine(0), - mErrorColumn(0), - mNumberOfChars(0), - mNumberOfNodes(0) +: mRoot(NULL), + mErrorDescription(ERROR_DESCRIPTION_NONE), + mErrorPosition(0), + mErrorLine(0), + mErrorColumn(0), + mNumberOfChars(0), + mNumberOfNodes(0) { } JsonParser::JsonParser(const TreeNode& tree) - : mRoot(NULL), - mErrorDescription(ERROR_DESCRIPTION_NONE), - mErrorPosition(0), - mErrorLine(0), - mErrorColumn(0), - mNumberOfChars(0), - mNumberOfNodes(0) +: mRoot(NULL), + mErrorDescription(ERROR_DESCRIPTION_NONE), + mErrorPosition(0), + mErrorLine(0), + mErrorColumn(0), + mNumberOfChars(0), + mNumberOfNodes(0) { - mRoot = TreeNodeManipulator::Copy( tree, mNumberOfNodes, mNumberOfChars ); + mRoot = TreeNodeManipulator::Copy(tree, mNumberOfNodes, mNumberOfChars); - mSources.push_back( VectorChar( (sizeof(char) * mNumberOfChars) ) ); + mSources.push_back(VectorChar((sizeof(char) * mNumberOfChars))); VectorChar& buffer = mSources.back(); @@ -98,40 +93,39 @@ JsonParser::~JsonParser() bool JsonParser::Parse(const std::string& source) { - mSources.push_back( VectorChar(source.begin(), source.end()) ); + mSources.push_back(VectorChar(source.begin(), source.end())); JsonParserState parserState(mRoot); - if( parserState.ParseJson(mSources.back()) ) + if(parserState.ParseJson(mSources.back())) { mRoot = parserState.GetRoot(); mNumberOfChars += parserState.GetParsedStringSize(); mNumberOfNodes += parserState.GetCreatedNodeCount(); - mErrorDescription = ERROR_DESCRIPTION_NONE; - mErrorPosition = 0; - mErrorLine = 0; - mErrorColumn = 0; + mErrorDescription = ERROR_DESCRIPTION_NONE; + mErrorPosition = 0; + mErrorLine = 0; + mErrorColumn = 0; } else { mRoot = NULL; - mErrorDescription = parserState.GetErrorDescription(); + mErrorDescription = parserState.GetErrorDescription(); if(NULL == mErrorDescription) { mErrorDescription = ERROR_DESCRIPTION_NONE; } - mErrorPosition = parserState.GetErrorPosition(); - mErrorLine = parserState.GetErrorLineNumber(); - mErrorColumn = parserState.GetErrorColumn(); + mErrorPosition = parserState.GetErrorPosition(); + mErrorLine = parserState.GetErrorLineNumber(); + mErrorColumn = parserState.GetErrorColumn(); } return mRoot != NULL; } - const TreeNode* JsonParser::GetRoot() const { return mRoot; @@ -164,7 +158,7 @@ int JsonParser::GetErrorColumn() const void JsonParser::Pack(void) { - mSources.push_back( VectorChar( (sizeof(char) * mNumberOfChars) ) ); + mSources.push_back(VectorChar((sizeof(char) * mNumberOfChars))); VectorChar& buffer = mSources.back(); @@ -174,7 +168,7 @@ void JsonParser::Pack(void) modify.MoveStrings(start, buffer.end()); - mSources.erase( mSources.begin(), --mSources.end() ); + mSources.erase(mSources.begin(), --mSources.end()); } void JsonParser::Write(std::ostream& output, int indent) const @@ -183,7 +177,6 @@ void JsonParser::Write(std::ostream& output, int indent) const modify.Write(output, indent); } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/builder/json-parser-impl.h b/dali-toolkit/internal/builder/json-parser-impl.h index f635a82..58c2ce0 100644 --- a/dali-toolkit/internal/builder/json-parser-impl.h +++ b/dali-toolkit/internal/builder/json-parser-impl.h @@ -2,7 +2,7 @@ #define DALI_JSON_PARSER_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,10 @@ */ // EXTERNAL INCLUDES -#include -#include #include #include +#include +#include // INTERNAL INCLUDES #include @@ -32,13 +32,10 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - /* * Parses JSON */ @@ -105,45 +102,42 @@ public: void Write(std::ostream& output, int indent) const; private: - typedef std::vector VectorChar; + typedef std::vector VectorChar; typedef VectorChar::iterator VectorCharIter; - typedef std::list SourceContainer; + typedef std::list SourceContainer; typedef std::list::iterator SourceContainerIter; - JsonParser(JsonParser &); + JsonParser(JsonParser&); JsonParser& operator=(const JsonParser&); - SourceContainer mSources; ///< List of strings from Parse() merge operations - - TreeNode* mRoot; ///< Tree root + SourceContainer mSources; ///< List of strings from Parse() merge operations - const char *mErrorDescription; ///< Last parse error description - int mErrorPosition; ///< Last parse error position - int mErrorLine; ///< Last parse error line - int mErrorColumn; ///< Last parse error column + TreeNode* mRoot; ///< Tree root - int mNumberOfChars; ///< The size of string data for all nodes - int mNumberOfNodes; ///< Node count + const char* mErrorDescription; ///< Last parse error description + int mErrorPosition; ///< Last parse error position + int mErrorLine; ///< Last parse error line + int mErrorColumn; ///< Last parse error column + int mNumberOfChars; ///< The size of string data for all nodes + int mNumberOfNodes; ///< Node count }; } // namespace Internal - inline const Internal::JsonParser& GetImplementation(const Toolkit::JsonParser& parser) { - DALI_ASSERT_ALWAYS( parser && "JsonParser handle is empty" ); + DALI_ASSERT_ALWAYS(parser && "JsonParser handle is empty"); const BaseObject& handle = parser.GetBaseObject(); return static_cast(handle); } - inline Internal::JsonParser& GetImplementation(Toolkit::JsonParser& parser) { - DALI_ASSERT_ALWAYS( parser && "JsonParser handle is empty" ); + DALI_ASSERT_ALWAYS(parser && "JsonParser handle is empty"); BaseObject& handle = parser.GetBaseObject(); @@ -154,5 +148,4 @@ inline Internal::JsonParser& GetImplementation(Toolkit::JsonParser& parser) } // namespace Dali - #endif // DALI_JSON_PARSER_IMPL_H diff --git a/dali-toolkit/internal/builder/json-parser-state.cpp b/dali-toolkit/internal/builder/json-parser-state.cpp index 40ec632..3262a81 100644 --- a/dali-toolkit/internal/builder/json-parser-state.cpp +++ b/dali-toolkit/internal/builder/json-parser-state.cpp @@ -19,21 +19,17 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - // true if character represent a digit inline bool IsDigit(char c) { @@ -41,30 +37,30 @@ inline bool IsDigit(char c) } // convert string to integer -bool StringToInteger(const char *first, const char *last, int& out) +bool StringToInteger(const char* first, const char* last, int& out) { int sign = 1; - if (first != last) + if(first != last) { - if (*first == '-') + if(*first == '-') { sign = -1; ++first; } - else if (*first == '+') + else if(*first == '+') { ++first; } } // json error for int starting with zero - if( 0 == (*first - '0') && (first+1 != last)) + if(0 == (*first - '0') && (first + 1 != last)) { return false; } int result = 0; - for (; first != last && IsDigit(*first); ++first) + for(; first != last && IsDigit(*first); ++first) { result = 10 * result + (*first - '0'); } @@ -81,21 +77,21 @@ bool StringToInteger(const char *first, const char *last, int& out) } // convert hexadecimal string to unsigned integer -bool HexStringToUnsignedInteger(const char *first, const char *last, unsigned int& out) +bool HexStringToUnsignedInteger(const char* first, const char* last, unsigned int& out) { unsigned int result = 0; - for (; first != last; ++first) + for(; first != last; ++first) { int digit; - if (IsDigit(*first)) + if(IsDigit(*first)) { digit = *first - '0'; } - else if (*first >= 'a' && *first <= 'f') + else if(*first >= 'a' && *first <= 'f') { digit = *first - 'a' + 10; } - else if (*first >= 'A' && *first <= 'F') + else if(*first >= 'A' && *first <= 'F') { digit = *first - 'A' + 10; } @@ -122,14 +118,14 @@ bool StringToFloat(const char* first, const char* last, float& out) { // sign float sign = 1; - if (first != last) + if(first != last) { - if (*first == '-') + if(*first == '-') { sign = -1; ++first; } - else if (*first == '+') + else if(*first == '+') { ++first; } @@ -137,18 +133,18 @@ bool StringToFloat(const char* first, const char* last, float& out) // integer part float result = 0; - for (; first != last && IsDigit(*first); ++first) + for(; first != last && IsDigit(*first); ++first) { result = 10 * result + (*first - '0'); } // fraction part - if (first != last && *first == '.') + if(first != last && *first == '.') { ++first; float inv_base = 0.1f; - for (; first != last && IsDigit(*first); ++first) + for(; first != last && IsDigit(*first); ++first) { result += (*first - '0') * inv_base; inv_base *= 0.1f; @@ -160,17 +156,17 @@ bool StringToFloat(const char* first, const char* last, float& out) // exponent bool exponent_negative = false; - int exponent = 0; - if (first != last && (*first == 'e' || *first == 'E')) + int exponent = 0; + if(first != last && (*first == 'e' || *first == 'E')) { ++first; - if (*first == '-') + if(*first == '-') { exponent_negative = true; ++first; } - else if (*first == '+') + else if(*first == '+') { ++first; } @@ -180,21 +176,21 @@ bool StringToFloat(const char* first, const char* last, float& out) return false; } - for (; first != last && IsDigit(*first); ++first) + for(; first != last && IsDigit(*first); ++first) { exponent = 10 * exponent + (*first - '0'); } } - if (exponent) + if(exponent) { float power_of_ten = 10; - for (; exponent > 1; exponent--) + for(; exponent > 1; exponent--) { power_of_ten *= 10; } - if (exponent_negative) + if(exponent_negative) { result /= power_of_ten; } @@ -216,11 +212,10 @@ bool StringToFloat(const char* first, const char* last, float& out) } } - bool IsNumber(char c) { bool ret = false; - switch( c ) + switch(c) { case '0': case '1': @@ -244,14 +239,19 @@ bool IsNumber(char c) return ret; } -} // anon namespace - +} // namespace JsonParserState::JsonParserState(TreeNode* _root) - : mRoot(_root), mCurrent(_root), - mErrorDescription(nullptr), mErrorNewLine(0), mErrorColumn(0), mErrorPosition(0), - mNumberOfParsedChars(0), mNumberOfCreatedNodes(0), mFirstParse(false), - mState(STATE_START) +: mRoot(_root), + mCurrent(_root), + mErrorDescription(nullptr), + mErrorNewLine(0), + mErrorColumn(0), + mErrorPosition(0), + mNumberOfParsedChars(0), + mNumberOfCreatedNodes(0), + mFirstParse(false), + mState(STATE_START) { if(_root == nullptr) { @@ -281,7 +281,6 @@ TreeNode* JsonParserState::CreateNewNode(const char* name, TreeNode::NodeType ty ++mNumberOfCreatedNodes; return node; - } TreeNode* JsonParserState::NewNode(const char* name, TreeNode::NodeType type) @@ -299,7 +298,7 @@ TreeNode* JsonParserState::NewNode(const char* name, TreeNode::NodeType type) if(name) { const TreeNode* found = mCurrent.GetChild(name); - if( nullptr != found ) + if(nullptr != found) { node = const_cast(found); } @@ -307,7 +306,7 @@ TreeNode* JsonParserState::NewNode(const char* name, TreeNode::NodeType type) else { // if root node - if( mCurrent.GetParent() == nullptr ) + if(mCurrent.GetParent() == nullptr) { node = mRoot; } @@ -356,7 +355,7 @@ bool JsonParserState::ParseWhiteSpace() bool c_comment = false; bool cpp_comment = false; - if( mIter == mEnd ) + if(mIter == mEnd) { return true; } @@ -372,7 +371,7 @@ bool JsonParserState::ParseWhiteSpace() NewLine(); } - if( AtLeast(2) ) + if(AtLeast(2)) { nextChar = mIter[1]; } @@ -381,43 +380,43 @@ bool JsonParserState::ParseWhiteSpace() nextChar = 0; } - if( cpp_comment ) + if(cpp_comment) { - if( '\n' == c ) + if('\n' == c) { cpp_comment = false; Advance(1); continue; // rather than carry on as comments may be back to back } } - else if( !c_comment && (c == '/' && nextChar == '/') ) + else if(!c_comment && (c == '/' && nextChar == '/')) { cpp_comment = true; } - if( c_comment ) + if(c_comment) { - if( c == '*' && nextChar == '/' ) + if(c == '*' && nextChar == '/') { c_comment = false; Advance(2); continue; } } - else if( !cpp_comment && (c == '/' && nextChar == '*') ) + else if(!cpp_comment && (c == '/' && nextChar == '*')) { c_comment = true; } - if( ! (c_comment || cpp_comment) ) + if(!(c_comment || cpp_comment)) { - if( ! (c == '\x20' || c == '\x9' || c == '\xD' || c == '\xA' ) ) + if(!(c == '\x20' || c == '\x9' || c == '\xD' || c == '\xA')) { break; } } - if( AdvanceEnded(1) ) + if(AdvanceEnded(1)) { break; } @@ -429,9 +428,9 @@ bool JsonParserState::ParseWhiteSpace() bool JsonParserState::ParseSymbol(const std::string& symbol) { - if( AtLeast( symbol.size() ) ) + if(AtLeast(symbol.size())) { - for(int i = 0; i < static_cast( symbol.size() ); ++i) + for(int i = 0; i < static_cast(symbol.size()); ++i) { if(*mIter != symbol[i]) { @@ -449,7 +448,7 @@ bool JsonParserState::ParseSymbol(const std::string& symbol) bool JsonParserState::ParseTrue() { - if( ParseSymbol("true") ) + if(ParseSymbol("true")) { mCurrent.SetInteger(1); mCurrent.SetType(TreeNode::BOOLEAN); @@ -463,7 +462,7 @@ bool JsonParserState::ParseTrue() bool JsonParserState::ParseFalse() { - if( ParseSymbol("false") ) + if(ParseSymbol("false")) { mCurrent.SetInteger(0); mCurrent.SetType(TreeNode::BOOLEAN); @@ -477,7 +476,7 @@ bool JsonParserState::ParseFalse() bool JsonParserState::ParseNULL() { - if( ParseSymbol("null") ) + if(ParseSymbol("null")) { mCurrent.SetType(TreeNode::IS_NULL); return true; @@ -490,30 +489,30 @@ bool JsonParserState::ParseNULL() bool JsonParserState::ParseNumber() { - mCurrent.SetType( TreeNode::INTEGER ); + mCurrent.SetType(TreeNode::INTEGER); VectorCharIter first = mIter; - char c = Char(); + char c = Char(); - if( !(c == '-' || IsNumber(c) ) ) + if(!(c == '-' || IsNumber(c))) { return Error("Number must start with '-' or 0-9"); } - while ( IsNumber(c) || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-' ) + while(IsNumber(c) || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-') { - if (c == '.' || c == 'e' || c == 'E') + if(c == '.' || c == 'e' || c == 'E') { - mCurrent.SetType( TreeNode::FLOAT ); + mCurrent.SetType(TreeNode::FLOAT); } Advance(1); c = Char(); } - if( mCurrent.GetType() == TreeNode::INTEGER ) + if(mCurrent.GetType() == TreeNode::INTEGER) { int i = 0; - if( StringToInteger(&(*first), &(*mIter), i ) ) + if(StringToInteger(&(*first), &(*mIter), i)) { mCurrent.SetInteger(i); } @@ -526,7 +525,7 @@ bool JsonParserState::ParseNumber() if(mCurrent.GetType() == TreeNode::FLOAT) { float f = 0.f; - if( StringToFloat(&(*first), &(*mIter), f) ) + if(StringToFloat(&(*first), &(*mIter), f)) { mCurrent.SetFloat(f); } @@ -536,25 +535,25 @@ bool JsonParserState::ParseNumber() } } - return (mCurrent.GetType() == TreeNode::INTEGER) || (mCurrent.GetType() == TreeNode::FLOAT); + return (mCurrent.GetType() == TreeNode::INTEGER) || (mCurrent.GetType() == TreeNode::FLOAT); } char* JsonParserState::EncodeString() { - int substitution = 0; - VectorCharIter first = mIter; - VectorCharIter last = mIter; + int substitution = 0; + VectorCharIter first = mIter; + VectorCharIter last = mIter; - while (*mIter) + while(*mIter) { - if (static_cast(*mIter) < '\x20') + if(static_cast(*mIter) < '\x20') { - static_cast( Error("Control characters not allowed in strings") ); + static_cast(Error("Control characters not allowed in strings")); return nullptr; } - else if (*mIter == '\\' && AtLeast(2)) + else if(*mIter == '\\' && AtLeast(2)) { - switch (*(mIter+1)) + switch(*(mIter + 1)) { case '"': { @@ -599,31 +598,31 @@ char* JsonParserState::EncodeString() case 'u': { unsigned int codepoint; - if( !AtLeast(6) ) + if(!AtLeast(6)) { - static_cast( Error("Bad unicode codepoint; not enough characters") ); + static_cast(Error("Bad unicode codepoint; not enough characters")); return nullptr; } - if ( !HexStringToUnsignedInteger(&(*(mIter + 2)), &(*(mIter + 6)), codepoint) ) + if(!HexStringToUnsignedInteger(&(*(mIter + 2)), &(*(mIter + 6)), codepoint)) { - static_cast( Error("Bad unicode codepoint") ); + static_cast(Error("Bad unicode codepoint")); return nullptr; } - if (codepoint <= 0x7F) + if(codepoint <= 0x7F) { *last = (char)codepoint; } - else if (codepoint <= 0x7FF) + else if(codepoint <= 0x7FF) { *last++ = (char)(0xC0 | (codepoint >> 6)); - *last = (char)(0x80 | (codepoint & 0x3F)); + *last = (char)(0x80 | (codepoint & 0x3F)); } - else if (codepoint <= 0xFFFF) + else if(codepoint <= 0xFFFF) { *last++ = (char)(0xE0 | (codepoint >> 12)); *last++ = (char)(0x80 | ((codepoint >> 6) & 0x3F)); - *last = (char)(0x80 | (codepoint & 0x3F)); + *last = (char)(0x80 | (codepoint & 0x3F)); } Advance(4); @@ -632,7 +631,7 @@ char* JsonParserState::EncodeString() default: { - static_cast( Error("Unrecognized escape sequence") ); + static_cast(Error("Unrecognized escape sequence")); return nullptr; } } @@ -640,7 +639,7 @@ char* JsonParserState::EncodeString() ++last; Advance(2); } - else if (*mIter == '{') + else if(*mIter == '{') { if((0 == substitution) && (*last != '\\')) { @@ -649,7 +648,7 @@ char* JsonParserState::EncodeString() *last++ = *mIter; Advance(1); } - else if (*mIter == '}') + else if(*mIter == '}') { if(substitution) { @@ -658,7 +657,7 @@ char* JsonParserState::EncodeString() *last++ = *mIter; Advance(1); } - else if (*mIter == '"') + else if(*mIter == '"') { *last = 0; Advance(1); @@ -673,9 +672,9 @@ char* JsonParserState::EncodeString() } // while(*mIter) mNumberOfParsedChars += last - first; - mNumberOfParsedChars += 1 ; // null terminator + mNumberOfParsedChars += 1; // null terminator - mCurrent.SetSubstitution( substitution > 1 ); + mCurrent.SetSubstitution(substitution > 1); // return true; return &(*first); @@ -684,12 +683,12 @@ char* JsonParserState::EncodeString() bool JsonParserState::HandleStartState(const char* name, const char currentChar) { - if( '{' == currentChar ) + if('{' == currentChar) { NewNode(name, TreeNode::OBJECT); mState = STATE_OBJECT; } - else if( '[' == currentChar ) + else if('[' == currentChar) { NewNode(name, TreeNode::ARRAY); mState = STATE_VALUE; @@ -705,20 +704,20 @@ bool JsonParserState::HandleStartState(const char* name, const char currentChar) bool JsonParserState::HandleObjectState(const char currentChar, const char lastCharacter) { - if( '}' == currentChar ) + if('}' == currentChar) { if(',' == lastCharacter) { return Error("Unexpected comma"); } - if( !UpToParent() ) + if(!UpToParent()) { return false; } mState = STATE_VALUE; } - else if ( '"' == currentChar ) + else if('"' == currentChar) { mState = STATE_KEY; } @@ -734,19 +733,19 @@ bool JsonParserState::HandleObjectState(const char currentChar, const char lastC bool JsonParserState::HandleKeyState(char*& name) { name = EncodeString(); - if( nullptr == name ) + if(nullptr == name) { return false; } - if( !ParseWhiteSpace() ) + if(!ParseWhiteSpace()) { return false; } - if( ':' != Char()) + if(':' != Char()) { return Error("Expected ':'"); } - if( !ParseWhiteSpace() ) + if(!ParseWhiteSpace()) { return false; } @@ -760,7 +759,7 @@ bool JsonParserState::HandleCharacterQuote(char*& name) { Advance(1); NewNode(name, TreeNode::STRING); - if( char* value = EncodeString() ) + if(char* value = EncodeString()) { mCurrent.SetString(value); } @@ -768,7 +767,7 @@ bool JsonParserState::HandleCharacterQuote(char*& name) { return false; } - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -779,11 +778,11 @@ bool JsonParserState::HandleCharacterQuote(char*& name) bool JsonParserState::HandleCharacterNumberOrHyphen(const char* name) { NewNode(name, TreeNode::IS_NULL); - if( !ParseNumber() ) + if(!ParseNumber()) { return false; } - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -795,43 +794,43 @@ bool JsonParserState::HandleValueState(char*& name, const char currentChar, cons { bool handled = true; - if( '"' == currentChar ) + if('"' == currentChar) { handled = HandleCharacterQuote(name); } - else if( IsNumber(currentChar) || currentChar == '-' ) + else if(IsNumber(currentChar) || currentChar == '-') { handled = HandleCharacterNumberOrHyphen(name); } - else if( '{' == currentChar ) + else if('{' == currentChar) { handled = HandleCharacterBracesStart(name, lastCharacter); } - else if( '}' == currentChar ) + else if('}' == currentChar) { handled = HandleCharacterBracesEnd(lastCharacter); } - else if( '[' == currentChar ) + else if('[' == currentChar) { handled = HandleCharacterSquareBracketStart(name); } - else if( ']' == currentChar ) + else if(']' == currentChar) { handled = HandleCharacterSquareBracketEnd(lastCharacter); } - else if( 't' == currentChar ) + else if('t' == currentChar) { handled = HandleCharacterLowercaseT(name); } - else if( 'n' == currentChar ) + else if('n' == currentChar) { handled = HandleCharacterLowercaseN(name); } - else if( 'f' == currentChar) + else if('f' == currentChar) { handled = HandleCharacterLowercaseF(name); } - else if( ',' == currentChar ) + else if(',' == currentChar) { handled = HandleCharacterComma(name); } @@ -852,7 +851,7 @@ bool JsonParserState::ParseJson(VectorChar& source) { Reset(); - if( 0 == source.size() ) + if(0 == source.size()) { return Error("Empty source buffer to parse"); } @@ -860,11 +859,11 @@ bool JsonParserState::ParseJson(VectorChar& source) mIter = source.begin(); mEnd = source.end(); - char* name = nullptr; - char currentChar = 0; - char lastCharacter = 0; + char* name = nullptr; + char currentChar = 0; + char lastCharacter = 0; - if( !ParseWhiteSpace() ) + if(!ParseWhiteSpace()) { return false; } @@ -872,9 +871,9 @@ bool JsonParserState::ParseJson(VectorChar& source) while(mIter != mEnd) { lastCharacter = currentChar; - currentChar = Char(); + currentChar = Char(); - switch( mState ) + switch(mState) { case STATE_START: { @@ -918,7 +917,7 @@ bool JsonParserState::ParseJson(VectorChar& source) } // while(1) // - if( mState != STATE_END ) + if(mState != STATE_END) { return Error("Unexpected termination character"); } @@ -933,15 +932,15 @@ void JsonParserState::Reset() { mCurrent = TreeNodeManipulator(mRoot); - mErrorDescription = nullptr; - mErrorNewLine = 0; - mErrorColumn = 0; - mErrorPosition = 0; + mErrorDescription = nullptr; + mErrorNewLine = 0; + mErrorColumn = 0; + mErrorPosition = 0; } bool JsonParserState::HandleCharacterBracesStart(const char* name, const char lastCharacter) { - if( '}' == lastCharacter ) + if('}' == lastCharacter) { return Error("Expected a comma"); } @@ -972,7 +971,7 @@ bool JsonParserState::HandleCharacterBracesEnd(const char lastCharacter) } else { - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -1007,7 +1006,7 @@ bool JsonParserState::HandleCharacterSquareBracketEnd(const char lastCharacter) } else { - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -1019,11 +1018,11 @@ bool JsonParserState::HandleCharacterSquareBracketEnd(const char lastCharacter) bool JsonParserState::HandleCharacterLowercaseT(const char* name) { NewNode(name, TreeNode::BOOLEAN); - if( !ParseTrue() ) + if(!ParseTrue()) { return false; } - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -1034,11 +1033,11 @@ bool JsonParserState::HandleCharacterLowercaseT(const char* name) bool JsonParserState::HandleCharacterLowercaseN(const char* name) { NewNode(name, TreeNode::IS_NULL); - if( !ParseNULL() ) + if(!ParseNULL()) { return false; } - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -1049,11 +1048,11 @@ bool JsonParserState::HandleCharacterLowercaseN(const char* name) bool JsonParserState::HandleCharacterLowercaseF(const char* name) { NewNode(name, TreeNode::BOOLEAN); - if( !ParseFalse() ) + if(!ParseFalse()) { return false; } - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -1063,7 +1062,7 @@ bool JsonParserState::HandleCharacterLowercaseF(const char* name) bool JsonParserState::HandleCharacterComma(const char* name) { - if( 0 == mCurrent.Size() ) + if(0 == mCurrent.Size()) { return Error("Missing Value"); } diff --git a/dali-toolkit/internal/builder/json-parser-state.h b/dali-toolkit/internal/builder/json-parser-state.h index 4d7e7a4..d6eb0e9 100644 --- a/dali-toolkit/internal/builder/json-parser-state.h +++ b/dali-toolkit/internal/builder/json-parser-state.h @@ -2,7 +2,7 @@ #define DALI_JSON_PARSE_STATE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,20 +28,17 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - /** * A safer std::advance() */ -template +template inline int AdvanceIter(IteratorType& iter, EndIteratorType& end, int n) { - for(int i =0; i < n; ++i) + for(int i = 0; i < n; ++i) { if(iter == end) { @@ -85,51 +82,69 @@ public: * Get the error description of the last parse * @return The error description or NULL if no error */ - const char* GetErrorDescription() { return mErrorDescription; } + const char* GetErrorDescription() + { + return mErrorDescription; + } /** * Get the error line number * @return The line number of the error */ - int GetErrorLineNumber() { return mErrorNewLine; } + int GetErrorLineNumber() + { + return mErrorNewLine; + } /** * Get the error column * @return The error column */ - int GetErrorColumn() { return mErrorColumn; } + int GetErrorColumn() + { + return mErrorColumn; + } /** * Get the error position * @return The error position */ - int GetErrorPosition() { return mErrorPosition; } + int GetErrorPosition() + { + return mErrorPosition; + } /** * Get the size of the string data that has been parsed * @return The size of string data */ - int GetParsedStringSize() { return mNumberOfParsedChars; }; + int GetParsedStringSize() + { + return mNumberOfParsedChars; + }; /** * Get the number of nodes created * @return The number of nodes */ - int GetCreatedNodeCount() { return mNumberOfCreatedNodes; }; + int GetCreatedNodeCount() + { + return mNumberOfCreatedNodes; + }; private: - VectorCharIter mIter; ///< Current position - VectorCharIter mStart; ///< Start position - VectorCharIter mEnd; ///< End of buffer being parsed - TreeNode* mRoot; ///< Root node created - TreeNodeManipulator mCurrent; ///< The Current modifiable node - const char* mErrorDescription; ///< The error description if set - int mErrorNewLine; ///< The error line number - int mErrorColumn; ///< The error column - int mErrorPosition; ///< The error position - int mNumberOfParsedChars; ///< The size of string data - int mNumberOfCreatedNodes; ///< The number of nodes created - bool mFirstParse; ///< Flag if first parse + VectorCharIter mIter; ///< Current position + VectorCharIter mStart; ///< Start position + VectorCharIter mEnd; ///< End of buffer being parsed + TreeNode* mRoot; ///< Root node created + TreeNodeManipulator mCurrent; ///< The Current modifiable node + const char* mErrorDescription; ///< The error description if set + int mErrorNewLine; ///< The error line number + int mErrorColumn; ///< The error column + int mErrorPosition; ///< The error position + int mNumberOfParsedChars; ///< The size of string data + int mNumberOfCreatedNodes; ///< The number of nodes created + bool mFirstParse; ///< Flag if first parse /** * The current parse state @@ -231,7 +246,7 @@ private: { return Error("Attempt to walk up above root"); } - mCurrent = TreeNodeManipulator( mCurrent.GetParent() ); + mCurrent = TreeNodeManipulator(mCurrent.GetParent()); return true; } @@ -269,7 +284,7 @@ private: { int c = AdvanceIter(mIter, mEnd, n); mErrorPosition += c; - mErrorColumn += c; + mErrorColumn += c; } /** @@ -279,7 +294,7 @@ private: { int c = AdvanceIter(mIter, mEnd, n); mErrorPosition += c; - mErrorColumn += c; + mErrorColumn += c; return mEnd == mIter; } @@ -290,8 +305,8 @@ private: { int c = AdvanceIter(mIter, mEnd, n); mErrorPosition += c; - mErrorColumn += c; - static_cast( ParseWhiteSpace() ); + mErrorColumn += c; + static_cast(ParseWhiteSpace()); } /** @@ -421,7 +436,6 @@ private: bool HandleCharacterComma(const char* name); }; - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/builder/optional-value.h b/dali-toolkit/internal/builder/optional-value.h index 666dd30..7251ad2 100644 --- a/dali-toolkit/internal/builder/optional-value.h +++ b/dali-toolkit/internal/builder/optional-value.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_INTERNAL_BUILDER_OPTIONAL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,70 +18,115 @@ * */ -template +template struct OptionalTypes { - typedef T ValueType; - typedef const T& ReturnType; - static ReturnType Get(const ValueType& v) { return v; } - static ValueType Set(const ReturnType v) { return v; } - static bool Ok(const ValueType& v) { return true; } + typedef T ValueType; + typedef const T& ReturnType; + static ReturnType Get(const ValueType& v) + { + return v; + } + static ValueType Set(const ReturnType v) + { + return v; + } + static bool Ok(const ValueType& v) + { + return true; + } }; -template +template struct OptionalTypes { - typedef T* ValueType; - typedef const T* ReturnType; - static ReturnType Get(const ValueType v) { return v; } - static ValueType Set(const ReturnType v) { return v; } - static bool Ok(const ReturnType v) { return NULL != v; } + typedef T* ValueType; + typedef const T* ReturnType; + static ReturnType Get(const ValueType v) + { + return v; + } + static ValueType Set(const ReturnType v) + { + return v; + } + static bool Ok(const ReturnType v) + { + return NULL != v; + } }; -template +template struct OptionalTypes { - typedef T* ValueType; - typedef const T& ReturnType; - static ReturnType Get(const ValueType v) { return *v; } - static ValueType Set(const ReturnType v) { return &v; } - static bool Ok(const ReturnType v) { return true; } + typedef T* ValueType; + typedef const T& ReturnType; + static ReturnType Get(const ValueType v) + { + return *v; + } + static ValueType Set(const ReturnType v) + { + return &v; + } + static bool Ok(const ReturnType v) + { + return true; + } }; -template +template class OptionalValue { public: - typedef void ( OptionalValue::*bool_type )() const; + typedef void (OptionalValue::*bool_type)() const; typedef typename OptionalTypes::ReturnType ReturnType; - typedef typename OptionalTypes::ValueType ValueType; + typedef typename OptionalTypes::ValueType ValueType; - OptionalValue(): mOk(false), mValue() {} - OptionalValue( T value ): mOk(OptionalTypes::Ok(value)), mValue(OptionalTypes::Set(value)) {} - OptionalValue( bool b, T value ): mOk(b), mValue(OptionalTypes::Set(value)) {} + OptionalValue() + : mOk(false), + mValue() + { + } + OptionalValue(T value) + : mOk(OptionalTypes::Ok(value)), + mValue(OptionalTypes::Set(value)) + { + } + OptionalValue(bool b, T value) + : mOk(b), + mValue(OptionalTypes::Set(value)) + { + } - ReturnType operator *() const { return OptionalTypes::Get(mValue); } + ReturnType operator*() const + { + return OptionalTypes::Get(mValue); + } // safe bool idiom - operator bool_type() const { + operator bool_type() const + { return mOk == true ? &OptionalValue::this_type_does_not_support_comparisons : 0; } private: - bool mOk; + bool mOk; ValueType mValue; - void this_type_does_not_support_comparisons() const {} + void this_type_does_not_support_comparisons() const + { + } }; -template -bool operator==( const OptionalValue& lhs, const OptionalValue& rhs ) +template +bool operator==(const OptionalValue& lhs, const OptionalValue& rhs) { lhs.this_type_does_not_support_comparisons(); return false; } -template -bool operator!=( const OptionalValue& lhs, const OptionalValue& rhs ) +template +bool operator!=(const OptionalValue& lhs, const OptionalValue& rhs) { lhs.this_type_does_not_support_comparisons(); return false; diff --git a/dali-toolkit/internal/builder/replacement.cpp b/dali-toolkit/internal/builder/replacement.cpp index a15ef21..5825da5 100644 --- a/dali-toolkit/internal/builder/replacement.cpp +++ b/dali-toolkit/internal/builder/replacement.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,29 +16,25 @@ */ // INTERNAL INCLUDES -#include -#include #include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - -namespace // anon +namespace // anon { - -Property::Value* FindReplacement( const std::string &str, const Property::Map& overrideMap, const Property::Map& defaultMap ) +Property::Value* FindReplacement(const std::string& str, const Property::Map& overrideMap, const Property::Map& defaultMap) { - Property::Value* ret = overrideMap.Find( str ); + Property::Value* ret = overrideMap.Find(str); - if ( !ret ) + if(!ret) { - ret = defaultMap.Find( str ); + ret = defaultMap.Find(str); // @ todo // try localized text ie dgettext. Look for colon {DOMAIN:TEXT} {LC_MESSAGE:ID_XXXX} @@ -47,17 +43,17 @@ Property::Value* FindReplacement( const std::string &str, const Property::Map& o return ret; } -std::size_t FirstUnescapedChar(const std::string &initialValue, const std::size_t& startPos, const char c) +std::size_t FirstUnescapedChar(const std::string& initialValue, const std::size_t& startPos, const char c) { - std::size_t pos = initialValue.find( c, startPos ); + std::size_t pos = initialValue.find(c, startPos); if(pos > 0) { - while( pos != std::string::npos ) + while(pos != std::string::npos) { - if( '\\' == initialValue.at( pos-1 ) ) + if('\\' == initialValue.at(pos - 1)) { - pos = initialValue.find( c, pos ); + pos = initialValue.find(c, pos); } else { @@ -69,11 +65,11 @@ std::size_t FirstUnescapedChar(const std::string &initialValue, const std::size_ return pos; } -bool GetSubstitutionPosition( const std::string &initialValue, std::size_t &startPos, std::size_t &size ) +bool GetSubstitutionPosition(const std::string& initialValue, std::size_t& startPos, std::size_t& size) { std::size_t pos = FirstUnescapedChar(initialValue, 0, '{'); - if( std::string::npos == pos ) + if(std::string::npos == pos) { startPos = std::string::npos; return false; @@ -85,7 +81,7 @@ bool GetSubstitutionPosition( const std::string &initialValue, std::size_t &star pos = FirstUnescapedChar(initialValue, startPos, '}'); - if( std::string::npos == pos ) + if(std::string::npos == pos) { size = std::string::npos; return false; @@ -98,11 +94,9 @@ bool GetSubstitutionPosition( const std::string &initialValue, std::size_t &star return true; } -bool ResolvePartialReplacement( const std::string &initialValue, Property::Value &out, - const Property::Map& overrideMap, const Property::Map& defaultMap ) +bool ResolvePartialReplacement(const std::string& initialValue, Property::Value& out, const Property::Map& overrideMap, const Property::Map& defaultMap) { - - if( initialValue.size() >= 2 ) + if(initialValue.size() >= 2) { // eg '{"constants": { "IMAGE_DIR": "/share/images" }, // ... @@ -111,36 +105,37 @@ bool ResolvePartialReplacement( const std::string &initialValue, Property::Value std::size_t startPos = 0; std::size_t size = std::string::npos; - if( !GetSubstitutionPosition( initialValue, startPos, size ) ) + if(!GetSubstitutionPosition(initialValue, startPos, size)) { out = initialValue; return true; } else { - const std::string str( initialValue.substr( startPos, size ) ); + const std::string str(initialValue.substr(startPos, size)); - Property::Value* value = FindReplacement( str, overrideMap, defaultMap ); + Property::Value* value = FindReplacement(str, overrideMap, defaultMap); - if( !value ) + if(!value) { - DALI_SCRIPT_WARNING( "Cannot find replacement for '%s'\n", str.c_str() ); + DALI_SCRIPT_WARNING("Cannot find replacement for '%s'\n", str.c_str()); } else { - if( Property::STRING != value->GetType() ) + if(Property::STRING != value->GetType()) { - DALI_SCRIPT_WARNING( "Cannot replace substring in non string property type='%s'. Initial value '%s'\n", - PropertyTypes::GetName( out.GetType() ), initialValue.c_str() ); + DALI_SCRIPT_WARNING("Cannot replace substring in non string property type='%s'. Initial value '%s'\n", + PropertyTypes::GetName(out.GetType()), + initialValue.c_str()); } else { - std::string newString = \ + std::string newString = initialValue.substr(0, startPos - 1) + - value->Get< std::string >() + - initialValue.substr( startPos + size + 1 ); + value->Get() + + initialValue.substr(startPos + size + 1); - return ResolvePartialReplacement( newString, out, overrideMap, defaultMap ); + return ResolvePartialReplacement(newString, out, overrideMap, defaultMap); } } } @@ -150,13 +145,12 @@ bool ResolvePartialReplacement( const std::string &initialValue, Property::Value return false; } -} // namespace anon +} // namespace - -Replacement::Replacement( const Property::Map& overrideMap, const Property::Map& defaultMap ) - : mOverrideMap( &overrideMap ), mDefaultMap( &defaultMap ) +Replacement::Replacement(const Property::Map& overrideMap, const Property::Map& defaultMap) +: mOverrideMap(&overrideMap), + mDefaultMap(&defaultMap) { - } namespace @@ -164,46 +158,46 @@ namespace Property::Map noMap; } -Replacement::Replacement( const Property::Map& defaultMap ) - : mOverrideMap( &noMap ), mDefaultMap( &defaultMap ) +Replacement::Replacement(const Property::Map& defaultMap) +: mOverrideMap(&noMap), + mDefaultMap(&defaultMap) { - } -Replacement::Replacement( ) - : mOverrideMap( &noMap ), mDefaultMap( &noMap ) +Replacement::Replacement() +: mOverrideMap(&noMap), + mDefaultMap(&noMap) { - } -OptionalString Replacement::HasFullReplacement( const TreeNode & node ) const +OptionalString Replacement::HasFullReplacement(const TreeNode& node) const { OptionalString ret; - if( node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count()) ) + if(node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count())) { - OptionalString v = ::IsString( node ); - if( v ) + OptionalString v = ::IsString(node); + if(v) { const std::string& initialValue = *v; - if( (initialValue[ 0 ] == '{') && (initialValue[ initialValue.size() -1 ] == '}') ) + if((initialValue[0] == '{') && (initialValue[initialValue.size() - 1] == '}')) { - ret = initialValue.substr( 1, initialValue.size() - 2 ); + ret = initialValue.substr(1, initialValue.size() - 2); } } } return ret; } -Property::Value Replacement::GetFullReplacement( const std::string& replacementString ) const +Property::Value Replacement::GetFullReplacement(const std::string& replacementString) const { Property::Value out; - DALI_ASSERT_DEBUG( mOverrideMap && "missing map"); - DALI_ASSERT_DEBUG( mDefaultMap && "missing map"); + DALI_ASSERT_DEBUG(mOverrideMap && "missing map"); + DALI_ASSERT_DEBUG(mDefaultMap && "missing map"); - Property::Value* value = FindReplacement( replacementString, *mOverrideMap, *mDefaultMap ); + Property::Value* value = FindReplacement(replacementString, *mOverrideMap, *mDefaultMap); - if( !value ) + if(!value) { DALI_SCRIPT_WARNING("Cannot find replacement for '%s'\n", replacementString.c_str()); } @@ -213,36 +207,36 @@ Property::Value Replacement::GetFullReplacement( const std::string& replacementS #if defined(DEBUG_ENABLED) DALI_SCRIPT_VERBOSE(" Full replacement for '%s' => to Type '%s'\n", replacementString.c_str(), - PropertyTypes::GetName( out.GetType()) ); + PropertyTypes::GetName(out.GetType())); #endif } return out; } -OptionalBoolean Replacement::IsBoolean( const TreeNode & node ) const +OptionalBoolean Replacement::IsBoolean(const TreeNode& node) const { OptionalBoolean ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::BOOLEAN == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::BOOLEAN == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsBoolean( node ); + ret = ::IsBoolean(node); } return ret; } -OptionalBoolean Replacement::IsBoolean( OptionalChild child ) const +OptionalBoolean Replacement::IsBoolean(OptionalChild child) const { - if( child ) + if(child) { - return IsBoolean( *child ); + return IsBoolean(*child); } else { @@ -250,39 +244,39 @@ OptionalBoolean Replacement::IsBoolean( OptionalChild child ) const } } -OptionalFloat Replacement::IsFloat( const TreeNode & node ) const +OptionalFloat Replacement::IsFloat(const TreeNode& node) const { OptionalFloat ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::FLOAT == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::FLOAT == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsFloat( node ); + ret = ::IsFloat(node); } return ret; } -OptionalString Replacement::IsString( const TreeNode& node ) const +OptionalString Replacement::IsString(const TreeNode& node) const { OptionalString ret; - DALI_ASSERT_DEBUG( mOverrideMap && "missing map"); - DALI_ASSERT_DEBUG( mDefaultMap && "missing map"); + DALI_ASSERT_DEBUG(mOverrideMap && "missing map"); + DALI_ASSERT_DEBUG(mDefaultMap && "missing map"); - if( node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count()) ) + if(node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count())) { - if( OptionalString v = ::IsString( node ) ) + if(OptionalString v = ::IsString(node)) { Property::Value value; - if( ResolvePartialReplacement( *v, value, *mOverrideMap, *mDefaultMap ) ) + if(ResolvePartialReplacement(*v, value, *mOverrideMap, *mDefaultMap)) { - if( Property::STRING == value.GetType() ) + if(Property::STRING == value.GetType()) { ret = value.Get(); #if defined(DEBUG_ENABLED) @@ -298,160 +292,160 @@ OptionalString Replacement::IsString( const TreeNode& node ) const } else { - ret = ::IsString( node ); + ret = ::IsString(node); } return ret; } -OptionalInteger Replacement::IsInteger( const TreeNode & node ) const +OptionalInteger Replacement::IsInteger(const TreeNode& node) const { OptionalInteger ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::INTEGER == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::INTEGER == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsInteger( node ); + ret = ::IsInteger(node); } return ret; } -OptionalVector2 Replacement::IsVector2( const TreeNode & node ) const +OptionalVector2 Replacement::IsVector2(const TreeNode& node) const { OptionalVector2 ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::VECTOR2 == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::VECTOR2 == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsVector2( node ); + ret = ::IsVector2(node); } return ret; } -OptionalVector3 Replacement::IsVector3( const TreeNode & node ) const +OptionalVector3 Replacement::IsVector3(const TreeNode& node) const { OptionalVector3 ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::VECTOR3 == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::VECTOR3 == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsVector3( node ); + ret = ::IsVector3(node); } return ret; } -OptionalVector4 Replacement::IsVector4( const TreeNode & node ) const +OptionalVector4 Replacement::IsVector4(const TreeNode& node) const { OptionalVector4 ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::VECTOR4 == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::VECTOR4 == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsVector4( node ); + ret = ::IsVector4(node); } return ret; } -OptionalMatrix Replacement::IsMatrix( const TreeNode & node ) const +OptionalMatrix Replacement::IsMatrix(const TreeNode& node) const { OptionalMatrix ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::MATRIX == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::MATRIX == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsMatrix( node ); + ret = ::IsMatrix(node); } return ret; } -OptionalMatrix3 Replacement::IsMatrix3( const TreeNode & node ) const +OptionalMatrix3 Replacement::IsMatrix3(const TreeNode& node) const { OptionalMatrix3 ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::MATRIX3 == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::MATRIX3 == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsMatrix3( node ); + ret = ::IsMatrix3(node); } return ret; } -OptionalRect Replacement::IsRect( const TreeNode & node ) const +OptionalRect Replacement::IsRect(const TreeNode& node) const { OptionalRect ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::RECTANGLE == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::RECTANGLE == value.GetType()) { ret = value.Get >(); } } else { - ret = ::IsRect( node ); + ret = ::IsRect(node); } return ret; } -OptionalExtents Replacement::IsExtents( const TreeNode & node ) const +OptionalExtents Replacement::IsExtents(const TreeNode& node) const { OptionalExtents extents; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::EXTENTS == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::EXTENTS == value.GetType()) { extents = value.Get(); } } else { - extents = ::IsExtents( node ); + extents = ::IsExtents(node); } return extents; } -OptionalFloat Replacement::IsFloat( OptionalChild child ) const +OptionalFloat Replacement::IsFloat(OptionalChild child) const { - if( child ) + if(child) { - return IsFloat( *child ); + return IsFloat(*child); } else { @@ -459,12 +453,11 @@ OptionalFloat Replacement::IsFloat( OptionalChild child ) const } } - -OptionalString Replacement::IsString( OptionalChild child ) const +OptionalString Replacement::IsString(OptionalChild child) const { - if( child ) + if(child) { - return IsString( *child ); + return IsString(*child); } else { @@ -472,11 +465,11 @@ OptionalString Replacement::IsString( OptionalChild child ) const } } -OptionalInteger Replacement::IsInteger( OptionalChild child ) const +OptionalInteger Replacement::IsInteger(OptionalChild child) const { - if( child ) + if(child) { - return IsInteger( *child ); + return IsInteger(*child); } else { @@ -484,11 +477,11 @@ OptionalInteger Replacement::IsInteger( OptionalChild child ) const } } -OptionalVector2 Replacement::IsVector2( OptionalChild child ) const +OptionalVector2 Replacement::IsVector2(OptionalChild child) const { - if( child ) + if(child) { - return IsVector2( *child ); + return IsVector2(*child); } else { @@ -496,11 +489,11 @@ OptionalVector2 Replacement::IsVector2( OptionalChild child ) const } } -OptionalVector3 Replacement::IsVector3( OptionalChild child ) const +OptionalVector3 Replacement::IsVector3(OptionalChild child) const { - if( child ) + if(child) { - return IsVector3( *child ); + return IsVector3(*child); } else { @@ -508,11 +501,11 @@ OptionalVector3 Replacement::IsVector3( OptionalChild child ) const } } -OptionalVector4 Replacement::IsVector4( OptionalChild child ) const +OptionalVector4 Replacement::IsVector4(OptionalChild child) const { - if( child ) + if(child) { - return IsVector4( *child ); + return IsVector4(*child); } else { @@ -520,11 +513,11 @@ OptionalVector4 Replacement::IsVector4( OptionalChild child ) const } } -OptionalMatrix Replacement::IsMatrix( OptionalChild child ) const +OptionalMatrix Replacement::IsMatrix(OptionalChild child) const { - if( child ) + if(child) { - return IsMatrix( *child ); + return IsMatrix(*child); } else { @@ -532,11 +525,11 @@ OptionalMatrix Replacement::IsMatrix( OptionalChild child ) const } } -OptionalMatrix3 Replacement::IsMatrix3( OptionalChild child ) const +OptionalMatrix3 Replacement::IsMatrix3(OptionalChild child) const { - if( child ) + if(child) { - return IsMatrix3( *child ); + return IsMatrix3(*child); } else { @@ -544,11 +537,11 @@ OptionalMatrix3 Replacement::IsMatrix3( OptionalChild child ) const } } -OptionalRect Replacement::IsRect( OptionalChild child ) const +OptionalRect Replacement::IsRect(OptionalChild child) const { - if( child ) + if(child) { - return IsRect( *child ); + return IsRect(*child); } else { @@ -556,16 +549,16 @@ OptionalRect Replacement::IsRect( OptionalChild child ) const } } -bool Replacement::IsMap( OptionalChild child, Property::Value& out ) const +bool Replacement::IsMap(OptionalChild child, Property::Value& out) const { bool ret = false; - if( child ) + if(child) { - if( OptionalString replace = HasFullReplacement( *child ) ) + if(OptionalString replace = HasFullReplacement(*child)) { - out = GetFullReplacement( *replace ); - if( Property::MAP == out.GetType() ) + out = GetFullReplacement(*replace); + if(Property::MAP == out.GetType()) { ret = true; } @@ -575,16 +568,16 @@ bool Replacement::IsMap( OptionalChild child, Property::Value& out ) const return ret; } -bool Replacement::IsArray( OptionalChild child, Property::Value& out ) const +bool Replacement::IsArray(OptionalChild child, Property::Value& out) const { bool ret = false; - if( child ) + if(child) { - if( OptionalString replace = HasFullReplacement( *child ) ) + if(OptionalString replace = HasFullReplacement(*child)) { - out = GetFullReplacement( *replace ); - if( Property::ARRAY == out.GetType() ) + out = GetFullReplacement(*replace); + if(Property::ARRAY == out.GetType()) { ret = true; } @@ -594,11 +587,11 @@ bool Replacement::IsArray( OptionalChild child, Property::Value& out ) const return ret; } -OptionalExtents Replacement::IsExtents( OptionalChild child ) const +OptionalExtents Replacement::IsExtents(OptionalChild child) const { - if( child ) + if(child) { - return IsExtents( *child ); + return IsExtents(*child); } else { diff --git a/dali-toolkit/internal/builder/replacement.h b/dali-toolkit/internal/builder/replacement.h index 24260de..7780ec6 100644 --- a/dali-toolkit/internal/builder/replacement.h +++ b/dali-toolkit/internal/builder/replacement.h @@ -2,7 +2,7 @@ #define DALI_TOOLKIT_INTERNAL_BUILDER_REPLACEMENT_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,18 +27,15 @@ namespace Dali { - namespace Toolkit { - class TreeNode; +class TreeNode; } namespace Toolkit { - namespace Internal { - /* * Supports template replacement functionality * @@ -46,7 +43,6 @@ namespace Internal class Replacement { public: - /* * Constructor */ @@ -59,7 +55,7 @@ public: * @param overrideMap The user overriding map * @param defaultMap The default map to use */ - Replacement( const Property::Map& overrideMap, const Property::Map& defaultMap ); + Replacement(const Property::Map& overrideMap, const Property::Map& defaultMap); /* * Constructor with default map @@ -67,175 +63,175 @@ public: * Make a deep copy of the tree. * @param overrideMap The user overriding map */ - Replacement( const Property::Map& defaultMap ); + Replacement(const Property::Map& defaultMap); /* @brief Check node for a type * * @param node The TreeNode to check * @return Optional value */ - OptionalString IsString( const TreeNode& node ) const; + OptionalString IsString(const TreeNode& node) const; /* @brief Check node for a type * * @param node The TreeNode to check * @return Optional value */ - OptionalBoolean IsBoolean( const TreeNode & node ) const; + OptionalBoolean IsBoolean(const TreeNode& node) const; /* @brief Check node for a type * * @param node The TreeNode to check * @return Optional value */ - OptionalFloat IsFloat( const TreeNode & node ) const; + OptionalFloat IsFloat(const TreeNode& node) const; /* @brief Check node for a type * * @param node The TreeNode to check * @return Optional value */ - OptionalInteger IsInteger( const TreeNode & node ) const; + OptionalInteger IsInteger(const TreeNode& node) const; /* @brief Check node for a type * * @param node The TreeNode to check * @return Optional value */ - OptionalVector2 IsVector2( const TreeNode & node ) const; + OptionalVector2 IsVector2(const TreeNode& node) const; /* @brief Check node for a type * * @param node The TreeNode to check * @return Optional value */ - OptionalVector3 IsVector3( const TreeNode & node ) const; + OptionalVector3 IsVector3(const TreeNode& node) const; /* @brief Check node for a type * * @param node The TreeNode to check * @return Optional value */ - OptionalVector4 IsVector4( const TreeNode & node ) const; + OptionalVector4 IsVector4(const TreeNode& node) const; /* @brief Check node for a type * * @param node The TreeNode to check * @return Optional value */ - OptionalMatrix IsMatrix( const TreeNode & node ) const; + OptionalMatrix IsMatrix(const TreeNode& node) const; /* @brief Check node for a type * * @param node The TreeNode to check * @return Optional value */ - OptionalMatrix3 IsMatrix3( const TreeNode & node ) const; + OptionalMatrix3 IsMatrix3(const TreeNode& node) const; /* @brief Check node for a type * * @param node The TreeNode to check * @return Optional value */ - OptionalRect IsRect( const TreeNode & node ) const; + OptionalRect IsRect(const TreeNode& node) const; /* @brief Check node for a type * * @param node The TreeNode to check * @return Optional value */ - OptionalExtents IsExtents( const TreeNode & node ) const; + OptionalExtents IsExtents(const TreeNode& node) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - OptionalString IsString( OptionalChild child ) const; + OptionalString IsString(OptionalChild child) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - OptionalFloat IsFloat( OptionalChild child ) const; + OptionalFloat IsFloat(OptionalChild child) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - OptionalBoolean IsBoolean( OptionalChild child ) const; + OptionalBoolean IsBoolean(OptionalChild child) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - OptionalInteger IsInteger( OptionalChild child ) const; + OptionalInteger IsInteger(OptionalChild child) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - OptionalVector2 IsVector2( OptionalChild child ) const; + OptionalVector2 IsVector2(OptionalChild child) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - OptionalVector3 IsVector3( OptionalChild child ) const; + OptionalVector3 IsVector3(OptionalChild child) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - OptionalVector4 IsVector4( OptionalChild child ) const; + OptionalVector4 IsVector4(OptionalChild child) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - OptionalMatrix IsMatrix( OptionalChild child ) const; + OptionalMatrix IsMatrix(OptionalChild child) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - OptionalMatrix3 IsMatrix3( OptionalChild child ) const; + OptionalMatrix3 IsMatrix3(OptionalChild child) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - OptionalRect IsRect( OptionalChild child ) const; + OptionalRect IsRect(OptionalChild child) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - bool IsMap( OptionalChild child, Property::Value& out ) const; + bool IsMap(OptionalChild child, Property::Value& out) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - bool IsArray( OptionalChild child, Property::Value& out ) const; + bool IsArray(OptionalChild child, Property::Value& out) const; /* @brief Check node for a type * * @param child The optional child TreeNode * @return Optional value */ - OptionalExtents IsExtents( OptionalChild child ) const; + OptionalExtents IsExtents(OptionalChild child) const; private: // Overriding map (overrides the default map). The map is not owned. @@ -249,11 +245,10 @@ private: // Replacement( const Replacement& copy ); // Returns the string if the node has a full replacement ie IMAGES if node is "{IMAGES}" - OptionalString HasFullReplacement( const TreeNode & node ) const; + OptionalString HasFullReplacement(const TreeNode& node) const; // Returns the property value for a full replacement from the maps - Property::Value GetFullReplacement( const std::string& replacementString ) const; - + Property::Value GetFullReplacement(const std::string& replacementString) const; }; } // namespace Internal diff --git a/dali-toolkit/internal/builder/style.cpp b/dali-toolkit/internal/builder/style.cpp index a5ced1b..b834b13 100644 --- a/dali-toolkit/internal/builder/style.cpp +++ b/dali-toolkit/internal/builder/style.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,70 +14,68 @@ * limitations under the License. */ -#include -#include -#include #include -#include #include #include +#include +#include +#include +#include namespace Dali { namespace Toolkit { - namespace Internal { - extern const Dali::Scripting::StringEnum ControlStateTable[]; -extern const unsigned int ControlStateTableCount; +extern const unsigned int ControlStateTableCount; StylePtr Style::New() { - StylePtr stylePtr( new Style() ); + StylePtr stylePtr(new Style()); return stylePtr; } void Style::ApplyVisualsAndPropertiesRecursively( - Handle handle, - const Dictionary& instancedProperties ) const + Handle handle, + const Dictionary& instancedProperties) const { - ApplyVisuals( handle, instancedProperties ); - ApplyProperties( handle ); + ApplyVisuals(handle, instancedProperties); + ApplyProperties(handle); Toolkit::Control control = Toolkit::Control::DownCast(handle); - if( control ) + if(control) { - std::string stateName; - Property::Value value = control.GetProperty(DevelControl::Property::STATE); + std::string stateName; + Property::Value value = control.GetProperty(DevelControl::Property::STATE); Dali::Toolkit::DevelControl::State state = static_cast(value.Get()); - stateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( state, ControlStateTable, ControlStateTableCount ); + stateName = Scripting::GetEnumerationName(state, ControlStateTable, ControlStateTableCount); - if( ! stateName.empty() ) + if(!stateName.empty()) { // Look up state in states table: - const StylePtr* stylePtr = subStates.FindConst( stateName ); - if( stylePtr ) + const StylePtr* stylePtr = subStates.FindConst(stateName); + if(stylePtr) { const StylePtr statePtr(*stylePtr); // We have a state match. - statePtr->ApplyVisuals( handle, instancedProperties ); - statePtr->ApplyProperties( handle ); + statePtr->ApplyVisuals(handle, instancedProperties); + statePtr->ApplyProperties(handle); // Apply substate visuals Property::Value value = control.GetProperty(DevelControl::Property::SUB_STATE); - std::string subStateName; - if( value.Get( subStateName ) && ! subStateName.empty() ) + std::string subStateName; + if(value.Get(subStateName) && !subStateName.empty()) { - const StylePtr* stylePtr = statePtr->subStates.FindConst( subStateName ); - if( stylePtr ) + const StylePtr* stylePtr = statePtr->subStates.FindConst(subStateName); + if(stylePtr) { const StylePtr subStatePtr(*stylePtr); // We have a sub-state match. - subStatePtr->ApplyVisuals( handle, instancedProperties ); - subStatePtr->ApplyProperties( handle ); + subStatePtr->ApplyVisuals(handle, instancedProperties); + subStatePtr->ApplyProperties(handle); } } } @@ -86,57 +84,57 @@ void Style::ApplyVisualsAndPropertiesRecursively( } void Style::ApplyVisuals( - Handle handle, - const Dictionary& instancedProperties ) const + Handle handle, + const Dictionary& instancedProperties) const { - ApplyVisuals( handle, visuals, instancedProperties ); + ApplyVisuals(handle, visuals, instancedProperties); } void Style::ApplyVisuals( - Handle handle, + Handle handle, const Dictionary& visualMaps, - const Dictionary& instancedProperties ) + const Dictionary& instancedProperties) { - for( Dictionary::iterator iter = visualMaps.Begin(); iter != visualMaps.End() ; ++iter ) + for(Dictionary::iterator iter = visualMaps.Begin(); iter != visualMaps.End(); ++iter) { - const std::string& visualName = (*iter).key; - Property::Map map = (*iter).entry; - Property::Map* instancedMap = instancedProperties.Find( visualName ); - ApplyVisual( handle, visualName, map, instancedMap ); + const std::string& visualName = (*iter).key; + Property::Map map = (*iter).entry; + Property::Map* instancedMap = instancedProperties.Find(visualName); + ApplyVisual(handle, visualName, map, instancedMap); } } void Style::ApplyVisual( - Handle handle, - const std::string& visualName, + Handle handle, + const std::string& visualName, const Property::Map& visualMap, - const Property::Map* instancedProperties ) + const Property::Map* instancedProperties) { // Check if this visual name is a valid property of handle - Dali::Property::Index index = handle.GetPropertyIndex( visualName ); - if( index != Property::INVALID_INDEX ) + Dali::Property::Index index = handle.GetPropertyIndex(visualName); + if(index != Property::INVALID_INDEX) { const Property::Map* applyMap = &visualMap; - Property::Map mergedMap; + Property::Map mergedMap; // If there are instanced properties, and the visual types match, // merge them into the visual map - if( instancedProperties ) + if(instancedProperties) { - Property::Value* instanceTypeValue = instancedProperties->Find( Toolkit::Visual::Property::TYPE); - Property::Value* newTypeValue = visualMap.Find( Toolkit::Visual::Property::TYPE, VISUAL_TYPE ); - if( instanceTypeValue && newTypeValue ) + Property::Value* instanceTypeValue = instancedProperties->Find(Toolkit::Visual::Property::TYPE); + Property::Value* newTypeValue = visualMap.Find(Toolkit::Visual::Property::TYPE, VISUAL_TYPE); + if(instanceTypeValue && newTypeValue) { - int instanceVisualType=-1; - int newVisualType=-1; - Scripting::GetEnumerationProperty( *instanceTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, instanceVisualType ); - Scripting::GetEnumerationProperty( *newTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, newVisualType ); + int instanceVisualType = -1; + int newVisualType = -1; + Scripting::GetEnumerationProperty(*instanceTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, instanceVisualType); + Scripting::GetEnumerationProperty(*newTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, newVisualType); - if( instanceVisualType == newVisualType ) + if(instanceVisualType == newVisualType) { // Same type - merge remaining instance data - mergedMap.Merge( visualMap ); - mergedMap.Merge( *instancedProperties ); + mergedMap.Merge(visualMap); + mergedMap.Merge(*instancedProperties); applyMap = &mergedMap; } } @@ -144,18 +142,18 @@ void Style::ApplyVisual( // Apply the visual property map to the handle const Property::Value value(const_cast(*applyMap)); - handle.SetProperty( index, value ); + handle.SetProperty(index, value); } } -void Style::ApplyProperties( Handle handle ) const +void Style::ApplyProperties(Handle handle) const { - for( Property::Map::SizeType i=0; i #include #include +#include namespace Dali { @@ -27,7 +27,6 @@ namespace Toolkit { namespace Internal { - class Style; typedef IntrusivePtr