[Tizen] Implement partial update
[platform/core/uifw/dali-core.git] / dali / internal / common / core-impl.cpp
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/common/core-impl.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/integration-api/core.h>
23 #include <dali/integration-api/debug.h>
24 #include <dali/integration-api/events/event.h>
25 #include <dali/integration-api/gl-sync-abstraction.h>
26 #include <dali/integration-api/gl-context-helper-abstraction.h>
27 #include <dali/integration-api/platform-abstraction.h>
28 #include <dali/integration-api/processor-interface.h>
29 #include <dali/integration-api/render-controller.h>
30 #include <dali/integration-api/render-surface.h>
31
32 #include <dali/internal/event/actors/actor-impl.h>
33 #include <dali/internal/event/animation/animation-playlist.h>
34 #include <dali/internal/event/common/notification-manager.h>
35 #include <dali/internal/event/common/property-notification-manager.h>
36 #include <dali/internal/event/common/stage-impl.h>
37 #include <dali/internal/event/common/thread-local-storage.h>
38 #include <dali/internal/event/common/event-thread-services.h>
39 #include <dali/internal/event/common/type-registry-impl.h>
40 #include <dali/internal/event/effects/shader-factory.h>
41 #include <dali/internal/event/events/event-processor.h>
42 #include <dali/internal/event/events/gesture-event-processor.h>
43 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
44 #include <dali/internal/event/size-negotiation/relayout-controller-impl.h>
45
46 #include <dali/internal/update/common/discard-queue.h>
47 #include <dali/internal/update/manager/update-manager.h>
48 #include <dali/internal/update/manager/render-task-processor.h>
49
50 #include <dali/internal/render/common/performance-monitor.h>
51 #include <dali/internal/render/common/render-manager.h>
52 #include <dali/internal/render/gl-resources/context.h>
53
54 using Dali::Internal::SceneGraph::UpdateManager;
55 using Dali::Internal::SceneGraph::RenderManager;
56 using Dali::Internal::SceneGraph::DiscardQueue;
57 using Dali::Internal::SceneGraph::RenderQueue;
58
59 namespace
60 {
61 // The Update for frame N+1 may be processed whilst frame N is being rendered.
62 const uint32_t MAXIMUM_UPDATE_COUNT = 2u;
63
64 #if defined(DEBUG_ENABLED)
65 Debug::Filter* gCoreFilter = Debug::Filter::New(Debug::Concise, false, "LOG_CORE");
66 #endif
67 }
68
69 namespace Dali
70 {
71
72 namespace Internal
73 {
74
75 using Integration::RenderController;
76 using Integration::PlatformAbstraction;
77 using Integration::GlSyncAbstraction;
78 using Integration::GlAbstraction;
79 using Integration::GlContextHelperAbstraction;
80 using Integration::Event;
81 using Integration::UpdateStatus;
82 using Integration::RenderStatus;
83
84 Core::Core( RenderController& renderController,
85             PlatformAbstraction& platform,
86             GlAbstraction& glAbstraction,
87             GlSyncAbstraction& glSyncAbstraction,
88             GlContextHelperAbstraction& glContextHelperAbstraction,
89             ResourcePolicy::DataRetention dataRetentionPolicy,
90             Integration::RenderToFrameBuffer renderToFboEnabled,
91             Integration::DepthBufferAvailable depthBufferAvailable,
92             Integration::StencilBufferAvailable stencilBufferAvailable,
93             Integration::PartialUpdateAvailable partialUpdateAvailable )
94 : mRenderController( renderController ),
95   mPlatform(platform),
96   mProcessingEvent(false),
97   mForceNextUpdate( false )
98 {
99   // Create the thread local storage
100   CreateThreadLocalStorage();
101
102   // This does nothing until Core is built with --enable-performance-monitor
103   PERFORMANCE_MONITOR_INIT( platform );
104
105   mNotificationManager = new NotificationManager();
106
107   mAnimationPlaylist = AnimationPlaylist::New();
108
109   mPropertyNotificationManager = PropertyNotificationManager::New();
110
111   mRenderTaskProcessor = new SceneGraph::RenderTaskProcessor();
112
113   mRenderManager = RenderManager::New( glAbstraction, glSyncAbstraction, glContextHelperAbstraction, depthBufferAvailable, stencilBufferAvailable, partialUpdateAvailable );
114
115   RenderQueue& renderQueue = mRenderManager->GetRenderQueue();
116
117   mDiscardQueue = new DiscardQueue( renderQueue );
118
119   mUpdateManager = new UpdateManager( *mNotificationManager,
120                                       *mAnimationPlaylist,
121                                       *mPropertyNotificationManager,
122                                       *mDiscardQueue,
123                                        renderController,
124                                       *mRenderManager,
125                                        renderQueue,
126                                       *mRenderTaskProcessor,
127                                        partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE );
128
129   mRenderManager->SetShaderSaver( *mUpdateManager );
130
131   mObjectRegistry = ObjectRegistry::New();
132
133   mStage = IntrusivePtr<Stage>( Stage::New( *mUpdateManager ) );
134
135   // This must be called after stage is created but before stage initialization
136   mRelayoutController = IntrusivePtr< RelayoutController >( new RelayoutController( mRenderController ) );
137
138   mGestureEventProcessor = new GestureEventProcessor( *mUpdateManager, mRenderController );
139
140   mShaderFactory = new ShaderFactory();
141   mUpdateManager->SetShaderSaver( *mShaderFactory );
142
143   GetImplementation(Dali::TypeRegistry::Get()).CallInitFunctions();
144 }
145
146 Core::~Core()
147 {
148   /*
149    * The order of destructing these singletons is important!!!
150    */
151
152   // clear the thread local storage first
153   // allows core to be created / deleted many times in the same thread (how TET cases work).
154   // Do this before mStage.Reset() so Stage::IsInstalled() returns false
155   ThreadLocalStorage* tls = ThreadLocalStorage::GetInternal();
156   if( tls )
157   {
158     tls->Remove();
159     delete tls;
160   }
161
162   mObjectRegistry.Reset();
163
164   // Stop relayout requests being raised on stage destruction
165   mRelayoutController.Reset();
166
167   // remove (last?) reference to stage
168   mStage.Reset();
169
170 }
171
172 void Core::Initialize()
173 {
174   mStage->Initialize( *mScenes[0] );
175 }
176
177 Integration::ContextNotifierInterface* Core::GetContextNotifier()
178 {
179   return mStage.Get();
180 }
181
182 void Core::RecoverFromContextLoss()
183 {
184   DALI_LOG_INFO(gCoreFilter, Debug::Verbose, "Core::RecoverFromContextLoss()\n");
185
186   mStage->GetRenderTaskList().RecoverFromContextLoss(); // Re-trigger render-tasks
187 }
188
189 void Core::ContextCreated()
190 {
191   mRenderManager->ContextCreated();
192 }
193
194 void Core::ContextDestroyed()
195 {
196   mRenderManager->ContextDestroyed();
197 }
198
199 void Core::SurfaceDeleted( Integration::RenderSurface* surface )
200 {
201   for( auto scene : mScenes )
202   {
203     if( scene->GetSurface() == surface )
204     {
205       scene->SurfaceDeleted();
206       break;
207     }
208   }
209 }
210
211 void Core::Update( float elapsedSeconds, uint32_t lastVSyncTimeMilliseconds, uint32_t nextVSyncTimeMilliseconds, Integration::UpdateStatus& status, bool renderToFboEnabled, bool isRenderingToFbo )
212 {
213   // set the time delta so adaptor can easily print FPS with a release build with 0 as
214   // it is cached by frametime
215   status.secondsFromLastFrame = elapsedSeconds;
216
217   // Render returns true when there are updates on the stage or one or more animations are completed.
218   // Use the estimated time diff till we render as the elapsed time.
219   status.keepUpdating = mUpdateManager->Update( elapsedSeconds,
220                                                 lastVSyncTimeMilliseconds,
221                                                 nextVSyncTimeMilliseconds,
222                                                 renderToFboEnabled,
223                                                 isRenderingToFbo );
224
225   // Check the Notification Manager message queue to set needsNotification
226   status.needsNotification = mNotificationManager->MessagesToProcess();
227
228   // Check if the default surface is changed
229   status.surfaceRectChanged = mUpdateManager->IsDefaultSurfaceRectChanged();
230
231   // No need to keep update running if there are notifications to process.
232   // Any message to update will wake it up anyways
233 }
234
235 void Core::Render( RenderStatus& status, bool forceClear, bool uploadOnly )
236 {
237   mRenderManager->Render( status, forceClear, uploadOnly );
238 }
239
240 void Core::SceneCreated()
241 {
242   mStage->EmitSceneCreatedSignal();
243
244   mRelayoutController->OnApplicationSceneCreated();
245
246   for( auto iter = mScenes.begin(); iter != mScenes.end(); ++iter )
247   {
248     Dali::Actor sceneRootLayer = (*iter)->GetRootLayer();
249     mRelayoutController->RequestRelayoutTree( sceneRootLayer );
250   }
251 }
252
253 void Core::QueueEvent( const Integration::Event& event )
254 {
255   if (mScenes.size() != 0)
256   {
257     mScenes.front()->QueueEvent( event );
258   }
259 }
260
261 void Core::ProcessEvents()
262 {
263   // Guard against calls to ProcessEvents() during ProcessEvents()
264   if( mProcessingEvent )
265   {
266     DALI_LOG_ERROR( "ProcessEvents should not be called from within ProcessEvents!\n" );
267     mRenderController.RequestProcessEventsOnIdle( false );
268     return;
269   }
270
271   mProcessingEvent = true;
272   mRelayoutController->SetProcessingCoreEvents( true );
273
274   // Signal that any messages received will be flushed soon
275   mUpdateManager->EventProcessingStarted();
276
277   // Scene could be added or removed while processing the events
278   // Copy the Scene container locally to avoid possibly invalid iterator
279   SceneContainer scenes = mScenes;
280
281   // process events in all scenes
282   for( auto scene : scenes )
283   {
284     scene->ProcessEvents();
285   }
286
287   mNotificationManager->ProcessMessages();
288
289   // Emit signal here to inform listeners that event processing has finished.
290   for( auto scene : scenes )
291   {
292     scene->EmitEventProcessingFinishedSignal();
293   }
294
295   // Run any registered processors
296   RunProcessors();
297
298   // Run the size negotiation after event processing finished signal
299   mRelayoutController->Relayout();
300
301   // Rebuild depth tree after event processing has finished
302   for( auto scene : scenes )
303   {
304     scene->RebuildDepthTree();
305   }
306
307   // Flush any queued messages for the update-thread
308   const bool messagesToProcess = mUpdateManager->FlushQueue();
309
310   // Check if the touch or gestures require updates.
311   const bool gestureNeedsUpdate = mGestureEventProcessor->NeedsUpdate();
312   // Check if the next update is forced.
313   const bool forceUpdate = IsNextUpdateForced();
314
315   if( messagesToProcess || gestureNeedsUpdate || forceUpdate )
316   {
317     // tell the render controller to keep update thread running
318     mRenderController.RequestUpdate( forceUpdate );
319   }
320
321   mRelayoutController->SetProcessingCoreEvents( false );
322
323   // ProcessEvents() may now be called again
324   mProcessingEvent = false;
325 }
326
327 uint32_t Core::GetMaximumUpdateCount() const
328 {
329   return MAXIMUM_UPDATE_COUNT;
330 }
331
332 void Core::RegisterProcessor( Integration::Processor& processor )
333 {
334   mProcessors.PushBack(&processor);
335 }
336
337 void Core::UnregisterProcessor( Integration::Processor& processor )
338 {
339   auto iter = std::find( mProcessors.Begin(), mProcessors.End(), &processor );
340   if( iter != mProcessors.End() )
341   {
342     mProcessors.Erase( iter );
343   }
344 }
345
346 void Core::RunProcessors()
347 {
348   // Copy processor pointers to prevent changes to vector affecting loop iterator.
349   Dali::Vector<Integration::Processor*> processors( mProcessors );
350
351   for( auto processor : processors )
352   {
353     if( processor )
354     {
355       processor->Process();
356     }
357   }
358 }
359
360 StagePtr Core::GetCurrentStage()
361 {
362   return mStage.Get();
363 }
364
365 PlatformAbstraction& Core::GetPlatform()
366 {
367   return mPlatform;
368 }
369
370 UpdateManager& Core::GetUpdateManager()
371 {
372   return *(mUpdateManager);
373 }
374
375 RenderManager& Core::GetRenderManager()
376 {
377   return *(mRenderManager);
378 }
379
380 NotificationManager& Core::GetNotificationManager()
381 {
382   return *(mNotificationManager);
383 }
384
385 ShaderFactory& Core::GetShaderFactory()
386 {
387   return *(mShaderFactory);
388 }
389
390 GestureEventProcessor& Core::GetGestureEventProcessor()
391 {
392   return *(mGestureEventProcessor);
393 }
394
395 RelayoutController& Core::GetRelayoutController()
396 {
397   return *(mRelayoutController.Get());
398 }
399
400 ObjectRegistry& Core::GetObjectRegistry() const
401 {
402   return *(mObjectRegistry.Get());
403 }
404
405 EventThreadServices& Core::GetEventThreadServices()
406 {
407   return *this;
408 }
409
410 PropertyNotificationManager& Core::GetPropertyNotificationManager() const
411 {
412   return *(mPropertyNotificationManager);
413 }
414
415 AnimationPlaylist& Core::GetAnimationPlaylist() const
416 {
417   return *(mAnimationPlaylist);
418 }
419
420 void Core::AddScene( Scene* scene )
421 {
422   mScenes.push_back( scene );
423 }
424
425 void Core::RemoveScene( Scene* scene )
426 {
427   auto iter = std::find( mScenes.begin(), mScenes.end(), scene );
428   if( iter != mScenes.end() )
429   {
430     mScenes.erase( iter );
431   }
432 }
433
434 void Core::CreateThreadLocalStorage()
435 {
436   // a pointer to the ThreadLocalStorage object will be stored in TLS
437   // The ThreadLocalStorage object should be deleted by the Core destructor
438   new ThreadLocalStorage(this);
439 }
440
441 void Core::RegisterObject( Dali::BaseObject* object )
442 {
443   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
444   mObjectRegistry->RegisterObject( object );
445 }
446
447 void Core::UnregisterObject( Dali::BaseObject* object )
448 {
449   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
450   mObjectRegistry->UnregisterObject( object );
451 }
452
453 Integration::RenderController& Core::GetRenderController()
454 {
455   return mRenderController;
456 }
457
458 uint32_t* Core::ReserveMessageSlot( uint32_t size, bool updateScene )
459 {
460   return mUpdateManager->ReserveMessageSlot( size, updateScene );
461 }
462
463 BufferIndex Core::GetEventBufferIndex() const
464 {
465   return mUpdateManager->GetEventBufferIndex();
466 }
467
468 void Core::ForceNextUpdate()
469 {
470   mForceNextUpdate = true;
471 }
472
473 bool Core::IsNextUpdateForced()
474 {
475   bool nextUpdateForced = mForceNextUpdate;
476   mForceNextUpdate = false;
477   return nextUpdateForced;
478 }
479
480 } // namespace Internal
481
482 } // namespace Dali