Fix some CppCheck errors
[platform/core/uifw/dali-core.git] / dali / internal / render / common / render-algorithms.cpp
1 /*
2  * Copyright (c) 2017 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/render/common/render-algorithms.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/internal/render/common/render-debug.h>
23 #include <dali/internal/render/common/render-list.h>
24 #include <dali/internal/render/common/render-instruction.h>
25 #include <dali/internal/render/gl-resources/context.h>
26 #include <dali/internal/render/renderers/render-renderer.h>
27 #include <dali/internal/update/nodes/scene-graph-layer.h>
28
29 using Dali::Internal::SceneGraph::RenderItem;
30 using Dali::Internal::SceneGraph::RenderList;
31 using Dali::Internal::SceneGraph::RenderListContainer;
32 using Dali::Internal::SceneGraph::RenderInstruction;
33
34 namespace Dali
35 {
36
37 namespace Internal
38 {
39
40 namespace Render
41 {
42
43 namespace
44 {
45
46 // Table for fast look-up of Dali::DepthFunction enum to a GL depth function.
47 // Note: These MUST be in the same order as Dali::DepthFunction enum.
48 const int DaliDepthToGLDepthTable[]  = { GL_NEVER, GL_ALWAYS, GL_LESS, GL_GREATER, GL_EQUAL, GL_NOTEQUAL, GL_LEQUAL, GL_GEQUAL };
49
50 // Table for fast look-up of Dali::StencilFunction enum to a GL stencil function.
51 // Note: These MUST be in the same order as Dali::StencilFunction enum.
52 const int DaliStencilFunctionToGL[]  = { GL_NEVER, GL_LESS, GL_EQUAL, GL_LEQUAL, GL_GREATER, GL_NOTEQUAL, GL_GEQUAL, GL_ALWAYS };
53
54 // Table for fast look-up of Dali::StencilOperation enum to a GL stencil operation.
55 // Note: These MUST be in the same order as Dali::StencilOperation enum.
56 const int DaliStencilOperationToGL[] = { GL_ZERO, GL_KEEP, GL_REPLACE, GL_INCR, GL_DECR, GL_INVERT, GL_INCR_WRAP, GL_DECR_WRAP };
57
58 } // Unnamed namespace
59
60 /**
61  * Sets up the scissor test if required.
62  * @param[in] renderList The render list from which to get the clipping flag
63  * @param[in] context The context
64  */
65 inline void SetScissorTest( const RenderList& renderList, Context& context )
66 {
67   // Scissor testing
68   if( renderList.IsClipping() )
69   {
70     context.SetScissorTest( true );
71
72     const Dali::ClippingBox& clip = renderList.GetClippingBox();
73     context.Scissor( clip.x, clip.y, clip.width, clip.height );
74   }
75   else
76   {
77     context.SetScissorTest( false );
78   }
79 }
80
81 /**
82  * @brief Set up the stencil and color buffer for automatic clipping (StencilMode::AUTO).
83  * @param[in]     item                     The current RenderItem about to be rendered
84  * @param[in]     context                  The context
85  * @param[in/out] lastStencilDepth         The stencil depth of the last renderer drawn.
86  * @param[in/out] lastClippingId           The clipping ID of the last renderer drawn.
87  */
88 inline void SetupClipping( const RenderItem& item, Context& context, uint32_t& lastStencilDepth, uint32_t& lastClippingId )
89 {
90   const Dali::Internal::SceneGraph::Node* node = item.mNode;
91   const uint32_t clippingId = node->GetClippingId();
92
93   // Turn the color buffer on as we always want to render this renderer, regardless of clipping hierarchy.
94   context.ColorMask( true );
95
96   // If there is no clipping Id, then either we haven't reached a clipping Node yet, or there aren't any.
97   // Either way we can skip clipping setup for this renderer.
98   if( clippingId == 0u )
99   {
100     // Exit immediately if there are no clipping actions to perform (EG. we have not yet hit a clipping node).
101     context.EnableStencilBuffer( false );
102     return;
103   }
104
105   const ClippingMode::Type clippingMode( node->GetClippingMode() );
106   const uint32_t currentStencilDepth( node->GetClippingDepth() );
107
108   context.EnableStencilBuffer( true );
109
110   // Pre-calculate a mask which has all bits set up to and including the current clipping depth.
111   // EG. If depth is 3, the mask would be "111" in binary.
112   const uint32_t currentDepthMask = ( 1u << currentStencilDepth ) - 1u;
113
114   // If we have a clipping mode specified, we are writing to the stencil buffer.
115   if( clippingMode != ClippingMode::DISABLED )
116   {
117     // We are writing to the stencil buffer.
118     // If clipping Id is 1, this is the first clipping renderer within this render-list.
119     if( clippingId == 1u )
120     {
121       // We are enabling the stencil-buffer for the first time within this render list.
122       // Clear the buffer at this point.
123       context.StencilMask( 0xff );
124       context.Clear( GL_STENCIL_BUFFER_BIT, Context::CHECK_CACHED_VALUES );
125     }
126     else if( ( currentStencilDepth < lastStencilDepth ) ||
127            ( ( currentStencilDepth == lastStencilDepth ) && ( clippingId > lastClippingId ) ) )
128     {
129       // The above if() statement tests if we need to clear some (not all) stencil bit-planes.
130       // We need to do this if either of the following are true:
131       //   1) We traverse up the scene-graph to a previous stencil depth
132       //   2) We are at the same stencil depth but the clipping Id has increased.
133       //
134       // This calculation takes the new depth to move to, and creates an inverse-mask of that number of consecutive bits.
135       // This has the effect of clearing everything except the bit-planes up to (and including) our current depth.
136       const uint32_t stencilClearMask = ( currentDepthMask >> 1u ) ^ 0xff;
137
138       context.StencilMask( stencilClearMask );
139       context.Clear( GL_STENCIL_BUFFER_BIT, Context::CHECK_CACHED_VALUES );
140     }
141
142     // We keep track of the last clipping Id and depth so we can determine when we are
143     // moving back up the scene graph and require some of the stencil bit-planes to be deleted.
144     lastStencilDepth = currentStencilDepth;
145     lastClippingId = clippingId;
146
147     // We only ever write to bit-planes up to the current depth as we may need
148     // to erase individual bit-planes and revert to a previous clipping area.
149     // Our reference value for testing (in StencilFunc) is written to to the buffer, but we actually
150     // want to test a different value. IE. All the bit-planes up to but not including the current depth.
151     // So we use the Mask parameter of StencilFunc to mask off the top bit-plane when testing.
152     // Here we create our test mask to innore the top bit of the reference test value.
153     // As the mask is made up of contiguous "1" values, we can do this quickly with a bit-shift.
154     const uint32_t testMask = currentDepthMask >> 1u;
155
156     context.StencilFunc( GL_EQUAL, currentDepthMask, testMask ); // Test against existing stencil bit-planes. All must match up to (but not including) this depth.
157     context.StencilMask( currentDepthMask );                     // Write to the new stencil bit-plane (the other previous bit-planes are also written to).
158     context.StencilOp( GL_KEEP, GL_REPLACE, GL_REPLACE );
159   }
160   else
161   {
162     // We are reading from the stencil buffer. Set up the stencil accordingly
163     // This calculation sets all the bits up to the current depth bit.
164     // This has the effect of testing that the pixel being written to exists in every bit-plane up to the current depth.
165     context.StencilFunc( GL_EQUAL, currentDepthMask, 0xff );
166     context.StencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
167   }
168 }
169
170 /**
171  * @brief Set up the stencil and color buffer based on the current Renderers properties.
172  * @param[in]     item                     The current RenderItem about to be rendered
173  * @param[in]     context                  The context
174  * @param[in/out] usedStencilBuffer        True if the stencil buffer has been used so far within this RenderList. Used by StencilMode::ON.
175  * @param[in/out] lastStencilDepth         The stencil depth of the last renderer drawn. Used by the clipping feature.
176  * @param[in/out] lastClippingId           The clipping ID of the last renderer drawn.   Used by the clipping feature.
177  */
178 inline void SetupStencilBuffer( const RenderItem& item, Context& context, bool& usedStencilBuffer, uint32_t& lastStencilDepth, uint32_t& lastClippingId )
179 {
180   const Renderer *renderer = item.mRenderer;
181
182   // Setup the stencil using either the automatic clipping feature, or, the manual per-renderer stencil API.
183   // Note: This switch is in order of most likely value first.
184   RenderMode::Type renderMode = renderer->GetRenderMode();
185   switch( renderMode )
186   {
187     case RenderMode::AUTO:
188     {
189       // The automatic clipping feature will manage the stencil functions and color buffer mask.
190       SetupClipping( item, context, lastStencilDepth, lastClippingId );
191       break;
192     }
193
194     case RenderMode::NONE:
195     case RenderMode::COLOR:
196     {
197       // The stencil buffer will not be used at all.
198       context.EnableStencilBuffer( false );
199
200       // Setup the color buffer based on the RenderMode.
201       context.ColorMask( renderMode == RenderMode::COLOR );
202       break;
203     }
204
205     case RenderMode::STENCIL:
206     case RenderMode::COLOR_STENCIL:
207     {
208       // We are using the low-level Renderer Stencil API.
209       // The stencil buffer must be enabled for every renderer with stencil mode on, as renderers in between can disable it.
210       // Note: As the command state is cached, it is only sent when needed.
211       context.EnableStencilBuffer( true );
212
213       // Setup the color buffer based on the RenderMode.
214       context.ColorMask( renderMode == RenderMode::COLOR_STENCIL );
215
216       // If this is the first use of the stencil buffer within this RenderList, clear it (this avoids unnecessary clears).
217       if( !usedStencilBuffer )
218       {
219         context.Clear( GL_STENCIL_BUFFER_BIT, Context::CHECK_CACHED_VALUES );
220         usedStencilBuffer = true;
221       }
222
223       // Setup the stencil buffer based on the renderers properties.
224       context.StencilFunc( DaliStencilFunctionToGL[ renderer->GetStencilFunction() ],
225           renderer->GetStencilFunctionReference(),
226           renderer->GetStencilFunctionMask() );
227       context.StencilOp( DaliStencilOperationToGL[ renderer->GetStencilOperationOnFail() ],
228           DaliStencilOperationToGL[ renderer->GetStencilOperationOnZFail() ],
229           DaliStencilOperationToGL[ renderer->GetStencilOperationOnZPass() ] );
230       context.StencilMask( renderer->GetStencilMask() );
231       break;
232     }
233   }
234 }
235
236 /**
237  * @brief Sets up the depth buffer for reading and writing based on the current render item.
238  * The items read and write mode are used if specified.
239  *  - If AUTO is selected for reading, the decision will be based on the Layer Behavior.
240  *  - If AUTO is selected for writing, the decision will be based on the items opacity.
241  * @param[in]     item                The RenderItem to set up the depth buffer for.
242  * @param[in]     context             The context used to execute GL commands.
243  * @param[in]     depthTestEnabled    True if depth testing has been enabled.
244  * @param[in/out] firstDepthBufferUse Initialise to true on the first call, this method will set it to false afterwards.
245  */
246 inline void SetupDepthBuffer( const RenderItem& item, Context& context, bool depthTestEnabled, bool& firstDepthBufferUse )
247 {
248   // Set up whether or not to write to the depth buffer.
249   const DepthWriteMode::Type depthWriteMode = item.mRenderer->GetDepthWriteMode();
250   // Most common mode (AUTO) is tested first.
251   const bool enableDepthWrite = ( ( depthWriteMode == DepthWriteMode::AUTO ) && depthTestEnabled && item.mIsOpaque ) ||
252                                 ( depthWriteMode == DepthWriteMode::ON );
253
254   // Set up whether or not to read from (test) the depth buffer.
255   const DepthTestMode::Type depthTestMode = item.mRenderer->GetDepthTestMode();
256   // Most common mode (AUTO) is tested first.
257   const bool enableDepthTest = ( ( depthTestMode == DepthTestMode::AUTO ) && depthTestEnabled ) ||
258                                ( depthTestMode == DepthTestMode::ON );
259
260   // Is the depth buffer in use?
261   if( enableDepthWrite || enableDepthTest )
262   {
263     // The depth buffer must be enabled if either reading or writing.
264     context.EnableDepthBuffer( true );
265
266     // Set up the depth mask based on our depth write setting.
267     context.DepthMask( enableDepthWrite );
268
269     // Look-up the GL depth function from the Dali::DepthFunction enum, and set it.
270     context.DepthFunc( DaliDepthToGLDepthTable[ item.mRenderer->GetDepthFunction() ] );
271
272     // If this is the first use of the depth buffer this RenderTask, perform a clear.
273     // Note: We could do this at the beginning of the RenderTask and rely on the
274     // context cache to ignore the clear if not required, but, we would have to enable
275     // the depth buffer to do so, which could be a redundant enable.
276     if( DALI_UNLIKELY( firstDepthBufferUse ) )
277     {
278       // This is the first time the depth buffer is being written to or read.
279       firstDepthBufferUse = false;
280
281       // Note: The buffer will only be cleared if written to since a previous clear.
282       context.Clear( GL_DEPTH_BUFFER_BIT, Context::CHECK_CACHED_VALUES );
283     }
284   }
285   else
286   {
287     // The depth buffer is not being used by this renderer, so we must disable it to stop it being tested.
288     context.EnableDepthBuffer( false );
289   }
290 }
291
292 /**
293  * @brief Process a render-list.
294  * @param[in] renderList       The render-list to process.
295  * @param[in] context          The GL context.
296  * @param[in] buffer           The current render buffer index (previous update buffer)
297  * @param[in] viewMatrix       The view matrix from the appropriate camera.
298  * @param[in] projectionMatrix The projection matrix from the appropriate camera.
299  */
300 inline void ProcessRenderList(
301   const RenderList& renderList,
302   Context& context,
303   BufferIndex bufferIndex,
304   const Matrix& viewMatrix,
305   const Matrix& projectionMatrix )
306 {
307   DALI_PRINT_RENDER_LIST( renderList );
308
309   SetScissorTest( renderList, context );
310
311   // Note: The depth buffer is enabled or disabled on a per-renderer basis.
312   // Here we pre-calculate the value to use if these modes are set to AUTO.
313   const bool autoDepthTestMode( !( renderList.GetSourceLayer()->IsDepthTestDisabled() ) && renderList.HasColorRenderItems() );
314   const std::size_t count = renderList.Count();
315   uint32_t lastStencilDepth( 0u );
316   uint32_t lastClippingId( 0u );
317   bool usedStencilBuffer( false );
318   bool firstDepthBufferUse( true );
319
320   for( size_t index( 0u ); index < count; ++index )
321   {
322     const RenderItem& item = renderList.GetItem( index );
323     DALI_PRINT_RENDER_ITEM( item );
324
325     // Set up the depth buffer based on per-renderer flags.
326     // If the per renderer flags are set to "ON" or "OFF", they will always override any Layer depth mode or
327     // draw-mode state, such as Overlays.
328     // If the flags are set to "AUTO", the behaviour then depends on the type of renderer. Overlay Renderers will always
329     // disable depth testing and writing. Color Renderers will enable them if the Layer does.
330     SetupDepthBuffer( item, context, autoDepthTestMode, firstDepthBufferUse );
331
332     // Set up the stencil buffer based on both the Renderer and Actor APIs.
333     // The Renderer API will be used if specified. If AUTO, the Actors automatic clipping feature will be used.
334     SetupStencilBuffer( item, context, usedStencilBuffer, lastStencilDepth, lastClippingId );
335
336     // Render the item
337     item.mRenderer->Render( context,
338                             bufferIndex,
339                             *item.mNode,
340                             item.mModelMatrix,
341                             item.mModelViewMatrix,
342                             viewMatrix,
343                             projectionMatrix,
344                             item.mSize,
345                             !item.mIsOpaque );
346   }
347 }
348
349 void ProcessRenderInstruction( const RenderInstruction& instruction,
350                                Context& context,
351                                BufferIndex bufferIndex )
352 {
353   DALI_PRINT_RENDER_INSTRUCTION( instruction, bufferIndex );
354
355   const Matrix* viewMatrix       = instruction.GetViewMatrix( bufferIndex );
356   const Matrix* projectionMatrix = instruction.GetProjectionMatrix( bufferIndex );
357
358   DALI_ASSERT_DEBUG( viewMatrix );
359   DALI_ASSERT_DEBUG( projectionMatrix );
360
361   if( viewMatrix && projectionMatrix )
362   {
363     const RenderListContainer::SizeType count = instruction.RenderListCount();
364
365     // Iterate through each render list in order. If a pair of render lists
366     // are marked as interleaved, then process them together.
367     for( RenderListContainer::SizeType index = 0; index < count; ++index )
368     {
369       const RenderList* renderList = instruction.GetRenderList( index );
370
371       if( renderList && !renderList->IsEmpty() )
372       {
373         ProcessRenderList( *renderList,
374                            context,
375                            bufferIndex,
376                            *viewMatrix,
377                            *projectionMatrix );
378       }
379     }
380   }
381 }
382
383 } // namespace Render
384
385 } // namespace Internal
386
387 } // namespace Dali