2 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali/internal/render/common/render-manager.h>
22 #include <dali/public-api/common/dali-common.h>
23 #include <dali/public-api/common/stage.h>
24 #include <dali/public-api/render-tasks/render-task.h>
25 #include <dali/integration-api/debug.h>
26 #include <dali/integration-api/core.h>
27 #include <dali/internal/common/owner-pointer.h>
28 #include <dali/internal/render/queue/render-queue.h>
29 #include <dali/internal/render/common/render-algorithms.h>
30 #include <dali/internal/render/common/render-debug.h>
31 #include <dali/internal/render/common/render-tracker.h>
32 #include <dali/internal/render/common/render-instruction-container.h>
33 #include <dali/internal/render/common/render-instruction.h>
34 #include <dali/internal/render/gl-resources/context.h>
35 #include <dali/internal/render/gl-resources/frame-buffer-texture.h>
36 #include <dali/internal/render/gl-resources/native-frame-buffer-texture.h>
37 #include <dali/internal/render/gl-resources/texture-cache.h>
38 #include <dali/internal/render/renderers/scene-graph-renderer.h>
39 #include <dali/internal/render/renderers/render-geometry.h>
40 #include <dali/internal/render/shaders/program-controller.h>
42 // Uncomment the next line to enable frame snapshot logging
43 //#define FRAME_SNAPSHOT_LOGGING
45 #ifdef FRAME_SNAPSHOT_LOGGING
47 using namespace Dali::Internal::Render;
49 namespace // unnamed namespace
51 unsigned int SNAPSHOT_FRAME_FREQUENCY = 1200; // dump every 20-30 seconds
52 } // unnamed namespace
54 #define SET_SNAPSHOT_FRAME_LOG_LEVEL \
55 DALI_LOG_FILTER_SET_LEVEL(Context::gGlLogFilter, ((GetFrameCount() % SNAPSHOT_FRAME_FREQUENCY)==5 ? Debug::General : Debug::Concise));
57 #else // FRAME_SNAPSHOT_LOGGING
59 #define SET_SNAPSHOT_FRAME_LOG_LEVEL
61 #endif // FRAME_SNAPSHOT_LOGGING
72 typedef OwnerContainer< Renderer* > RendererOwnerContainer;
73 typedef RendererOwnerContainer::Iterator RendererOwnerIter;
75 typedef OwnerContainer< RenderGeometry* > RenderGeometryOwnerContainer;
76 typedef RenderGeometryOwnerContainer::Iterator RenderGeometryOwnerIter;
78 typedef OwnerContainer< RenderTracker* > RenderTrackerContainer;
79 typedef RenderTrackerContainer::Iterator RenderTrackerIter;
80 typedef RenderTrackerContainer::ConstIterator RenderTrackerConstIter;
83 * Structure to contain internal data
85 struct RenderManager::Impl
87 Impl( Dali::Integration::GlAbstraction& glAbstraction,
88 ResourcePostProcessList& resourcePostProcessQ,
89 PostProcessResourceDispatcher& postProcessDispatcher )
90 : context( glAbstraction ),
92 textureCache( renderQueue, postProcessDispatcher, context ),
93 resourcePostProcessQueue( resourcePostProcessQ ),
95 backgroundColor( Dali::Stage::DEFAULT_BACKGROUND_COLOR ),
97 lastFrameTime( 0.0f ),
99 renderBufferIndex( SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX ),
100 defaultSurfaceRect(),
102 renderersAdded( false ),
103 firstRenderCompleted( false ),
104 defaultShader( NULL ),
105 programController( glAbstraction )
113 void AddRenderTracker( RenderTracker* renderTracker )
115 DALI_ASSERT_DEBUG( renderTracker != NULL );
116 mRenderTrackers.PushBack( renderTracker );
119 void RemoveRenderTracker( RenderTracker* renderTracker )
121 DALI_ASSERT_DEBUG( renderTracker != NULL );
122 for(RenderTrackerIter iter = mRenderTrackers.Begin(), end = mRenderTrackers.End(); iter != end; ++iter)
124 if( *iter == renderTracker )
126 mRenderTrackers.Erase( iter );
132 void UpdateTrackers()
134 for(RenderTrackerIter iter = mRenderTrackers.Begin(), end = mRenderTrackers.End(); iter != end; ++iter)
136 (*iter)->PollSyncObject();
140 // the order is important for destruction,
141 // programs are owned by context at the moment.
142 Context context; ///< holds the GL state
143 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
144 TextureCache textureCache; ///< Cache for all GL textures
145 ResourcePostProcessList& resourcePostProcessQueue; ///< A queue for requesting resource post processing in update thread
147 // Render instructions describe what should be rendered during RenderManager::Render()
148 // Owned by RenderManager. Update manager updates instructions for the next frame while we render the current one
149 RenderInstructionContainer instructions;
151 Vector4 backgroundColor; ///< The glClear color used at the beginning of each frame.
153 volatile float frameTime; ///< The elapsed time since the previous frame
154 float lastFrameTime; ///< Last frame delta.
156 unsigned int frameCount; ///< The current frame count
157 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
159 Rect<int> defaultSurfaceRect; ///< Rectangle for the default surface we are rendering to
161 RendererOwnerContainer rendererContainer; ///< List of owned renderers
162 RenderGeometryOwnerContainer renderGeometryContainer; ///< List of owned RenderGeometries
166 RenderTrackerContainer mRenderTrackers; ///< List of render trackers
168 bool firstRenderCompleted; ///< False until the first render is done
169 Shader* defaultShader; ///< Default shader to use
170 ProgramController programController; ///< Owner of the GL programs
173 RenderManager* RenderManager::New( Integration::GlAbstraction& glAbstraction, ResourcePostProcessList& resourcePostProcessQ )
175 RenderManager* manager = new RenderManager;
176 manager->mImpl = new Impl( glAbstraction, resourcePostProcessQ, *manager );
180 RenderManager::RenderManager()
185 RenderManager::~RenderManager()
190 RenderQueue& RenderManager::GetRenderQueue()
192 return mImpl->renderQueue;
195 TextureCache& RenderManager::GetTextureCache()
197 return mImpl->textureCache;
200 void RenderManager::ContextCreated()
202 mImpl->context.GlContextCreated();
203 mImpl->programController.GlContextCreated();
205 // renderers, textures and gpu buffers cannot reinitialize themselves
206 // so they rely on someone reloading the data for them
209 void RenderManager::ContextDestroyed()
211 // @todo Set an atomic value to prevent render manager rendering again until
212 // ContextCreated has been called.
214 mImpl->context.GlContextDestroyed();
215 mImpl->programController.GlContextDestroyed();
217 // inform texture cache
218 mImpl->textureCache.GlContextDestroyed(); // Clears gl texture ids
221 RendererOwnerContainer::Iterator end = mImpl->rendererContainer.End();
222 RendererOwnerContainer::Iterator iter = mImpl->rendererContainer.Begin();
223 for( ; iter != end; ++iter )
225 GlResourceOwner* renderer = *iter;
226 renderer->GlContextDestroyed(); // Clear up vertex buffers
230 void RenderManager::DispatchPostProcessRequest(ResourcePostProcessRequest& request)
232 mImpl->resourcePostProcessQueue[ mImpl->renderBufferIndex ].push_back( request );
235 void RenderManager::SetShaderSaver( ShaderSaver& upstream )
237 mImpl->programController.SetShaderSaver( upstream );
240 RenderInstructionContainer& RenderManager::GetRenderInstructionContainer()
242 return mImpl->instructions;
245 void RenderManager::SetBackgroundColor( const Vector4& color )
247 mImpl->backgroundColor = color;
250 void RenderManager::SetFrameDeltaTime( float deltaTime )
252 Dali::Mutex::ScopedLock lock( mMutex );
253 mImpl->frameTime = deltaTime;
256 void RenderManager::SetDefaultSurfaceRect(const Rect<int>& rect)
258 mImpl->defaultSurfaceRect = rect;
261 void RenderManager::AddRenderer( Renderer* renderer )
263 // Initialize the renderer as we are now in render thread
264 renderer->Initialize( mImpl->context, mImpl->textureCache );
266 mImpl->rendererContainer.PushBack( renderer );
268 if( !mImpl->renderersAdded )
270 mImpl->renderersAdded = true;
274 void RenderManager::RemoveRenderer( Renderer* renderer )
276 DALI_ASSERT_DEBUG( NULL != renderer );
278 RendererOwnerContainer& renderers = mImpl->rendererContainer;
281 for ( RendererOwnerIter iter = renderers.Begin(); iter != renderers.End(); ++iter )
283 if ( *iter == renderer )
285 renderers.Erase( iter ); // Renderer found; now destroy it
291 void RenderManager::AddGeometry( RenderGeometry* renderGeometry )
293 mImpl->renderGeometryContainer.PushBack( renderGeometry );
296 void RenderManager::RemoveGeometry( RenderGeometry* renderGeometry )
298 DALI_ASSERT_DEBUG( NULL != renderGeometry );
300 RenderGeometryOwnerContainer& geometries = mImpl->renderGeometryContainer;
303 for ( RenderGeometryOwnerIter iter = geometries.Begin(); iter != geometries.End(); ++iter )
305 if ( *iter == renderGeometry )
307 geometries.Erase( iter ); // Geometry found; now destroy it
313 void RenderManager::AddPropertyBuffer( RenderGeometry* renderGeometry, PropertyBufferDataProvider* propertyBuffer, const GpuBuffer::Target& target, const GpuBuffer::Usage& usage )
315 DALI_ASSERT_DEBUG( NULL != renderGeometry );
317 RenderGeometryOwnerContainer& geometries = mImpl->renderGeometryContainer;
320 for ( RenderGeometryOwnerIter iter = geometries.Begin(); iter != geometries.End(); ++iter )
322 if ( *iter == renderGeometry )
324 (*iter)->AddPropertyBuffer( propertyBuffer, target, usage );
330 void RenderManager::RemovePropertyBuffer( RenderGeometry* renderGeometry, PropertyBufferDataProvider* propertyBuffer )
332 DALI_ASSERT_DEBUG( NULL != renderGeometry );
334 RenderGeometryOwnerContainer& geometries = mImpl->renderGeometryContainer;
337 for ( RenderGeometryOwnerIter iter = geometries.Begin(); iter != geometries.End(); ++iter )
339 if ( *iter == renderGeometry )
341 (*iter)->RemovePropertyBuffer( propertyBuffer );
348 void RenderManager::AddRenderTracker( RenderTracker* renderTracker )
350 mImpl->AddRenderTracker(renderTracker);
353 void RenderManager::RemoveRenderTracker( RenderTracker* renderTracker )
355 mImpl->RemoveRenderTracker(renderTracker);
358 void RenderManager::SetDefaultShader( Shader* shader )
360 mImpl->defaultShader = shader;
363 ProgramCache* RenderManager::GetProgramCache()
365 return &(mImpl->programController);
368 bool RenderManager::Render( Integration::RenderStatus& status )
370 DALI_PRINT_RENDER_START( mImpl->renderBufferIndex );
372 // Core::Render documents that GL context must be current before calling Render
373 DALI_ASSERT_DEBUG( mImpl->context.IsGlContextCreated() );
375 status.SetHasRendered( false );
377 // Increment the frame count at the beginning of each frame
378 ++(mImpl->frameCount);
379 mImpl->context.SetFrameCount(mImpl->frameCount);
380 mImpl->context.ClearRendererCount();
381 mImpl->context.ClearCulledCount();
383 PERF_MONITOR_START(PerformanceMonitor::DRAW_NODES);
385 SET_SNAPSHOT_FRAME_LOG_LEVEL;
387 // Process messages queued during previous update
388 mImpl->renderQueue.ProcessMessages( mImpl->renderBufferIndex );
390 // No need to make any gl calls if we've done 1st glClear & don't have any renderers to render during startup.
391 if( !mImpl->firstRenderCompleted || mImpl->renderersAdded )
393 // switch rendering to adaptor provided (default) buffer
394 mImpl->context.BindFramebuffer( GL_FRAMEBUFFER, 0 );
396 mImpl->context.Viewport( mImpl->defaultSurfaceRect.x,
397 mImpl->defaultSurfaceRect.y,
398 mImpl->defaultSurfaceRect.width,
399 mImpl->defaultSurfaceRect.height );
401 mImpl->context.ClearColor( mImpl->backgroundColor.r,
402 mImpl->backgroundColor.g,
403 mImpl->backgroundColor.b,
404 mImpl->backgroundColor.a );
406 mImpl->context.ClearStencil( 0 );
408 // Clear the entire color, depth and stencil buffers for the default framebuffer.
409 // It is important to clear all 3 buffers, for performance on deferred renderers like Mali
410 // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
411 // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
412 mImpl->context.SetScissorTest( false );
413 mImpl->context.ColorMask( true );
414 mImpl->context.DepthMask( true );
415 mImpl->context.StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
416 mImpl->context.Clear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, Context::FORCE_CLEAR );
418 // reset the program matrices for all programs once per frame
419 // this ensures we will set view and projection matrix once per program per camera
420 // @todo move programs out of context onto a program controller and let that handle this
421 mImpl->programController.ResetProgramMatrices();
423 // if we don't have default shader, no point doing the render calls
424 if( mImpl->defaultShader )
426 size_t count = mImpl->instructions.Count( mImpl->renderBufferIndex );
427 for ( size_t i = 0; i < count; ++i )
429 RenderInstruction& instruction = mImpl->instructions.At( mImpl->renderBufferIndex, i );
431 DoRender( instruction, *mImpl->defaultShader, mImpl->lastFrameTime );
433 const RenderListContainer::SizeType countRenderList = instruction.RenderListCount();
434 if ( countRenderList > 0 )
436 status.SetHasRendered( true );
439 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
440 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
442 mImpl->UpdateTrackers();
444 mImpl->firstRenderCompleted = true;
448 PERF_MONITOR_END(PerformanceMonitor::DRAW_NODES);
452 // check if anything has been posted to the update thread
453 bool updateRequired = !mImpl->resourcePostProcessQueue[ mImpl->renderBufferIndex ].empty();
455 //Notify RenderGeometries that rendering has finished
456 for ( RenderGeometryOwnerIter iter = mImpl->renderGeometryContainer.Begin(); iter != mImpl->renderGeometryContainer.End(); ++iter )
458 (*iter)->OnRenderFinished();
462 * The rendering has finished; swap to the next buffer.
463 * Ideally the update has just finished using this buffer; otherwise the render thread
464 * should block until the update has finished.
466 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
468 DALI_PRINT_RENDER_END();
470 DALI_PRINT_RENDERER_COUNT(mImpl->frameCount, mImpl->context.GetRendererCount());
471 DALI_PRINT_CULL_COUNT(mImpl->frameCount, mImpl->context.GetCulledCount());
473 return updateRequired;
476 void RenderManager::SetLastFrameTime()
478 Dali::Mutex::ScopedLock lock(mMutex);
479 mImpl->lastFrameTime = mImpl->frameTime;
482 void RenderManager::DoRender( RenderInstruction& instruction, Shader& defaultShader, float elapsedTime )
484 Rect<int> viewportRect;
487 if ( instruction.mIsClearColorSet )
489 clearColor = instruction.mClearColor;
493 clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
496 FrameBufferTexture* offscreen = NULL;
498 if ( instruction.mOffscreenTextureId != 0 )
500 offscreen = mImpl->textureCache.GetFramebuffer( instruction.mOffscreenTextureId );
501 DALI_ASSERT_DEBUG( NULL != offscreen );
503 if( NULL != offscreen &&
504 offscreen->Prepare() )
506 // Check whether a viewport is specified, otherwise the full surface size is used
507 if ( instruction.mIsViewportSet )
509 // For glViewport the lower-left corner is (0,0)
510 const int y = ( offscreen->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
511 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
515 viewportRect.Set( 0, 0, offscreen->GetWidth(), offscreen->GetHeight() );
520 // Offscreen is NULL or could not be prepared.
524 else // !(instruction.mOffscreenTexture)
526 // switch rendering to adaptor provided (default) buffer
527 mImpl->context.BindFramebuffer( GL_FRAMEBUFFER, 0 );
529 // Check whether a viewport is specified, otherwise the full surface size is used
530 if ( instruction.mIsViewportSet )
532 // For glViewport the lower-left corner is (0,0)
533 const int y = ( mImpl->defaultSurfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
534 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
538 viewportRect = mImpl->defaultSurfaceRect;
542 mImpl->context.Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
544 if ( instruction.mIsClearColorSet )
546 mImpl->context.ClearColor( clearColor.r,
551 // Clear the viewport area only
552 mImpl->context.SetScissorTest( true );
553 mImpl->context.Scissor( viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height );
554 mImpl->context.ColorMask( true );
555 mImpl->context.Clear( GL_COLOR_BUFFER_BIT , Context::CHECK_CACHED_VALUES );
556 mImpl->context.SetScissorTest( false );
559 Render::ProcessRenderInstruction( instruction,
563 mImpl->renderBufferIndex,
566 if(instruction.mOffscreenTextureId != 0)
568 GLenum attachments[] = { GL_DEPTH_ATTACHMENT, GL_STENCIL_ATTACHMENT };
569 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
572 if( instruction.mRenderTracker && offscreen != NULL )
574 instruction.mRenderTracker->CreateSyncObject();
575 instruction.mRenderTracker = NULL; // Only create once.
579 } // namespace SceneGraph
581 } // namespace Internal