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