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