Merge "Making DALi core internals typesafe using guaranteed types; uint8_t, uint32_t...
[platform/core/uifw/dali-core.git] / dali / internal / render / renderers / render-renderer.cpp
1 /*
2  * Copyright (c) 2018 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/renderers/render-renderer.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/internal/common/image-sampler.h>
23 #include <dali/internal/render/gl-resources/context.h>
24 #include <dali/internal/render/renderers/render-sampler.h>
25 #include <dali/internal/render/shaders/scene-graph-shader.h>
26 #include <dali/internal/render/shaders/program.h>
27 #include <dali/internal/render/data-providers/node-data-provider.h>
28
29 namespace Dali
30 {
31
32 namespace Internal
33 {
34
35 namespace
36 {
37
38 static Matrix gModelViewProjectionMatrix( false ); ///< a shared matrix to calculate the MVP matrix, dont want to store it in object to reduce storage overhead
39 static Matrix3 gNormalMatrix; ///< a shared matrix to calculate normal matrix, dont want to store it in object to reduce storage overhead
40
41 /**
42  * Helper to set view and projection matrices once per program
43  * @param program to set the matrices to
44  * @param modelMatrix to set
45  * @param viewMatrix to set
46  * @param projectionMatrix to set
47  * @param modelViewMatrix to set
48  * @param modelViewProjectionMatrix to set
49  */
50 inline void SetMatrices( Program& program,
51                          const Matrix& modelMatrix,
52                          const Matrix& viewMatrix,
53                          const Matrix& projectionMatrix,
54                          const Matrix& modelViewMatrix )
55 {
56   GLint loc = program.GetUniformLocation( Program::UNIFORM_MODEL_MATRIX );
57   if( Program::UNIFORM_UNKNOWN != loc )
58   {
59     program.SetUniformMatrix4fv( loc, 1, modelMatrix.AsFloat() );
60   }
61   loc = program.GetUniformLocation( Program::UNIFORM_VIEW_MATRIX );
62   if( Program::UNIFORM_UNKNOWN != loc )
63   {
64     if( program.GetViewMatrix() != &viewMatrix )
65     {
66       program.SetViewMatrix( &viewMatrix );
67       program.SetUniformMatrix4fv( loc, 1, viewMatrix.AsFloat() );
68     }
69   }
70   // set projection matrix if program has not yet received it this frame or if it is dirty
71   loc = program.GetUniformLocation( Program::UNIFORM_PROJECTION_MATRIX );
72   if( Program::UNIFORM_UNKNOWN != loc )
73   {
74     if( program.GetProjectionMatrix() != &projectionMatrix )
75     {
76       program.SetProjectionMatrix( &projectionMatrix );
77       program.SetUniformMatrix4fv( loc, 1, projectionMatrix.AsFloat() );
78     }
79   }
80   loc = program.GetUniformLocation(Program::UNIFORM_MODELVIEW_MATRIX);
81   if( Program::UNIFORM_UNKNOWN != loc )
82   {
83     program.SetUniformMatrix4fv( loc, 1, modelViewMatrix.AsFloat() );
84   }
85
86   loc = program.GetUniformLocation( Program::UNIFORM_MVP_MATRIX );
87   if( Program::UNIFORM_UNKNOWN != loc )
88   {
89     Matrix::Multiply( gModelViewProjectionMatrix, modelViewMatrix, projectionMatrix );
90     program.SetUniformMatrix4fv( loc, 1, gModelViewProjectionMatrix.AsFloat() );
91   }
92
93   loc = program.GetUniformLocation( Program::UNIFORM_NORMAL_MATRIX );
94   if( Program::UNIFORM_UNKNOWN != loc )
95   {
96     gNormalMatrix = modelViewMatrix;
97     gNormalMatrix.Invert();
98     gNormalMatrix.Transpose();
99     program.SetUniformMatrix3fv( loc, 1, gNormalMatrix.AsFloat() );
100   }
101 }
102
103 }
104
105 namespace Render
106 {
107
108 Renderer* Renderer::New( SceneGraph::RenderDataProvider* dataProvider,
109                          Render::Geometry* geometry,
110                          uint32_t blendingBitmask,
111                          const Vector4& blendColor,
112                          FaceCullingMode::Type faceCullingMode,
113                          bool preMultipliedAlphaEnabled,
114                          DepthWriteMode::Type depthWriteMode,
115                          DepthTestMode::Type depthTestMode,
116                          DepthFunction::Type depthFunction,
117                          StencilParameters& stencilParameters )
118 {
119   return new Renderer( dataProvider, geometry, blendingBitmask, blendColor,
120                        faceCullingMode, preMultipliedAlphaEnabled, depthWriteMode, depthTestMode,
121                        depthFunction, stencilParameters );
122 }
123
124 Renderer::Renderer( SceneGraph::RenderDataProvider* dataProvider,
125                     Render::Geometry* geometry,
126                     uint32_t blendingBitmask,
127                     const Vector4& blendColor,
128                     FaceCullingMode::Type faceCullingMode,
129                     bool preMultipliedAlphaEnabled,
130                     DepthWriteMode::Type depthWriteMode,
131                     DepthTestMode::Type depthTestMode,
132                     DepthFunction::Type depthFunction,
133                     StencilParameters& stencilParameters )
134 : mRenderDataProvider( dataProvider ),
135   mContext( NULL),
136   mGeometry( geometry ),
137   mUniformIndexMap(),
138   mAttributesLocation(),
139   mStencilParameters( stencilParameters ),
140   mBlendingOptions(),
141   mIndexedDrawFirstElement( 0 ),
142   mIndexedDrawElementsCount( 0 ),
143   mDepthFunction( depthFunction ),
144   mFaceCullingMode( faceCullingMode ),
145   mDepthWriteMode( depthWriteMode ),
146   mDepthTestMode( depthTestMode ),
147   mUpdateAttributesLocation( true ),
148   mPremultipledAlphaEnabled( preMultipliedAlphaEnabled )
149 {
150   if( blendingBitmask != 0u )
151   {
152     mBlendingOptions.SetBitmask( blendingBitmask );
153   }
154
155   mBlendingOptions.SetBlendColor( blendColor );
156 }
157
158 void Renderer::Initialize( Context& context )
159 {
160   mContext = &context;
161 }
162
163 Renderer::~Renderer()
164 {
165 }
166
167 void Renderer::SetGeometry( Render::Geometry* geometry )
168 {
169   mGeometry = geometry;
170   mUpdateAttributesLocation = true;
171 }
172
173 void Renderer::SetBlending( Context& context, bool blend )
174 {
175   context.SetBlend( blend );
176   if( blend )
177   {
178     // Blend color is optional and rarely used
179     const Vector4* blendColor = mBlendingOptions.GetBlendColor();
180     if( blendColor )
181     {
182       context.SetCustomBlendColor( *blendColor );
183     }
184     else
185     {
186       context.SetDefaultBlendColor();
187     }
188
189     // Set blend source & destination factors
190     context.BlendFuncSeparate( mBlendingOptions.GetBlendSrcFactorRgb(),
191                                mBlendingOptions.GetBlendDestFactorRgb(),
192                                mBlendingOptions.GetBlendSrcFactorAlpha(),
193                                mBlendingOptions.GetBlendDestFactorAlpha() );
194
195     // Set blend equations
196     context.BlendEquationSeparate( mBlendingOptions.GetBlendEquationRgb(),
197                                    mBlendingOptions.GetBlendEquationAlpha() );
198   }
199 }
200
201 void Renderer::GlContextDestroyed()
202 {
203   mGeometry->GlContextDestroyed();
204 }
205
206 void Renderer::GlCleanup()
207 {
208 }
209
210 void Renderer::SetUniforms( BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program )
211 {
212   // Check if the map has changed
213   DALI_ASSERT_DEBUG( mRenderDataProvider && "No Uniform map data provider available" );
214
215   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
216
217   if( uniformMapDataProvider.GetUniformMapChanged( bufferIndex ) ||
218       node.GetUniformMapChanged(bufferIndex) ||
219       mUniformIndexMap.Count() == 0)
220   {
221     const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap( bufferIndex );
222     const SceneGraph::CollectedUniformMap& uniformMapNode = node.GetUniformMap( bufferIndex );
223
224     uint32_t maxMaps = static_cast<uint32_t>( uniformMap.Count() + uniformMapNode.Count() ); // 4,294,967,295 maps should be enough
225     mUniformIndexMap.Clear(); // Clear contents, but keep memory if we don't change size
226     mUniformIndexMap.Resize( maxMaps );
227
228     uint32_t mapIndex = 0;
229     for(; mapIndex < uniformMap.Count() ; ++mapIndex )
230     {
231       mUniformIndexMap[mapIndex].propertyValue = uniformMap[mapIndex]->propertyPtr;
232       mUniformIndexMap[mapIndex].uniformIndex = program.RegisterUniform( uniformMap[mapIndex]->uniformName );
233     }
234
235     for( uint32_t nodeMapIndex = 0; nodeMapIndex < uniformMapNode.Count() ; ++nodeMapIndex )
236     {
237       uint32_t uniformIndex = program.RegisterUniform( uniformMapNode[nodeMapIndex]->uniformName );
238       bool found(false);
239       for( uint32_t i = 0; i<uniformMap.Count(); ++i )
240       {
241         if( mUniformIndexMap[i].uniformIndex == uniformIndex )
242         {
243           mUniformIndexMap[i].propertyValue = uniformMapNode[nodeMapIndex]->propertyPtr;
244           found = true;
245           break;
246         }
247       }
248
249       if( !found )
250       {
251         mUniformIndexMap[mapIndex].propertyValue = uniformMapNode[nodeMapIndex]->propertyPtr;
252         mUniformIndexMap[mapIndex].uniformIndex = uniformIndex;
253         ++mapIndex;
254       }
255     }
256
257     mUniformIndexMap.Resize( mapIndex );
258   }
259
260   // Set uniforms in local map
261   for( UniformIndexMappings::Iterator iter = mUniformIndexMap.Begin(),
262          end = mUniformIndexMap.End() ;
263        iter != end ;
264        ++iter )
265   {
266     SetUniformFromProperty( bufferIndex, program, *iter );
267   }
268
269   GLint sizeLoc = program.GetUniformLocation( Program::UNIFORM_SIZE );
270   if( -1 != sizeLoc )
271   {
272     program.SetSizeUniform3f( sizeLoc, size.x, size.y, size.z );
273   }
274 }
275
276 void Renderer::SetUniformFromProperty( BufferIndex bufferIndex, Program& program, UniformIndexMap& map )
277 {
278   GLint location = program.GetUniformLocation(map.uniformIndex);
279   if( Program::UNIFORM_UNKNOWN != location )
280   {
281     // switch based on property type to use correct GL uniform setter
282     switch ( map.propertyValue->GetType() )
283     {
284       case Property::INTEGER:
285       {
286         program.SetUniform1i( location, map.propertyValue->GetInteger( bufferIndex ) );
287         break;
288       }
289       case Property::FLOAT:
290       {
291         program.SetUniform1f( location, map.propertyValue->GetFloat( bufferIndex ) );
292         break;
293       }
294       case Property::VECTOR2:
295       {
296         Vector2 value( map.propertyValue->GetVector2( bufferIndex ) );
297         program.SetUniform2f( location, value.x, value.y );
298         break;
299       }
300
301       case Property::VECTOR3:
302       {
303         Vector3 value( map.propertyValue->GetVector3( bufferIndex ) );
304         program.SetUniform3f( location, value.x, value.y, value.z );
305         break;
306       }
307
308       case Property::VECTOR4:
309       {
310         Vector4 value( map.propertyValue->GetVector4( bufferIndex ) );
311         program.SetUniform4f( location, value.x, value.y, value.z, value.w );
312         break;
313       }
314
315       case Property::ROTATION:
316       {
317         Quaternion value( map.propertyValue->GetQuaternion( bufferIndex ) );
318         program.SetUniform4f( location, value.mVector.x, value.mVector.y, value.mVector.z, value.mVector.w );
319         break;
320       }
321
322       case Property::MATRIX:
323       {
324         const Matrix& value = map.propertyValue->GetMatrix(bufferIndex);
325         program.SetUniformMatrix4fv(location, 1, value.AsFloat() );
326         break;
327       }
328
329       case Property::MATRIX3:
330       {
331         const Matrix3& value = map.propertyValue->GetMatrix3(bufferIndex);
332         program.SetUniformMatrix3fv(location, 1, value.AsFloat() );
333         break;
334       }
335
336       default:
337       {
338         // Other property types are ignored
339         break;
340       }
341     }
342   }
343 }
344
345 bool Renderer::BindTextures( Context& context, Program& program )
346 {
347   uint32_t textureUnit = 0;
348   bool result = true;
349
350   GLint uniformLocation(-1);
351   std::vector<Render::Sampler*>& samplers( mRenderDataProvider->GetSamplers() );
352   std::vector<Render::Texture*>& textures( mRenderDataProvider->GetTextures() );
353   for( uint32_t i = 0; i < static_cast<uint32_t>( textures.size() ) && result; ++i ) // not expecting more than uint32_t of textures
354   {
355     if( textures[i] )
356     {
357       result = textures[i]->Bind(context, textureUnit, samplers[i] );
358       if( result && program.GetSamplerUniformLocation( i, uniformLocation ) )
359       {
360         program.SetUniform1i( uniformLocation, textureUnit );
361         ++textureUnit;
362       }
363     }
364   }
365
366   return result;
367 }
368
369 void Renderer::SetFaceCullingMode( FaceCullingMode::Type mode )
370 {
371   mFaceCullingMode =  mode;
372 }
373
374 void Renderer::SetBlendingBitMask( uint32_t bitmask )
375 {
376   mBlendingOptions.SetBitmask( bitmask );
377 }
378
379 void Renderer::SetBlendColor( const Vector4& color )
380 {
381   mBlendingOptions.SetBlendColor( color );
382 }
383
384 void Renderer::SetIndexedDrawFirstElement( uint32_t firstElement )
385 {
386   mIndexedDrawFirstElement = firstElement;
387 }
388
389 void Renderer::SetIndexedDrawElementsCount( uint32_t elementsCount )
390 {
391   mIndexedDrawElementsCount = elementsCount;
392 }
393
394 void Renderer::EnablePreMultipliedAlpha( bool enable )
395 {
396   mPremultipledAlphaEnabled = enable;
397 }
398
399 void Renderer::SetDepthWriteMode( DepthWriteMode::Type depthWriteMode )
400 {
401   mDepthWriteMode = depthWriteMode;
402 }
403
404 void Renderer::SetDepthTestMode( DepthTestMode::Type depthTestMode )
405 {
406   mDepthTestMode = depthTestMode;
407 }
408
409 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
410 {
411   return mDepthWriteMode;
412 }
413
414 DepthTestMode::Type Renderer::GetDepthTestMode() const
415 {
416   return mDepthTestMode;
417 }
418
419 void Renderer::SetDepthFunction( DepthFunction::Type depthFunction )
420 {
421   mDepthFunction = depthFunction;
422 }
423
424 DepthFunction::Type Renderer::GetDepthFunction() const
425 {
426   return mDepthFunction;
427 }
428
429 void Renderer::SetRenderMode( RenderMode::Type renderMode )
430 {
431   mStencilParameters.renderMode = renderMode;
432 }
433
434 RenderMode::Type Renderer::GetRenderMode() const
435 {
436   return mStencilParameters.renderMode;
437 }
438
439 void Renderer::SetStencilFunction( StencilFunction::Type stencilFunction )
440 {
441   mStencilParameters.stencilFunction = stencilFunction;
442 }
443
444 StencilFunction::Type Renderer::GetStencilFunction() const
445 {
446   return mStencilParameters.stencilFunction;
447 }
448
449 void Renderer::SetStencilFunctionMask( int stencilFunctionMask )
450 {
451   mStencilParameters.stencilFunctionMask = stencilFunctionMask;
452 }
453
454 int Renderer::GetStencilFunctionMask() const
455 {
456   return mStencilParameters.stencilFunctionMask;
457 }
458
459 void Renderer::SetStencilFunctionReference( int stencilFunctionReference )
460 {
461   mStencilParameters.stencilFunctionReference = stencilFunctionReference;
462 }
463
464 int Renderer::GetStencilFunctionReference() const
465 {
466   return mStencilParameters.stencilFunctionReference;
467 }
468
469 void Renderer::SetStencilMask( int stencilMask )
470 {
471   mStencilParameters.stencilMask = stencilMask;
472 }
473
474 int Renderer::GetStencilMask() const
475 {
476   return mStencilParameters.stencilMask;
477 }
478
479 void Renderer::SetStencilOperationOnFail( StencilOperation::Type stencilOperationOnFail )
480 {
481   mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
482 }
483
484 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
485 {
486   return mStencilParameters.stencilOperationOnFail;
487 }
488
489 void Renderer::SetStencilOperationOnZFail( StencilOperation::Type stencilOperationOnZFail )
490 {
491   mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
492 }
493
494 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
495 {
496   return mStencilParameters.stencilOperationOnZFail;
497 }
498
499 void Renderer::SetStencilOperationOnZPass( StencilOperation::Type stencilOperationOnZPass )
500 {
501   mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
502 }
503
504 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
505 {
506   return mStencilParameters.stencilOperationOnZPass;
507 }
508
509 void Renderer::Render( Context& context,
510                        BufferIndex bufferIndex,
511                        const SceneGraph::NodeDataProvider& node,
512                        const Matrix& modelMatrix,
513                        const Matrix& modelViewMatrix,
514                        const Matrix& viewMatrix,
515                        const Matrix& projectionMatrix,
516                        const Vector3& size,
517                        bool blend )
518 {
519   // Get the program to use:
520   Program* program = mRenderDataProvider->GetShader().GetProgram();
521   if( !program )
522   {
523     DALI_LOG_ERROR( "Failed to get program for shader at address %p.\n", reinterpret_cast< void* >( &mRenderDataProvider->GetShader() ) );
524     return;
525   }
526
527   //Set cull face  mode
528   context.CullFace( mFaceCullingMode );
529
530   //Set blending mode
531   SetBlending( context, blend );
532
533   // Take the program into use so we can send uniforms to it
534   program->Use();
535
536   if( DALI_LIKELY( BindTextures( context, *program ) ) )
537   {
538     // Only set up and draw if we have textures and they are all valid
539
540     // set projection and view matrix if program has not yet received them yet this frame
541     SetMatrices( *program, modelMatrix, viewMatrix, projectionMatrix, modelViewMatrix );
542
543     // set color uniform
544     GLint loc = program->GetUniformLocation( Program::UNIFORM_COLOR );
545     if( Program::UNIFORM_UNKNOWN != loc )
546     {
547       const Vector4& color = node.GetRenderColor( bufferIndex );
548       if( mPremultipledAlphaEnabled )
549       {
550         float alpha = color.a * mRenderDataProvider->GetOpacity( bufferIndex );
551         program->SetUniform4f( loc, color.r * alpha, color.g * alpha, color.b * alpha, alpha );
552       }
553       else
554       {
555         program->SetUniform4f( loc, color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity( bufferIndex ) );
556       }
557     }
558
559     SetUniforms( bufferIndex, node, size, *program );
560
561     if( mUpdateAttributesLocation || mGeometry->AttributesChanged() )
562     {
563       mGeometry->GetAttributeLocationFromProgram( mAttributesLocation, *program, bufferIndex );
564       mUpdateAttributesLocation = false;
565     }
566
567     mGeometry->UploadAndDraw( context,
568                               bufferIndex,
569                               mAttributesLocation,
570                               mIndexedDrawFirstElement,
571                               mIndexedDrawElementsCount );
572   }
573 }
574
575 void Renderer::SetSortAttributes( BufferIndex bufferIndex,
576                                   SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes ) const
577 {
578   sortAttributes.shader = &( mRenderDataProvider->GetShader() );
579   sortAttributes.geometry = mGeometry;
580 }
581
582 } // namespace SceneGraph
583
584 } // namespace Internal
585
586 } // namespace Dali