[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
128   mRenderManager->SetShaderSaver( *mUpdateManager );
129
130   mObjectRegistry = ObjectRegistry::New();
131
132   mStage = IntrusivePtr<Stage>( Stage::New( *mUpdateManager ) );
133
134   // This must be called after stage is created but before stage initialization
135   mRelayoutController = IntrusivePtr< RelayoutController >( new RelayoutController( mRenderController ) );
136
137   mGestureEventProcessor = new GestureEventProcessor( *mUpdateManager, mRenderController );
138
139   mShaderFactory = new ShaderFactory();
140   mUpdateManager->SetShaderSaver( *mShaderFactory );
141
142   GetImplementation(Dali::TypeRegistry::Get()).CallInitFunctions();
143 }
144
145 Core::~Core()
146 {
147   /*
148    * The order of destructing these singletons is important!!!
149    */
150
151   // clear the thread local storage first
152   // allows core to be created / deleted many times in the same thread (how TET cases work).
153   // Do this before mStage.Reset() so Stage::IsInstalled() returns false
154   ThreadLocalStorage* tls = ThreadLocalStorage::GetInternal();
155   if( tls )
156   {
157     tls->Remove();
158     delete tls;
159   }
160
161   mObjectRegistry.Reset();
162
163   // Stop relayout requests being raised on stage destruction
164   mRelayoutController.Reset();
165
166   // remove (last?) reference to stage
167   mStage.Reset();
168
169 }
170
171 void Core::Initialize()
172 {
173   mStage->Initialize( *mScenes[0] );
174 }
175
176 Integration::ContextNotifierInterface* Core::GetContextNotifier()
177 {
178   return mStage.Get();
179 }
180
181 void Core::RecoverFromContextLoss()
182 {
183   DALI_LOG_INFO(gCoreFilter, Debug::Verbose, "Core::RecoverFromContextLoss()\n");
184
185   mStage->GetRenderTaskList().RecoverFromContextLoss(); // Re-trigger render-tasks
186 }
187
188 void Core::ContextCreated()
189 {
190   mRenderManager->ContextCreated();
191 }
192
193 void Core::ContextDestroyed()
194 {
195   mRenderManager->ContextDestroyed();
196 }
197
198 void Core::SurfaceDeleted( Integration::RenderSurface* surface )
199 {
200   for( auto scene : mScenes )
201   {
202     if( scene->GetSurface() == surface )
203     {
204       scene->SurfaceDeleted();
205       break;
206     }
207   }
208 }
209
210 void Core::Update( float elapsedSeconds, uint32_t lastVSyncTimeMilliseconds, uint32_t nextVSyncTimeMilliseconds, Integration::UpdateStatus& status, bool renderToFboEnabled, bool isRenderingToFbo )
211 {
212   // set the time delta so adaptor can easily print FPS with a release build with 0 as
213   // it is cached by frametime
214   status.secondsFromLastFrame = elapsedSeconds;
215
216   // Render returns true when there are updates on the stage or one or more animations are completed.
217   // Use the estimated time diff till we render as the elapsed time.
218   status.keepUpdating = mUpdateManager->Update( elapsedSeconds,
219                                                 lastVSyncTimeMilliseconds,
220                                                 nextVSyncTimeMilliseconds,
221                                                 renderToFboEnabled,
222                                                 isRenderingToFbo );
223
224   // Check the Notification Manager message queue to set needsNotification
225   status.needsNotification = mNotificationManager->MessagesToProcess();
226
227   // Check if the default surface is changed
228   status.surfaceRectChanged = mUpdateManager->IsDefaultSurfaceRectChanged();
229
230   // No need to keep update running if there are notifications to process.
231   // Any message to update will wake it up anyways
232 }
233
234 void Core::Render( RenderStatus& status, bool forceClear )
235 {
236   mRenderManager->Render( status, forceClear );
237 }
238
239 void Core::SceneCreated()
240 {
241   mStage->EmitSceneCreatedSignal();
242
243   mRelayoutController->OnApplicationSceneCreated();
244
245   for( auto iter = mScenes.begin(); iter != mScenes.end(); ++iter )
246   {
247     Dali::Actor sceneRootLayer = (*iter)->GetRootLayer();
248     mRelayoutController->RequestRelayoutTree( sceneRootLayer );
249   }
250 }
251
252 void Core::QueueEvent( const Integration::Event& event )
253 {
254   if (mScenes.size() != 0)
255   {
256     mScenes.front()->QueueEvent( event );
257   }
258 }
259
260 void Core::ProcessEvents()
261 {
262   // Guard against calls to ProcessEvents() during ProcessEvents()
263   if( mProcessingEvent )
264   {
265     DALI_LOG_ERROR( "ProcessEvents should not be called from within ProcessEvents!\n" );
266     mRenderController.RequestProcessEventsOnIdle( false );
267     return;
268   }
269
270   mProcessingEvent = true;
271   mRelayoutController->SetProcessingCoreEvents( true );
272
273   // Signal that any messages received will be flushed soon
274   mUpdateManager->EventProcessingStarted();
275
276   // Scene could be added or removed while processing the events
277   // Copy the Scene container locally to avoid possibly invalid iterator
278   SceneContainer scenes = mScenes;
279
280   // process events in all scenes
281   for( auto scene : scenes )
282   {
283     scene->ProcessEvents();
284   }
285
286   mNotificationManager->ProcessMessages();
287
288   // Emit signal here to inform listeners that event processing has finished.
289   for( auto scene : scenes )
290   {
291     scene->EmitEventProcessingFinishedSignal();
292   }
293
294   // Run any registered processors
295   RunProcessors();
296
297   // Run the size negotiation after event processing finished signal
298   mRelayoutController->Relayout();
299
300   // Rebuild depth tree after event processing has finished
301   for( auto scene : scenes )
302   {
303     scene->RebuildDepthTree();
304   }
305
306   // Flush any queued messages for the update-thread
307   const bool messagesToProcess = mUpdateManager->FlushQueue();
308
309   // Check if the touch or gestures require updates.
310   const bool gestureNeedsUpdate = mGestureEventProcessor->NeedsUpdate();
311   // Check if the next update is forced.
312   const bool forceUpdate = IsNextUpdateForced();
313
314   if( messagesToProcess || gestureNeedsUpdate || forceUpdate )
315   {
316     // tell the render controller to keep update thread running
317     mRenderController.RequestUpdate( forceUpdate );
318   }
319
320   mRelayoutController->SetProcessingCoreEvents( false );
321
322   // ProcessEvents() may now be called again
323   mProcessingEvent = false;
324 }
325
326 uint32_t Core::GetMaximumUpdateCount() const
327 {
328   return MAXIMUM_UPDATE_COUNT;
329 }
330
331 void Core::RegisterProcessor( Integration::Processor& processor )
332 {
333   mProcessors.PushBack(&processor);
334 }
335
336 void Core::UnregisterProcessor( Integration::Processor& processor )
337 {
338   auto iter = std::find( mProcessors.Begin(), mProcessors.End(), &processor );
339   if( iter != mProcessors.End() )
340   {
341     mProcessors.Erase( iter );
342   }
343 }
344
345 void Core::RunProcessors()
346 {
347   // Copy processor pointers to prevent changes to vector affecting loop iterator.
348   Dali::Vector<Integration::Processor*> processors( mProcessors );
349
350   for( auto processor : processors )
351   {
352     if( processor )
353     {
354       processor->Process();
355     }
356   }
357 }
358
359 StagePtr Core::GetCurrentStage()
360 {
361   return mStage.Get();
362 }
363
364 PlatformAbstraction& Core::GetPlatform()
365 {
366   return mPlatform;
367 }
368
369 UpdateManager& Core::GetUpdateManager()
370 {
371   return *(mUpdateManager);
372 }
373
374 RenderManager& Core::GetRenderManager()
375 {
376   return *(mRenderManager);
377 }
378
379 NotificationManager& Core::GetNotificationManager()
380 {
381   return *(mNotificationManager);
382 }
383
384 ShaderFactory& Core::GetShaderFactory()
385 {
386   return *(mShaderFactory);
387 }
388
389 GestureEventProcessor& Core::GetGestureEventProcessor()
390 {
391   return *(mGestureEventProcessor);
392 }
393
394 RelayoutController& Core::GetRelayoutController()
395 {
396   return *(mRelayoutController.Get());
397 }
398
399 ObjectRegistry& Core::GetObjectRegistry() const
400 {
401   return *(mObjectRegistry.Get());
402 }
403
404 EventThreadServices& Core::GetEventThreadServices()
405 {
406   return *this;
407 }
408
409 PropertyNotificationManager& Core::GetPropertyNotificationManager() const
410 {
411   return *(mPropertyNotificationManager);
412 }
413
414 AnimationPlaylist& Core::GetAnimationPlaylist() const
415 {
416   return *(mAnimationPlaylist);
417 }
418
419 void Core::AddScene( Scene* scene )
420 {
421   mScenes.push_back( scene );
422 }
423
424 void Core::RemoveScene( Scene* scene )
425 {
426   auto iter = std::find( mScenes.begin(), mScenes.end(), scene );
427   if( iter != mScenes.end() )
428   {
429     mScenes.erase( iter );
430   }
431 }
432
433 void Core::CreateThreadLocalStorage()
434 {
435   // a pointer to the ThreadLocalStorage object will be stored in TLS
436   // The ThreadLocalStorage object should be deleted by the Core destructor
437   new ThreadLocalStorage(this);
438 }
439
440 void Core::RegisterObject( Dali::BaseObject* object )
441 {
442   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
443   mObjectRegistry->RegisterObject( object );
444 }
445
446 void Core::UnregisterObject( Dali::BaseObject* object )
447 {
448   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
449   mObjectRegistry->UnregisterObject( object );
450 }
451
452 Integration::RenderController& Core::GetRenderController()
453 {
454   return mRenderController;
455 }
456
457 uint32_t* Core::ReserveMessageSlot( uint32_t size, bool updateScene )
458 {
459   return mUpdateManager->ReserveMessageSlot( size, updateScene );
460 }
461
462 BufferIndex Core::GetEventBufferIndex() const
463 {
464   return mUpdateManager->GetEventBufferIndex();
465 }
466
467 void Core::ForceNextUpdate()
468 {
469   mForceNextUpdate = true;
470 }
471
472 bool Core::IsNextUpdateForced()
473 {
474   bool nextUpdateForced = mForceNextUpdate;
475   mForceNextUpdate = false;
476   return nextUpdateForced;
477 }
478
479 } // namespace Internal
480
481 } // namespace Dali