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/actors/sampling.h>
23 #include <dali/public-api/common/dali-common.h>
24 #include <dali/public-api/common/stage.h>
25 #include <dali/public-api/render-tasks/render-task.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/integration-api/core.h>
28 #include <dali/internal/common/owner-pointer.h>
29 #include <dali/internal/render/queue/render-queue.h>
30 #include <dali/internal/render/common/render-algorithms.h>
31 #include <dali/internal/render/common/render-debug.h>
32 #include <dali/internal/render/common/render-tracker.h>
33 #include <dali/internal/render/common/render-instruction-container.h>
34 #include <dali/internal/render/common/render-instruction.h>
35 #include <dali/internal/render/gl-resources/context.h>
36 #include <dali/internal/render/gl-resources/frame-buffer-texture.h>
37 #include <dali/internal/render/gl-resources/texture-cache.h>
38 #include <dali/internal/render/renderers/render-renderer.h>
39 #include <dali/internal/render/renderers/render-geometry.h>
40 #include <dali/internal/render/renderers/render-sampler.h>
41 #include <dali/internal/render/shaders/program-controller.h>
43 // Uncomment the next line to enable frame snapshot logging
44 //#define FRAME_SNAPSHOT_LOGGING
46 #ifdef FRAME_SNAPSHOT_LOGGING
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< Render::Renderer* > RendererOwnerContainer;
73 typedef RendererOwnerContainer::Iterator RendererOwnerIter;
75 typedef OwnerContainer< RenderGeometry* > RenderGeometryOwnerContainer;
76 typedef RenderGeometryOwnerContainer::Iterator RenderGeometryOwnerIter;
78 typedef OwnerContainer< Render::Sampler* > SamplerOwnerContainer;
79 typedef SamplerOwnerContainer::Iterator SamplerOwnerIter;
81 typedef OwnerContainer< RenderTracker* > RenderTrackerContainer;
82 typedef RenderTrackerContainer::Iterator RenderTrackerIter;
83 typedef RenderTrackerContainer::ConstIterator RenderTrackerConstIter;
86 * Structure to contain internal data
88 struct RenderManager::Impl
90 Impl( Dali::Integration::GlAbstraction& glAbstraction,
91 ResourcePostProcessList& resourcePostProcessQ,
92 PostProcessResourceDispatcher& postProcessDispatcher )
93 : context( glAbstraction ),
95 textureCache( renderQueue, postProcessDispatcher, context ),
96 resourcePostProcessQueue( resourcePostProcessQ ),
98 backgroundColor( Dali::Stage::DEFAULT_BACKGROUND_COLOR ),
100 lastFrameTime( 0.0f ),
102 renderBufferIndex( SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX ),
103 defaultSurfaceRect(),
106 renderersAdded( false ),
107 firstRenderCompleted( false ),
108 defaultShader( NULL ),
109 programController( glAbstraction )
117 void AddRenderTracker( RenderTracker* renderTracker )
119 DALI_ASSERT_DEBUG( renderTracker != NULL );
120 mRenderTrackers.PushBack( renderTracker );
123 void RemoveRenderTracker( RenderTracker* renderTracker )
125 DALI_ASSERT_DEBUG( renderTracker != NULL );
126 for(RenderTrackerIter iter = mRenderTrackers.Begin(), end = mRenderTrackers.End(); iter != end; ++iter)
128 if( *iter == renderTracker )
130 mRenderTrackers.Erase( iter );
136 void UpdateTrackers()
138 for(RenderTrackerIter iter = mRenderTrackers.Begin(), end = mRenderTrackers.End(); iter != end; ++iter)
140 (*iter)->PollSyncObject();
144 // the order is important for destruction,
145 // programs are owned by context at the moment.
146 Context context; ///< holds the GL state
147 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
148 TextureCache textureCache; ///< Cache for all GL textures
149 ResourcePostProcessList& resourcePostProcessQueue; ///< A queue for requesting resource post processing in update thread
151 // Render instructions describe what should be rendered during RenderManager::Render()
152 // Owned by RenderManager. Update manager updates instructions for the next frame while we render the current one
153 RenderInstructionContainer instructions;
155 Vector4 backgroundColor; ///< The glClear color used at the beginning of each frame.
157 float frameTime; ///< The elapsed time since the previous frame
158 float lastFrameTime; ///< Last frame delta.
160 unsigned int frameCount; ///< The current frame count
161 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
163 Rect<int> defaultSurfaceRect; ///< Rectangle for the default surface we are rendering to
165 RendererOwnerContainer rendererContainer; ///< List of owned renderers
166 SamplerOwnerContainer samplerContainer; ///< List of owned samplers
167 RenderGeometryOwnerContainer renderGeometryContainer; ///< List of owned RenderGeometries
171 RenderTrackerContainer mRenderTrackers; ///< List of render trackers
173 bool firstRenderCompleted; ///< False until the first render is done
174 Shader* defaultShader; ///< Default shader to use
175 ProgramController programController; ///< Owner of the GL programs
178 RenderManager* RenderManager::New( Integration::GlAbstraction& glAbstraction, ResourcePostProcessList& resourcePostProcessQ )
180 RenderManager* manager = new RenderManager;
181 manager->mImpl = new Impl( glAbstraction, resourcePostProcessQ, *manager );
185 RenderManager::RenderManager()
190 RenderManager::~RenderManager()
195 RenderQueue& RenderManager::GetRenderQueue()
197 return mImpl->renderQueue;
200 TextureCache& RenderManager::GetTextureCache()
202 return mImpl->textureCache;
205 void RenderManager::ContextCreated()
207 mImpl->context.GlContextCreated();
208 mImpl->programController.GlContextCreated();
210 // renderers, textures and gpu buffers cannot reinitialize themselves
211 // so they rely on someone reloading the data for them
214 void RenderManager::ContextDestroyed()
216 // @todo Set an atomic value to prevent render manager rendering again until
217 // ContextCreated has been called.
219 mImpl->context.GlContextDestroyed();
220 mImpl->programController.GlContextDestroyed();
222 // inform texture cache
223 mImpl->textureCache.GlContextDestroyed(); // Clears gl texture ids
226 RendererOwnerContainer::Iterator end = mImpl->rendererContainer.End();
227 RendererOwnerContainer::Iterator iter = mImpl->rendererContainer.Begin();
228 for( ; iter != end; ++iter )
230 GlResourceOwner* renderer = *iter;
231 renderer->GlContextDestroyed(); // Clear up vertex buffers
235 void RenderManager::DispatchPostProcessRequest(ResourcePostProcessRequest& request)
237 mImpl->resourcePostProcessQueue[ mImpl->renderBufferIndex ].push_back( request );
240 void RenderManager::SetShaderSaver( ShaderSaver& upstream )
242 mImpl->programController.SetShaderSaver( upstream );
245 RenderInstructionContainer& RenderManager::GetRenderInstructionContainer()
247 return mImpl->instructions;
250 void RenderManager::SetBackgroundColor( const Vector4& color )
252 mImpl->backgroundColor = color;
255 void RenderManager::SetFrameDeltaTime( float deltaTime )
257 mImpl->frameTime = deltaTime;
260 void RenderManager::SetDefaultSurfaceRect(const Rect<int>& rect)
262 mImpl->defaultSurfaceRect = rect;
265 void RenderManager::AddRenderer( Render::Renderer* renderer )
267 // Initialize the renderer as we are now in render thread
268 renderer->Initialize( mImpl->context, mImpl->textureCache );
270 mImpl->rendererContainer.PushBack( renderer );
272 if( !mImpl->renderersAdded )
274 mImpl->renderersAdded = true;
278 void RenderManager::RemoveRenderer( Render::Renderer* renderer )
280 DALI_ASSERT_DEBUG( NULL != renderer );
282 RendererOwnerContainer& renderers = mImpl->rendererContainer;
285 for ( RendererOwnerIter iter = renderers.Begin(); iter != renderers.End(); ++iter )
287 if ( *iter == renderer )
289 renderers.Erase( iter ); // Renderer found; now destroy it
295 void RenderManager::AddSampler( Render::Sampler* sampler )
297 mImpl->samplerContainer.PushBack( sampler );
300 void RenderManager::RemoveSampler( Render::Sampler* sampler )
302 DALI_ASSERT_DEBUG( NULL != sampler );
304 SamplerOwnerContainer& samplers = mImpl->samplerContainer;
307 for ( SamplerOwnerIter iter = samplers.Begin(); iter != samplers.End(); ++iter )
309 if ( *iter == sampler )
311 samplers.Erase( iter ); // Sampler found; now destroy it
317 void RenderManager::SetFilterMode( Render::Sampler* sampler, unsigned int minFilterMode, unsigned int magFilterMode )
319 sampler->SetFilterMode( (Dali::FilterMode::Type)minFilterMode, (Dali::FilterMode::Type)magFilterMode );
322 void RenderManager::SetWrapMode( Render::Sampler* sampler, unsigned int uWrapMode, unsigned int vWrapMode )
324 sampler->SetWrapMode( (Dali::WrapMode::Type)uWrapMode, (Dali::WrapMode::Type)vWrapMode );
327 void RenderManager::AddGeometry( RenderGeometry* renderGeometry )
329 mImpl->renderGeometryContainer.PushBack( renderGeometry );
332 void RenderManager::RemoveGeometry( RenderGeometry* renderGeometry )
334 DALI_ASSERT_DEBUG( NULL != renderGeometry );
336 RenderGeometryOwnerContainer& geometries = mImpl->renderGeometryContainer;
339 for ( RenderGeometryOwnerIter iter = geometries.Begin(); iter != geometries.End(); ++iter )
341 if ( *iter == renderGeometry )
343 geometries.Erase( iter ); // Geometry found; now destroy it
349 void RenderManager::AddPropertyBuffer( RenderGeometry* renderGeometry, PropertyBufferDataProvider* propertyBuffer, const GpuBuffer::Target& target, const GpuBuffer::Usage& usage )
351 DALI_ASSERT_DEBUG( NULL != renderGeometry );
353 RenderGeometryOwnerContainer& geometries = mImpl->renderGeometryContainer;
356 for ( RenderGeometryOwnerIter iter = geometries.Begin(); iter != geometries.End(); ++iter )
358 if ( *iter == renderGeometry )
360 (*iter)->AddPropertyBuffer( propertyBuffer, target, usage );
366 void RenderManager::RemovePropertyBuffer( RenderGeometry* renderGeometry, PropertyBufferDataProvider* propertyBuffer )
368 DALI_ASSERT_DEBUG( NULL != renderGeometry );
370 RenderGeometryOwnerContainer& geometries = mImpl->renderGeometryContainer;
373 for ( RenderGeometryOwnerIter iter = geometries.Begin(); iter != geometries.End(); ++iter )
375 if ( *iter == renderGeometry )
377 (*iter)->RemovePropertyBuffer( propertyBuffer );
384 void RenderManager::AddRenderTracker( RenderTracker* renderTracker )
386 mImpl->AddRenderTracker(renderTracker);
389 void RenderManager::RemoveRenderTracker( RenderTracker* renderTracker )
391 mImpl->RemoveRenderTracker(renderTracker);
394 void RenderManager::SetDefaultShader( Shader* shader )
396 mImpl->defaultShader = shader;
399 ProgramCache* RenderManager::GetProgramCache()
401 return &(mImpl->programController);
404 bool RenderManager::Render( Integration::RenderStatus& status )
406 DALI_PRINT_RENDER_START( mImpl->renderBufferIndex );
408 // Core::Render documents that GL context must be current before calling Render
409 DALI_ASSERT_DEBUG( mImpl->context.IsGlContextCreated() );
411 status.SetHasRendered( false );
413 // Increment the frame count at the beginning of each frame
414 ++(mImpl->frameCount);
415 mImpl->context.SetFrameCount(mImpl->frameCount);
416 mImpl->context.ClearRendererCount();
417 mImpl->context.ClearCulledCount();
419 PERF_MONITOR_START(PerformanceMonitor::DRAW_NODES);
421 SET_SNAPSHOT_FRAME_LOG_LEVEL;
423 // Process messages queued during previous update
424 mImpl->renderQueue.ProcessMessages( mImpl->renderBufferIndex );
426 // No need to make any gl calls if we've done 1st glClear & don't have any renderers to render during startup.
427 if( !mImpl->firstRenderCompleted || mImpl->renderersAdded )
429 // switch rendering to adaptor provided (default) buffer
430 mImpl->context.BindFramebuffer( GL_FRAMEBUFFER, 0 );
432 mImpl->context.Viewport( mImpl->defaultSurfaceRect.x,
433 mImpl->defaultSurfaceRect.y,
434 mImpl->defaultSurfaceRect.width,
435 mImpl->defaultSurfaceRect.height );
437 mImpl->context.ClearColor( mImpl->backgroundColor.r,
438 mImpl->backgroundColor.g,
439 mImpl->backgroundColor.b,
440 mImpl->backgroundColor.a );
442 mImpl->context.ClearStencil( 0 );
444 // Clear the entire color, depth and stencil buffers for the default framebuffer.
445 // It is important to clear all 3 buffers, for performance on deferred renderers like Mali
446 // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
447 // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
448 mImpl->context.SetScissorTest( false );
449 mImpl->context.ColorMask( true );
450 mImpl->context.DepthMask( true );
451 mImpl->context.StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
452 mImpl->context.Clear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, Context::FORCE_CLEAR );
454 // reset the program matrices for all programs once per frame
455 // this ensures we will set view and projection matrix once per program per camera
456 // @todo move programs out of context onto a program controller and let that handle this
457 mImpl->programController.ResetProgramMatrices();
459 // if we don't have default shader, no point doing the render calls
460 if( mImpl->defaultShader )
462 size_t count = mImpl->instructions.Count( mImpl->renderBufferIndex );
463 for ( size_t i = 0; i < count; ++i )
465 RenderInstruction& instruction = mImpl->instructions.At( mImpl->renderBufferIndex, i );
467 DoRender( instruction, *mImpl->defaultShader, mImpl->lastFrameTime );
469 const RenderListContainer::SizeType countRenderList = instruction.RenderListCount();
470 if ( countRenderList > 0 )
472 status.SetHasRendered( true );
475 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
476 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
478 mImpl->UpdateTrackers();
480 mImpl->firstRenderCompleted = true;
484 PERF_MONITOR_END(PerformanceMonitor::DRAW_NODES);
486 // Update the frame time
487 mImpl->lastFrameTime = mImpl->frameTime;
489 // check if anything has been posted to the update thread
490 bool updateRequired = !mImpl->resourcePostProcessQueue[ mImpl->renderBufferIndex ].empty();
492 //Notify RenderGeometries that rendering has finished
493 for ( RenderGeometryOwnerIter iter = mImpl->renderGeometryContainer.Begin(); iter != mImpl->renderGeometryContainer.End(); ++iter )
495 (*iter)->OnRenderFinished();
499 * The rendering has finished; swap to the next buffer.
500 * Ideally the update has just finished using this buffer; otherwise the render thread
501 * should block until the update has finished.
503 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
505 DALI_PRINT_RENDER_END();
507 DALI_PRINT_RENDERER_COUNT(mImpl->frameCount, mImpl->context.GetRendererCount());
508 DALI_PRINT_CULL_COUNT(mImpl->frameCount, mImpl->context.GetCulledCount());
510 return updateRequired;
513 void RenderManager::DoRender( RenderInstruction& instruction, Shader& defaultShader, float elapsedTime )
515 Rect<int> viewportRect;
518 if ( instruction.mIsClearColorSet )
520 clearColor = instruction.mClearColor;
524 clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
527 FrameBufferTexture* offscreen = NULL;
529 if ( instruction.mOffscreenTextureId != 0 )
531 offscreen = mImpl->textureCache.GetFramebuffer( instruction.mOffscreenTextureId );
532 DALI_ASSERT_DEBUG( NULL != offscreen );
534 if( NULL != offscreen &&
535 offscreen->Prepare() )
537 // Check whether a viewport is specified, otherwise the full surface size is used
538 if ( instruction.mIsViewportSet )
540 // For glViewport the lower-left corner is (0,0)
541 const int y = ( offscreen->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
542 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
546 viewportRect.Set( 0, 0, offscreen->GetWidth(), offscreen->GetHeight() );
551 // Offscreen is NULL or could not be prepared.
555 else // !(instruction.mOffscreenTexture)
557 // switch rendering to adaptor provided (default) buffer
558 mImpl->context.BindFramebuffer( GL_FRAMEBUFFER, 0 );
560 // Check whether a viewport is specified, otherwise the full surface size is used
561 if ( instruction.mIsViewportSet )
563 // For glViewport the lower-left corner is (0,0)
564 const int y = ( mImpl->defaultSurfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
565 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
569 viewportRect = mImpl->defaultSurfaceRect;
573 mImpl->context.Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
575 if ( instruction.mIsClearColorSet )
577 mImpl->context.ClearColor( clearColor.r,
582 // Clear the viewport area only
583 mImpl->context.SetScissorTest( true );
584 mImpl->context.Scissor( viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height );
585 mImpl->context.ColorMask( true );
586 mImpl->context.Clear( GL_COLOR_BUFFER_BIT , Context::CHECK_CACHED_VALUES );
587 mImpl->context.SetScissorTest( false );
590 Render::ProcessRenderInstruction( instruction,
594 mImpl->renderBufferIndex,
597 if(instruction.mOffscreenTextureId != 0)
599 GLenum attachments[] = { GL_DEPTH_ATTACHMENT, GL_STENCIL_ATTACHMENT };
600 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
603 if( instruction.mRenderTracker && offscreen != NULL )
605 instruction.mRenderTracker->CreateSyncObject();
606 instruction.mRenderTracker = NULL; // Only create once.
610 } // namespace SceneGraph
612 } // namespace Internal