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