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