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