[Tizen] Apply precompile shader
[platform/core/uifw/dali-core.git] / dali / internal / common / core-impl.cpp
1 /*
2  * Copyright (c) 2023 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 #include <dali/integration-api/trace.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::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 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_PERFORMANCE_MARKER, false);
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::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   mProcessorUnregistered(false),
93   mPostProcessorUnregistered(false),
94   mRelayoutFlush(false)
95 {
96   // Create the thread local storage
97   CreateThreadLocalStorage();
98
99   // This does nothing until Core is built with --enable-performance-monitor
100   PERFORMANCE_MONITOR_INIT(platform);
101
102   mNotificationManager = new NotificationManager();
103
104   mAnimationPlaylist = AnimationPlaylist::New();
105
106   mPropertyNotificationManager = PropertyNotificationManager::New();
107
108   mRenderTaskProcessor = new SceneGraph::RenderTaskProcessor();
109
110   mRenderManager = RenderManager::New(graphicsController, depthBufferAvailable, stencilBufferAvailable, partialUpdateAvailable);
111
112   RenderQueue& renderQueue = mRenderManager->GetRenderQueue();
113
114   mUpdateManager = new UpdateManager(*mNotificationManager,
115                                      *mAnimationPlaylist,
116                                      *mPropertyNotificationManager,
117                                      renderController,
118                                      *mRenderManager,
119                                      renderQueue,
120                                      *mRenderTaskProcessor);
121
122   mRenderManager->SetShaderSaver(*mUpdateManager);
123
124   mObjectRegistry = ObjectRegistry::New();
125
126   mStage = IntrusivePtr<Stage>(Stage::New(*mUpdateManager));
127
128   // This must be called after stage is created but before stage initialization
129   mRelayoutController = IntrusivePtr<RelayoutController>(new RelayoutController(mRenderController));
130
131   mGestureEventProcessor = new GestureEventProcessor(*mUpdateManager, mRenderController);
132
133   mShaderFactory = new ShaderFactory();
134   mUpdateManager->SetShaderSaver(*mShaderFactory);
135
136   GetImplementation(Dali::TypeRegistry::Get()).CallInitFunctions();
137
138   DALI_LOG_RELEASE_INFO("Node size: %lu\n", sizeof(Dali::Internal::SceneGraph::Node));
139   DALI_LOG_RELEASE_INFO("Renderer size: %lu\n", sizeof(Dali::Internal::SceneGraph::Renderer));
140   DALI_LOG_RELEASE_INFO("RenderItem size: %lu\n", sizeof(Dali::Internal::SceneGraph::RenderItem));
141 }
142
143 Core::~Core()
144 {
145   /*
146    * The order of destructing these singletons is important!!!
147    */
148
149   // clear the thread local storage first
150   // allows core to be created / deleted many times in the same thread (how TET cases work).
151   // Do this before mStage.Reset() so Stage::IsInstalled() returns false
152   ThreadLocalStorage* tls = ThreadLocalStorage::GetInternal();
153   if(tls)
154   {
155     tls->Remove();
156     tls->Unreference();
157   }
158
159   mObjectRegistry.Reset();
160
161   // Stop relayout requests being raised on stage destruction
162   mRelayoutController.Reset();
163
164   // remove (last?) reference to stage
165   mStage.Reset();
166 }
167
168 void Core::Initialize()
169 {
170   mStage->Initialize(*mScenes[0]);
171 }
172
173 Integration::ContextNotifierInterface* Core::GetContextNotifier()
174 {
175   return mStage.Get();
176 }
177
178 void Core::RecoverFromContextLoss()
179 {
180   DALI_LOG_INFO(gCoreFilter, Debug::Verbose, "Core::RecoverFromContextLoss()\n");
181
182   mStage->GetRenderTaskList().RecoverFromContextLoss(); // Re-trigger render-tasks
183 }
184
185 void Core::ContextCreated()
186 {
187 }
188
189 void Core::ContextDestroyed()
190 {
191 }
192
193 void Core::Update(float elapsedSeconds, uint32_t lastVSyncTimeMilliseconds, uint32_t nextVSyncTimeMilliseconds, Integration::UpdateStatus& status, bool renderToFboEnabled, bool isRenderingToFbo, bool uploadOnly)
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                                                uploadOnly);
207
208   // Check the Notification Manager message queue to set needsNotification
209   status.needsNotification = mNotificationManager->MessagesToProcess();
210
211   // No need to keep update running if there are notifications to process.
212   // Any message to update will wake it up anyways
213 }
214
215 void Core::PreRender(RenderStatus& status, bool forceClear)
216 {
217   mRenderManager->PreRender(status, forceClear);
218 }
219
220 void Core::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
221 {
222   mRenderManager->PreRender(scene, damagedRects);
223 }
224
225 void Core::RenderScene(RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
226 {
227   mRenderManager->RenderScene(status, scene, renderToFbo);
228 }
229
230 void Core::RenderScene(RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
231 {
232   mRenderManager->RenderScene(status, scene, renderToFbo, clippingRect);
233 }
234
235 void Core::PreCompileShader(const std::string& vertexShader, const std::string& fragmentShader)
236 {
237   mRenderManager->PreCompileShader(vertexShader, fragmentShader);
238 }
239
240 void Core::PostRender()
241 {
242   mUpdateManager->PostRender();
243   mRenderManager->PostRender();
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::ForceRelayout()
268 {
269   if(mRelayoutFlush)
270   {
271     DALI_LOG_ERROR("ForceRelayout should not be called from within RelayoutAndFlush!\n");
272     return;
273   }
274
275   // Scene could be added or removed while processing the events
276   // Copy the Scene container locally to avoid possibly invalid iterator
277   SceneContainer scenes = mScenes;
278
279   RelayoutAndFlush(scenes);
280 }
281
282 void Core::ProcessEvents()
283 {
284   // Guard against calls to ProcessEvents() during ProcessEvents()
285   if(mProcessingEvent)
286   {
287     DALI_LOG_ERROR("ProcessEvents should not be called from within ProcessEvents!\n");
288     mRenderController.RequestProcessEventsOnIdle();
289     return;
290   }
291
292   mProcessingEvent = true;
293   mRelayoutController->SetProcessingCoreEvents(true);
294
295   // Signal that any messages received will be flushed soon
296   mUpdateManager->EventProcessingStarted();
297
298   // Scene could be added or removed while processing the events
299   // Copy the Scene container locally to avoid possibly invalid iterator
300   SceneContainer scenes = mScenes;
301
302   // process events in all scenes
303   for(auto scene : scenes)
304   {
305     scene->ProcessEvents();
306   }
307
308   mNotificationManager->ProcessMessages();
309
310   // Emit signal here to inform listeners that event processing has finished.
311   for(auto scene : scenes)
312   {
313     scene->EmitEventProcessingFinishedSignal();
314   }
315
316   RelayoutAndFlush(scenes);
317
318   mUpdateManager->EventProcessingFinished();
319
320   // Check if the touch or gestures require updates.
321   const bool gestureNeedsUpdate = mGestureEventProcessor->NeedsUpdate();
322
323   if(gestureNeedsUpdate)
324   {
325     // tell the render controller to keep update thread running
326     mRenderController.RequestUpdate();
327   }
328
329   mRelayoutController->SetProcessingCoreEvents(false);
330
331   // ProcessEvents() may now be called again
332   mProcessingEvent = false;
333 }
334
335 void Core::RelayoutAndFlush(SceneContainer& scenes)
336 {
337   if(mRelayoutFlush)
338   {
339     DALI_LOG_ERROR("RelayoutAndFlush should not be called from within RelayoutAndFlush!\n");
340     return;
341   }
342
343   const bool isProcessEvents = mProcessingEvent;
344
345   if(!isProcessEvents)
346   {
347     // Fake that we are in ProcessEvents()
348     mProcessingEvent = true;
349     mRelayoutController->SetProcessingCoreEvents(true);
350
351     // Signal that any messages received will be flushed soon
352     mUpdateManager->EventProcessingStarted();
353   }
354
355   mRelayoutFlush = true;
356
357   // Run any registered processors
358   RunProcessors();
359
360   // Run the size negotiation after event processing finished signal
361   mRelayoutController->Relayout();
362
363   // Run any registered post processors
364   RunPostProcessors();
365
366   // Rebuild depth tree after event processing has finished
367   for(auto& scene : scenes)
368   {
369     scene->RebuildDepthTree();
370   }
371
372   // Flush any queued messages for the update-thread
373   const bool messagesToProcess = mUpdateManager->FlushQueue();
374
375   if(messagesToProcess)
376   {
377     // tell the render controller to keep update thread running
378     mRenderController.RequestUpdate();
379   }
380
381   mRelayoutFlush = false;
382
383   if(!isProcessEvents)
384   {
385     // Revert fake informations
386     mProcessingEvent = false;
387     mRelayoutController->SetProcessingCoreEvents(false);
388
389     mUpdateManager->EventProcessingFinished();
390   }
391 }
392
393 uint32_t Core::GetMaximumUpdateCount() const
394 {
395   return MAXIMUM_UPDATE_COUNT;
396 }
397
398 void Core::RegisterProcessor(Integration::Processor& processor, bool postProcessor)
399 {
400   if(postProcessor)
401   {
402     mPostProcessors.PushBack(&processor);
403   }
404   else
405   {
406     mProcessors.PushBack(&processor);
407   }
408 }
409
410 void Core::UnregisterProcessor(Integration::Processor& processor, bool postProcessor)
411 {
412   if(postProcessor)
413   {
414     auto iter = std::find(mPostProcessors.Begin(), mPostProcessors.End(), &processor);
415     if(iter != mPostProcessors.End())
416     {
417       mPostProcessors.Erase(iter);
418       mPostProcessorUnregistered = true;
419     }
420   }
421   else
422   {
423     auto iter = std::find(mProcessors.Begin(), mProcessors.End(), &processor);
424     if(iter != mProcessors.End())
425     {
426       mProcessors.Erase(iter);
427       mProcessorUnregistered = true;
428     }
429   }
430 }
431
432 void Core::RunProcessors()
433 {
434   if(mProcessors.Count() != 0)
435   {
436     DALI_TRACE_SCOPE(gTraceFilter, "DALI_CORE_RUN_PROCESSORS");
437
438     // Copy processor pointers to prevent changes to vector affecting loop iterator.
439     Dali::Vector<Integration::Processor*> processors(mProcessors);
440
441     // To prevent accessing processor unregistered during the loop
442     mProcessorUnregistered = false;
443
444     for(auto processor : processors)
445     {
446       if(processor)
447       {
448         if(!mProcessorUnregistered)
449         {
450           processor->Process(false);
451         }
452         else
453         {
454           // Run processor if the processor is still in the list.
455           // It may be removed during the loop.
456           auto iter = std::find(mProcessors.Begin(), mProcessors.End(), processor);
457           if(iter != mProcessors.End())
458           {
459             processor->Process(false);
460           }
461         }
462       }
463     }
464   }
465 }
466
467 void Core::RunPostProcessors()
468 {
469   if(mPostProcessors.Count() != 0)
470   {
471     DALI_TRACE_SCOPE(gTraceFilter, "DALI_CORE_RUN_POST_PROCESSORS");
472
473     // Copy processor pointers to prevent changes to vector affecting loop iterator.
474     Dali::Vector<Integration::Processor*> processors(mPostProcessors);
475
476     // To prevent accessing processor unregistered during the loop
477     mPostProcessorUnregistered = false;
478
479     for(auto processor : processors)
480     {
481       if(processor)
482       {
483         if(!mPostProcessorUnregistered)
484         {
485           processor->Process(true);
486         }
487         else
488         {
489           // Run processor if the processor is still in the list.
490           // It may be removed during the loop.
491           auto iter = std::find(mPostProcessors.Begin(), mPostProcessors.End(), processor);
492           if(iter != mPostProcessors.End())
493           {
494             processor->Process(true);
495           }
496         }
497       }
498     }
499   }
500 }
501
502 StagePtr Core::GetCurrentStage()
503 {
504   return mStage.Get();
505 }
506
507 PlatformAbstraction& Core::GetPlatform()
508 {
509   return mPlatform;
510 }
511
512 UpdateManager& Core::GetUpdateManager()
513 {
514   return *(mUpdateManager);
515 }
516
517 RenderManager& Core::GetRenderManager()
518 {
519   return *(mRenderManager);
520 }
521
522 NotificationManager& Core::GetNotificationManager()
523 {
524   return *(mNotificationManager);
525 }
526
527 ShaderFactory& Core::GetShaderFactory()
528 {
529   return *(mShaderFactory);
530 }
531
532 GestureEventProcessor& Core::GetGestureEventProcessor()
533 {
534   return *(mGestureEventProcessor);
535 }
536
537 RelayoutController& Core::GetRelayoutController()
538 {
539   return *(mRelayoutController.Get());
540 }
541
542 ObjectRegistry& Core::GetObjectRegistry() const
543 {
544   return *(mObjectRegistry.Get());
545 }
546
547 void Core::LogMemoryPools() const
548 {
549   uint32_t animationPoolCapacity    = SceneGraph::Animation::GetMemoryPoolCapacity();
550   uint32_t renderItemPoolCapacity   = SceneGraph::RenderItem::GetMemoryPoolCapacity();
551   uint32_t relayoutItemPoolCapacity = mRelayoutController->GetMemoryPoolCapacity();
552   uint32_t rendererPoolCapacity     = SceneGraph::Renderer::GetMemoryPoolCapacity();
553   uint32_t textureSetPoolCapacity   = SceneGraph::TextureSet::GetMemoryPoolCapacity();
554   uint32_t renderTaskPoolCapacity   = SceneGraph::RenderTaskList::GetMemoryPoolCapacity();
555   uint32_t nodePoolCapacity         = SceneGraph::Node::GetMemoryPoolCapacity();
556
557   DALI_LOG_RELEASE_INFO(
558     "\nMemory Pool capacities:\n"
559     "  Animations:    %lu\n"
560     "  RenderItems:   %lu\n"
561     "  RelayoutItems: %lu\n"
562     "  Renderers:     %lu\n"
563     "  TextureSets:   %lu\n"
564     "  RenderTasks:   %lu\n"
565     "  Nodes:         %lu\n",
566     animationPoolCapacity,
567     renderItemPoolCapacity,
568     relayoutItemPoolCapacity,
569     rendererPoolCapacity,
570     textureSetPoolCapacity,
571     renderTaskPoolCapacity,
572     nodePoolCapacity);
573
574   uint32_t updateQCapacity = mUpdateManager->GetUpdateMessageQueueCapacity();
575   uint32_t renderQCapacity = mUpdateManager->GetRenderMessageQueueCapacity();
576
577   DALI_LOG_RELEASE_INFO(
578     "\nMessage Queue capacities:\n"
579     "  UpdateQueue: %lu\n"
580     "  RenderQueue: %lu\n",
581     updateQCapacity,
582     renderQCapacity);
583
584   size_t renderInstructionCapacity = mUpdateManager->GetRenderInstructionCapacity();
585   DALI_LOG_RELEASE_INFO("\nRenderInstruction capacity: %lu\n", renderInstructionCapacity);
586 }
587
588 EventThreadServices& Core::GetEventThreadServices()
589 {
590   return *this;
591 }
592
593 PropertyNotificationManager& Core::GetPropertyNotificationManager() const
594 {
595   return *(mPropertyNotificationManager);
596 }
597
598 AnimationPlaylist& Core::GetAnimationPlaylist() const
599 {
600   return *(mAnimationPlaylist);
601 }
602
603 Integration::GlAbstraction& Core::GetGlAbstraction() const
604 {
605   return mGraphicsController.GetGlAbstraction();
606 }
607
608 void Core::AddScene(Scene* scene)
609 {
610   mScenes.push_back(scene);
611 }
612
613 void Core::RemoveScene(Scene* scene)
614 {
615   auto iter = std::find(mScenes.begin(), mScenes.end(), scene);
616   if(iter != mScenes.end())
617   {
618     mScenes.erase(iter);
619   }
620 }
621
622 void Core::CreateThreadLocalStorage()
623 {
624   // a pointer to the ThreadLocalStorage object will be stored in TLS
625   // The ThreadLocalStorage object should be deleted by the Core destructor
626   ThreadLocalStorage* tls = new ThreadLocalStorage(this);
627   tls->Reference();
628 }
629
630 void Core::RegisterObject(Dali::BaseObject* object)
631 {
632   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
633   mObjectRegistry->RegisterObject(object);
634 }
635
636 void Core::UnregisterObject(Dali::BaseObject* object)
637 {
638   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
639   mObjectRegistry->UnregisterObject(object);
640 }
641
642 Integration::RenderController& Core::GetRenderController()
643 {
644   return mRenderController;
645 }
646
647 uint32_t* Core::ReserveMessageSlot(uint32_t size, bool updateScene)
648 {
649   return mUpdateManager->ReserveMessageSlot(size, updateScene);
650 }
651
652 BufferIndex Core::GetEventBufferIndex() const
653 {
654   return mUpdateManager->GetEventBufferIndex();
655 }
656
657 } // namespace Internal
658
659 } // namespace Dali