Merge "Clean up the code to build successfully on macOS" into devel/master
[platform/core/uifw/dali-core.git] / dali / internal / common / core-impl.cpp
1 /*
2  * Copyright (c) 2020 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
31 #include <dali/internal/event/actors/actor-impl.h>
32 #include <dali/internal/event/animation/animation-playlist.h>
33 #include <dali/internal/event/common/notification-manager.h>
34 #include <dali/internal/event/common/property-notification-manager.h>
35 #include <dali/internal/event/common/stage-impl.h>
36 #include <dali/internal/event/common/thread-local-storage.h>
37 #include <dali/internal/event/common/event-thread-services.h>
38 #include <dali/internal/event/common/type-registry-impl.h>
39 #include <dali/internal/event/effects/shader-factory.h>
40 #include <dali/internal/event/events/event-processor.h>
41 #include <dali/internal/event/events/gesture-event-processor.h>
42 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
43 #include <dali/internal/event/size-negotiation/relayout-controller-impl.h>
44
45 #include <dali/internal/update/common/discard-queue.h>
46 #include <dali/internal/update/manager/update-manager.h>
47 #include <dali/internal/update/manager/render-task-processor.h>
48
49 #include <dali/internal/render/common/performance-monitor.h>
50 #include <dali/internal/render/common/render-manager.h>
51 #include <dali/internal/render/gl-resources/context.h>
52
53 using Dali::Internal::SceneGraph::UpdateManager;
54 using Dali::Internal::SceneGraph::RenderManager;
55 using Dali::Internal::SceneGraph::DiscardQueue;
56 using Dali::Internal::SceneGraph::RenderQueue;
57
58 namespace
59 {
60 // The Update for frame N+1 may be processed whilst frame N is being rendered.
61 const uint32_t MAXIMUM_UPDATE_COUNT = 2u;
62
63 #if defined(DEBUG_ENABLED)
64 Debug::Filter* gCoreFilter = Debug::Filter::New(Debug::Concise, false, "LOG_CORE");
65 #endif
66 }
67
68 namespace Dali
69 {
70
71 namespace Internal
72 {
73
74 using Integration::RenderController;
75 using Integration::PlatformAbstraction;
76 using Integration::GlSyncAbstraction;
77 using Integration::GlAbstraction;
78 using Integration::GlContextHelperAbstraction;
79 using Integration::Event;
80 using Integration::UpdateStatus;
81 using Integration::RenderStatus;
82
83 Core::Core( RenderController& renderController,
84             PlatformAbstraction& platform,
85             GlAbstraction& glAbstraction,
86             GlSyncAbstraction& glSyncAbstraction,
87             GlContextHelperAbstraction& glContextHelperAbstraction,
88             Integration::RenderToFrameBuffer renderToFboEnabled,
89             Integration::DepthBufferAvailable depthBufferAvailable,
90             Integration::StencilBufferAvailable stencilBufferAvailable,
91             Integration::PartialUpdateAvailable partialUpdateAvailable )
92 : mRenderController( renderController ),
93   mPlatform(platform),
94   mGlAbstraction(glAbstraction),
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, partialUpdateAvailable );
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     tls->Unreference();
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::Update( float elapsedSeconds, uint32_t lastVSyncTimeMilliseconds, uint32_t nextVSyncTimeMilliseconds, Integration::UpdateStatus& status, bool renderToFboEnabled, bool isRenderingToFbo )
198 {
199   // set the time delta so adaptor can easily print FPS with a release build with 0 as
200   // it is cached by frametime
201   status.secondsFromLastFrame = elapsedSeconds;
202
203   // Render returns true when there are updates on the stage or one or more animations are completed.
204   // Use the estimated time diff till we render as the elapsed time.
205   status.keepUpdating = mUpdateManager->Update( elapsedSeconds,
206                                                 lastVSyncTimeMilliseconds,
207                                                 nextVSyncTimeMilliseconds,
208                                                 renderToFboEnabled,
209                                                 isRenderingToFbo );
210
211   // Check the Notification Manager message queue to set needsNotification
212   status.needsNotification = mNotificationManager->MessagesToProcess();
213
214   // Check if the default surface is changed
215   status.surfaceRectChanged = mUpdateManager->IsDefaultSurfaceRectChanged();
216
217   // No need to keep update running if there are notifications to process.
218   // Any message to update will wake it up anyways
219 }
220
221 void Core::PreRender( RenderStatus& status, bool forceClear, bool uploadOnly )
222 {
223   mRenderManager->PreRender( status, forceClear, uploadOnly );
224 }
225
226 void Core::PreRender( Integration::Scene& scene, std::vector<Rect<int>>& damagedRects )
227 {
228   mRenderManager->PreRender( scene, damagedRects );
229 }
230
231 void Core::RenderScene( RenderStatus& status, Integration::Scene& scene, bool renderToFbo )
232 {
233   mRenderManager->RenderScene( status, scene, renderToFbo );
234 }
235
236 void Core::RenderScene( RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect )
237 {
238   mRenderManager->RenderScene( status, scene, renderToFbo, clippingRect );
239 }
240
241 void Core::PostRender( bool uploadOnly )
242 {
243   mRenderManager->PostRender( uploadOnly );
244 }
245
246 void Core::SceneCreated()
247 {
248   mStage->EmitSceneCreatedSignal();
249
250   mRelayoutController->OnApplicationSceneCreated();
251
252   for( const auto& scene : mScenes )
253   {
254     Dali::Actor sceneRootLayer = scene->GetRootLayer();
255     mRelayoutController->RequestRelayoutTree( sceneRootLayer );
256   }
257 }
258
259 void Core::QueueEvent( const Integration::Event& event )
260 {
261   if (mScenes.size() != 0)
262   {
263     mScenes.front()->QueueEvent( event );
264   }
265 }
266
267 void Core::ProcessEvents()
268 {
269   // Guard against calls to ProcessEvents() during ProcessEvents()
270   if( mProcessingEvent )
271   {
272     DALI_LOG_ERROR( "ProcessEvents should not be called from within ProcessEvents!\n" );
273     mRenderController.RequestProcessEventsOnIdle( false );
274     return;
275   }
276
277   mProcessingEvent = true;
278   mRelayoutController->SetProcessingCoreEvents( true );
279
280   // Signal that any messages received will be flushed soon
281   mUpdateManager->EventProcessingStarted();
282
283   // Scene could be added or removed while processing the events
284   // Copy the Scene container locally to avoid possibly invalid iterator
285   SceneContainer scenes = mScenes;
286
287   // process events in all scenes
288   for( auto scene : scenes )
289   {
290     scene->ProcessEvents();
291   }
292
293   mNotificationManager->ProcessMessages();
294
295   // Emit signal here to inform listeners that event processing has finished.
296   for( auto scene : scenes )
297   {
298     scene->EmitEventProcessingFinishedSignal();
299   }
300
301   // Run any registered processors
302   RunProcessors();
303
304   // Run the size negotiation after event processing finished signal
305   mRelayoutController->Relayout();
306
307   // Rebuild depth tree after event processing has finished
308   for( auto scene : scenes )
309   {
310     scene->RebuildDepthTree();
311   }
312
313   // Flush any queued messages for the update-thread
314   const bool messagesToProcess = mUpdateManager->FlushQueue();
315
316   // Check if the touch or gestures require updates.
317   const bool gestureNeedsUpdate = mGestureEventProcessor->NeedsUpdate();
318   // Check if the next update is forced.
319   const bool forceUpdate = IsNextUpdateForced();
320
321   if( messagesToProcess || gestureNeedsUpdate || forceUpdate )
322   {
323     // tell the render controller to keep update thread running
324     mRenderController.RequestUpdate( forceUpdate );
325   }
326
327   mRelayoutController->SetProcessingCoreEvents( false );
328
329   // ProcessEvents() may now be called again
330   mProcessingEvent = false;
331 }
332
333 uint32_t Core::GetMaximumUpdateCount() const
334 {
335   return MAXIMUM_UPDATE_COUNT;
336 }
337
338 void Core::RegisterProcessor( Integration::Processor& processor )
339 {
340   mProcessors.PushBack(&processor);
341 }
342
343 void Core::UnregisterProcessor( Integration::Processor& processor )
344 {
345   auto iter = std::find( mProcessors.Begin(), mProcessors.End(), &processor );
346   if( iter != mProcessors.End() )
347   {
348     mProcessors.Erase( iter );
349   }
350 }
351
352 void Core::RunProcessors()
353 {
354   // Copy processor pointers to prevent changes to vector affecting loop iterator.
355   Dali::Vector<Integration::Processor*> processors( mProcessors );
356
357   for( auto processor : processors )
358   {
359     if( processor )
360     {
361       processor->Process();
362     }
363   }
364 }
365
366 StagePtr Core::GetCurrentStage()
367 {
368   return mStage.Get();
369 }
370
371 PlatformAbstraction& Core::GetPlatform()
372 {
373   return mPlatform;
374 }
375
376 UpdateManager& Core::GetUpdateManager()
377 {
378   return *(mUpdateManager);
379 }
380
381 RenderManager& Core::GetRenderManager()
382 {
383   return *(mRenderManager);
384 }
385
386 NotificationManager& Core::GetNotificationManager()
387 {
388   return *(mNotificationManager);
389 }
390
391 ShaderFactory& Core::GetShaderFactory()
392 {
393   return *(mShaderFactory);
394 }
395
396 GestureEventProcessor& Core::GetGestureEventProcessor()
397 {
398   return *(mGestureEventProcessor);
399 }
400
401 RelayoutController& Core::GetRelayoutController()
402 {
403   return *(mRelayoutController.Get());
404 }
405
406 ObjectRegistry& Core::GetObjectRegistry() const
407 {
408   return *(mObjectRegistry.Get());
409 }
410
411 EventThreadServices& Core::GetEventThreadServices()
412 {
413   return *this;
414 }
415
416 PropertyNotificationManager& Core::GetPropertyNotificationManager() const
417 {
418   return *(mPropertyNotificationManager);
419 }
420
421 AnimationPlaylist& Core::GetAnimationPlaylist() const
422 {
423   return *(mAnimationPlaylist);
424 }
425
426 Integration::GlAbstraction& Core::GetGlAbstraction() const
427 {
428   return mGlAbstraction;
429 }
430
431 void Core::AddScene( Scene* scene )
432 {
433   mScenes.push_back( scene );
434 }
435
436 void Core::RemoveScene( Scene* scene )
437 {
438   auto iter = std::find( mScenes.begin(), mScenes.end(), scene );
439   if( iter != mScenes.end() )
440   {
441     mScenes.erase( iter );
442   }
443 }
444
445 void Core::CreateThreadLocalStorage()
446 {
447   // a pointer to the ThreadLocalStorage object will be stored in TLS
448   // The ThreadLocalStorage object should be deleted by the Core destructor
449   ThreadLocalStorage* tls = new ThreadLocalStorage(this);
450   tls->Reference();
451 }
452
453 void Core::RegisterObject( Dali::BaseObject* object )
454 {
455   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
456   mObjectRegistry->RegisterObject( object );
457 }
458
459 void Core::UnregisterObject( Dali::BaseObject* object )
460 {
461   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
462   mObjectRegistry->UnregisterObject( object );
463 }
464
465 Integration::RenderController& Core::GetRenderController()
466 {
467   return mRenderController;
468 }
469
470 uint32_t* Core::ReserveMessageSlot( uint32_t size, bool updateScene )
471 {
472   return mUpdateManager->ReserveMessageSlot( size, updateScene );
473 }
474
475 BufferIndex Core::GetEventBufferIndex() const
476 {
477   return mUpdateManager->GetEventBufferIndex();
478 }
479
480 void Core::ForceNextUpdate()
481 {
482   mForceNextUpdate = true;
483 }
484
485 bool Core::IsNextUpdateForced()
486 {
487   bool nextUpdateForced = mForceNextUpdate;
488   mForceNextUpdate = false;
489   return nextUpdateForced;
490 }
491
492 } // namespace Internal
493
494 } // namespace Dali