Remove RenderSurface from Core
[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 : mRenderController( renderController ),
92   mPlatform(platform),
93   mProcessingEvent(false),
94   mForceNextUpdate( 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( glAbstraction, glSyncAbstraction, glContextHelperAbstraction, depthBufferAvailable, stencilBufferAvailable );
111
112   RenderQueue& renderQueue = mRenderManager->GetRenderQueue();
113
114   mDiscardQueue = new DiscardQueue( renderQueue );
115
116   mUpdateManager = new UpdateManager( *mNotificationManager,
117                                       *mAnimationPlaylist,
118                                       *mPropertyNotificationManager,
119                                       *mDiscardQueue,
120                                        renderController,
121                                       *mRenderManager,
122                                        renderQueue,
123                                       *mRenderTaskProcessor );
124
125   mRenderManager->SetShaderSaver( *mUpdateManager );
126
127   mObjectRegistry = ObjectRegistry::New();
128
129   mStage = IntrusivePtr<Stage>( Stage::New( *mUpdateManager ) );
130
131   // This must be called after stage is created but before stage initialization
132   mRelayoutController = IntrusivePtr< RelayoutController >( new RelayoutController( mRenderController ) );
133
134   mGestureEventProcessor = new GestureEventProcessor( *mUpdateManager, mRenderController );
135
136   mShaderFactory = new ShaderFactory();
137   mUpdateManager->SetShaderSaver( *mShaderFactory );
138
139   GetImplementation(Dali::TypeRegistry::Get()).CallInitFunctions();
140 }
141
142 Core::~Core()
143 {
144   /*
145    * The order of destructing these singletons is important!!!
146    */
147
148   // clear the thread local storage first
149   // allows core to be created / deleted many times in the same thread (how TET cases work).
150   // Do this before mStage.Reset() so Stage::IsInstalled() returns false
151   ThreadLocalStorage* tls = ThreadLocalStorage::GetInternal();
152   if( tls )
153   {
154     tls->Remove();
155     tls->Unreference();
156   }
157
158   mObjectRegistry.Reset();
159
160   // Stop relayout requests being raised on stage destruction
161   mRelayoutController.Reset();
162
163   // remove (last?) reference to stage
164   mStage.Reset();
165
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   mRenderManager->ContextCreated();
188 }
189
190 void Core::ContextDestroyed()
191 {
192   mRenderManager->ContextDestroyed();
193 }
194
195 void Core::Update( float elapsedSeconds, uint32_t lastVSyncTimeMilliseconds, uint32_t nextVSyncTimeMilliseconds, Integration::UpdateStatus& status, bool renderToFboEnabled, bool isRenderingToFbo )
196 {
197   // set the time delta so adaptor can easily print FPS with a release build with 0 as
198   // it is cached by frametime
199   status.secondsFromLastFrame = elapsedSeconds;
200
201   // Render returns true when there are updates on the stage or one or more animations are completed.
202   // Use the estimated time diff till we render as the elapsed time.
203   status.keepUpdating = mUpdateManager->Update( elapsedSeconds,
204                                                 lastVSyncTimeMilliseconds,
205                                                 nextVSyncTimeMilliseconds,
206                                                 renderToFboEnabled,
207                                                 isRenderingToFbo );
208
209   // Check the Notification Manager message queue to set needsNotification
210   status.needsNotification = mNotificationManager->MessagesToProcess();
211
212   // Check if the default surface is changed
213   status.surfaceRectChanged = mUpdateManager->IsDefaultSurfaceRectChanged();
214
215   // No need to keep update running if there are notifications to process.
216   // Any message to update will wake it up anyways
217 }
218
219 void Core::PreRender( RenderStatus& status, bool forceClear, bool uploadOnly )
220 {
221   mRenderManager->PreRender( status, forceClear, uploadOnly );
222 }
223
224 void Core::RenderScene( Integration::Scene& scene, bool renderToFbo )
225 {
226   mRenderManager->RenderScene( scene, renderToFbo );
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( auto iter = mScenes.begin(); iter != mScenes.end(); ++iter )
241   {
242     Dali::Actor sceneRootLayer = (*iter)->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   // Rebuild depth tree after event processing has finished
296   for( auto scene : scenes )
297   {
298     scene->RebuildDepthTree();
299   }
300
301   // Flush any queued messages for the update-thread
302   const bool messagesToProcess = mUpdateManager->FlushQueue();
303
304   // Check if the touch or gestures require updates.
305   const bool gestureNeedsUpdate = mGestureEventProcessor->NeedsUpdate();
306   // Check if the next update is forced.
307   const bool forceUpdate = IsNextUpdateForced();
308
309   if( messagesToProcess || gestureNeedsUpdate || forceUpdate )
310   {
311     // tell the render controller to keep update thread running
312     mRenderController.RequestUpdate( forceUpdate );
313   }
314
315   mRelayoutController->SetProcessingCoreEvents( false );
316
317   // ProcessEvents() may now be called again
318   mProcessingEvent = false;
319 }
320
321 uint32_t Core::GetMaximumUpdateCount() const
322 {
323   return MAXIMUM_UPDATE_COUNT;
324 }
325
326 void Core::RegisterProcessor( Integration::Processor& processor )
327 {
328   mProcessors.PushBack(&processor);
329 }
330
331 void Core::UnregisterProcessor( Integration::Processor& processor )
332 {
333   auto iter = std::find( mProcessors.Begin(), mProcessors.End(), &processor );
334   if( iter != mProcessors.End() )
335   {
336     mProcessors.Erase( iter );
337   }
338 }
339
340 void Core::RunProcessors()
341 {
342   // Copy processor pointers to prevent changes to vector affecting loop iterator.
343   Dali::Vector<Integration::Processor*> processors( mProcessors );
344
345   for( auto processor : processors )
346   {
347     if( processor )
348     {
349       processor->Process();
350     }
351   }
352 }
353
354 StagePtr Core::GetCurrentStage()
355 {
356   return mStage.Get();
357 }
358
359 PlatformAbstraction& Core::GetPlatform()
360 {
361   return mPlatform;
362 }
363
364 UpdateManager& Core::GetUpdateManager()
365 {
366   return *(mUpdateManager);
367 }
368
369 RenderManager& Core::GetRenderManager()
370 {
371   return *(mRenderManager);
372 }
373
374 NotificationManager& Core::GetNotificationManager()
375 {
376   return *(mNotificationManager);
377 }
378
379 ShaderFactory& Core::GetShaderFactory()
380 {
381   return *(mShaderFactory);
382 }
383
384 GestureEventProcessor& Core::GetGestureEventProcessor()
385 {
386   return *(mGestureEventProcessor);
387 }
388
389 RelayoutController& Core::GetRelayoutController()
390 {
391   return *(mRelayoutController.Get());
392 }
393
394 ObjectRegistry& Core::GetObjectRegistry() const
395 {
396   return *(mObjectRegistry.Get());
397 }
398
399 EventThreadServices& Core::GetEventThreadServices()
400 {
401   return *this;
402 }
403
404 PropertyNotificationManager& Core::GetPropertyNotificationManager() const
405 {
406   return *(mPropertyNotificationManager);
407 }
408
409 AnimationPlaylist& Core::GetAnimationPlaylist() const
410 {
411   return *(mAnimationPlaylist);
412 }
413
414 void Core::AddScene( Scene* scene )
415 {
416   mScenes.push_back( scene );
417 }
418
419 void Core::RemoveScene( Scene* scene )
420 {
421   auto iter = std::find( mScenes.begin(), mScenes.end(), scene );
422   if( iter != mScenes.end() )
423   {
424     mScenes.erase( iter );
425   }
426 }
427
428 void Core::CreateThreadLocalStorage()
429 {
430   // a pointer to the ThreadLocalStorage object will be stored in TLS
431   // The ThreadLocalStorage object should be deleted by the Core destructor
432   ThreadLocalStorage* tls = new ThreadLocalStorage(this);
433   tls->Reference();
434 }
435
436 void Core::RegisterObject( Dali::BaseObject* object )
437 {
438   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
439   mObjectRegistry->RegisterObject( object );
440 }
441
442 void Core::UnregisterObject( Dali::BaseObject* object )
443 {
444   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
445   mObjectRegistry->UnregisterObject( object );
446 }
447
448 Integration::RenderController& Core::GetRenderController()
449 {
450   return mRenderController;
451 }
452
453 uint32_t* Core::ReserveMessageSlot( uint32_t size, bool updateScene )
454 {
455   return mUpdateManager->ReserveMessageSlot( size, updateScene );
456 }
457
458 BufferIndex Core::GetEventBufferIndex() const
459 {
460   return mUpdateManager->GetEventBufferIndex();
461 }
462
463 void Core::ForceNextUpdate()
464 {
465   mForceNextUpdate = true;
466 }
467
468 bool Core::IsNextUpdateForced()
469 {
470   bool nextUpdateForced = mForceNextUpdate;
471   mForceNextUpdate = false;
472   return nextUpdateForced;
473 }
474
475 } // namespace Internal
476
477 } // namespace Dali