717c00b429ae638465b75d00b8ef83be9ccbce8f
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / renderers / mesh / mesh-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 "mesh-renderer.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23 #include <dali/public-api/images/resource-image.h>
24 #include <dali/public-api/common/stage.h>
25 #include <dali/devel-api/adaptor-framework/bitmap-loader.h>
26 #include <dali/devel-api/adaptor-framework/file-loader.h>
27 #include <fstream>
28
29 //INTERNAL INCLUDES
30 #include <dali-toolkit/internal/controls/renderers/renderer-string-constants.h>
31 #include <dali-toolkit/internal/controls/renderers/renderer-factory-impl.h>
32 #include <dali-toolkit/internal/controls/renderers/renderer-factory-cache.h>
33 #include <dali-toolkit/internal/controls/renderers/control-renderer-data-impl.h>
34
35 namespace Dali
36 {
37
38 namespace
39 {
40   /**
41    * @brief Loads a texture from a file
42    * @param[in] imageUrl The url of the file
43    * @param[in] generateMipmaps Indicates whether to generate mipmaps for the texture
44    * @return A texture if loading succeeds, an empty handle otherwise
45    */
46   Texture LoadTexture( const char* imageUrl, bool generateMipmaps )
47   {
48     Texture texture;
49     Dali::BitmapLoader loader = Dali::BitmapLoader::New( imageUrl );
50     loader.Load();
51     PixelData pixelData = loader.GetPixelData();
52     if( pixelData )
53     {
54       texture = Texture::New( TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight() );
55       texture.Upload( pixelData );
56
57       if( generateMipmaps )
58       {
59         texture.GenerateMipmaps();
60       }
61     }
62
63     return texture;
64   }
65 }// unnamed namespace
66
67 namespace Toolkit
68 {
69
70 namespace Internal
71 {
72
73 namespace
74 {
75
76 //Defines ordering of textures for shaders.
77 //All shaders, if including certain texture types, must include them in the same order.
78 //Within the texture set for the renderer, textures are ordered in the same manner.
79 enum TextureIndex
80 {
81   DIFFUSE_INDEX = 0u,
82   NORMAL_INDEX = 1u,
83   GLOSS_INDEX = 2u
84 };
85
86 const char * const LIGHT_POSITION( "uLightPosition" ); //Shader property
87 const char * const OBJECT_MATRIX( "uObjectMatrix" ); //Shader property
88
89 const char * const SHADER_TYPE_TEXTURELESS( "TEXTURELESS" );
90 const char * const SHADER_TYPE_DIFFUSE_TEXTURE( "DIFFUSE_TEXTURE" );
91 const char * const SHADER_TYPE_ALL_TEXTURES( "ALL_TEXTURES" );
92
93 //Shaders
94 //If a shader requires certain textures, they must be listed in order,
95 //as detailed in the TextureIndex enum documentation.
96
97 //A basic shader that doesn't use textures at all.
98 const char* SIMPLE_VERTEX_SHADER = DALI_COMPOSE_SHADER(
99   attribute highp vec3 aPosition;\n
100   attribute highp vec3 aNormal;\n
101   varying mediump vec3 vIllumination;\n
102   uniform mediump vec3 uSize;\n
103   uniform mediump mat4 uMvpMatrix;\n
104   uniform mediump mat4 uModelView;\n
105   uniform mediump mat3 uNormalMatrix;
106   uniform mediump mat4 uObjectMatrix;\n
107   uniform mediump vec3 uLightPosition;\n
108
109   void main()\n
110   {\n
111     vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
112     vertexPosition = uObjectMatrix * vertexPosition;\n
113     vertexPosition = uMvpMatrix * vertexPosition;\n
114
115     //Illumination in Model-View space - Transform attributes and uniforms\n
116     vec4 vertPos = uModelView * vec4( aPosition.xyz, 1.0 );\n
117     vec3 normal = uNormalMatrix * mat3( uObjectMatrix ) * aNormal;\n
118     vec4 centre = uModelView * vec4( 0.0, 0.0, 0.0, 1.0 );\n
119     vec4 lightPos = vec4( centre.x, centre.y, uLightPosition.z, 1.0 );\n
120     vec3 vecToLight = normalize( lightPos.xyz - vertPos.xyz );\n
121
122     float lightDiffuse = max( dot( vecToLight, normal ), 0.0 );\n
123     vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
124
125     gl_Position = vertexPosition;\n
126   }\n
127 );
128
129 //Fragment shader corresponding to the texture-less shader.
130 const char* SIMPLE_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
131   precision mediump float;\n
132   varying mediump vec3 vIllumination;\n
133   uniform lowp vec4 uColor;\n
134
135   void main()\n
136   {\n
137     gl_FragColor = vec4( vIllumination.rgb * uColor.rgb, uColor.a );\n
138   }\n
139 );
140
141 //Diffuse and specular illumination shader with albedo texture. Texture is index 0.
142 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
143   attribute highp vec3 aPosition;\n
144   attribute highp vec2 aTexCoord;\n
145   attribute highp vec3 aNormal;\n
146   varying mediump vec2 vTexCoord;\n
147   varying mediump vec3 vIllumination;\n
148   varying mediump float vSpecular;\n
149   uniform mediump vec3 uSize;\n
150   uniform mediump mat4 uMvpMatrix;\n
151   uniform mediump mat4 uModelView;
152   uniform mediump mat3 uNormalMatrix;
153   uniform mediump mat4 uObjectMatrix;\n
154   uniform mediump vec3 uLightPosition;\n
155
156   void main()
157   {\n
158     vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
159     vertexPosition = uObjectMatrix * vertexPosition;\n
160     vertexPosition = uMvpMatrix * vertexPosition;\n
161
162     //Illumination in Model-View space - Transform attributes and uniforms\n
163     vec4 vertPos = uModelView * vec4( aPosition.xyz, 1.0 );\n
164     vec4 centre = uModelView * vec4( 0.0, 0.0, 0.0, 1.0 );\n
165     vec4 lightPos = vec4( centre.x, centre.y, uLightPosition.z, 1.0 );\n
166     vec3 normal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aNormal );\n
167
168     vec3 vecToLight = normalize( lightPos.xyz - vertPos.xyz );\n
169     vec3 viewDir = normalize( -vertPos.xyz );
170
171     vec3 halfVector = normalize( viewDir + vecToLight );
172
173     float lightDiffuse = dot( vecToLight, normal );\n
174     lightDiffuse = max( 0.0,lightDiffuse );\n
175     vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
176
177     vec3 reflectDir = reflect( -vecToLight, normal );
178     vSpecular = pow( max( dot( reflectDir, viewDir ), 0.0 ), 4.0 );
179
180     vTexCoord = aTexCoord;\n
181     gl_Position = vertexPosition;\n
182   }\n
183 );
184
185 //Fragment shader corresponding to the diffuse and specular illumination shader with albedo texture
186 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
187   precision mediump float;\n
188   varying mediump vec2 vTexCoord;\n
189   varying mediump vec3 vIllumination;\n
190   varying mediump float vSpecular;\n
191   uniform sampler2D sDiffuse;\n
192   uniform lowp vec4 uColor;\n
193
194   void main()\n
195   {\n
196     vec4 texture = texture2D( sDiffuse, vTexCoord );\n
197     gl_FragColor = vec4( vIllumination.rgb * texture.rgb * uColor.rgb + vSpecular * 0.3, texture.a * uColor.a );\n
198   }\n
199 );
200
201 //Diffuse and specular illumination shader with albedo texture, normal map and gloss map shader.
202 //Diffuse (albedo) texture is index 0, normal is 1, gloss is 2. They must be declared in this order.
203 const char* NORMAL_MAP_VERTEX_SHADER = DALI_COMPOSE_SHADER(
204   attribute highp vec3 aPosition;\n
205   attribute highp vec2 aTexCoord;\n
206   attribute highp vec3 aNormal;\n
207   attribute highp vec3 aTangent;\n
208   attribute highp vec3 aBiNormal;\n
209   varying mediump vec2 vTexCoord;\n
210   varying mediump vec3 vLightDirection;\n
211   varying mediump vec3 vHalfVector;\n
212   uniform mediump vec3 uSize;\n
213   uniform mediump mat4 uMvpMatrix;\n
214   uniform mediump mat4 uModelView;
215   uniform mediump mat3 uNormalMatrix;
216   uniform mediump mat4 uObjectMatrix;\n
217   uniform mediump vec3 uLightPosition;\n
218
219   void main()
220   {\n
221     vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
222     vertexPosition = uObjectMatrix * vertexPosition;\n
223     vertexPosition = uMvpMatrix * vertexPosition;\n
224
225     vec4 vertPos = uModelView * vec4( aPosition.xyz, 1.0 );\n
226     vec4 centre = uModelView * vec4( 0.0, 0.0, 0.0, 1.0 );\n
227     vec4 lightPos = vec4( centre.x, centre.y, uLightPosition.z, 1.0 );\n
228
229     vec3 tangent = normalize( uNormalMatrix * aTangent );
230     vec3 binormal = normalize( uNormalMatrix * aBiNormal );
231     vec3 normal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aNormal );
232
233     vec3 vecToLight = normalize( lightPos.xyz - vertPos.xyz );\n
234     vLightDirection.x = dot( vecToLight, tangent );
235     vLightDirection.y = dot( vecToLight, binormal );
236     vLightDirection.z = dot( vecToLight, normal );
237
238     vec3 viewDir = normalize( -vertPos.xyz );
239     vec3 halfVector = normalize( viewDir + vecToLight );
240     vHalfVector.x = dot( halfVector, tangent );
241     vHalfVector.y = dot( halfVector, binormal );
242     vHalfVector.z = dot( halfVector, normal );
243
244     vTexCoord = aTexCoord;\n
245     gl_Position = vertexPosition;\n
246   }\n
247 );
248
249 //Fragment shader corresponding to the shader that uses all textures (diffuse, normal and gloss maps)
250 const char* NORMAL_MAP_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
251   precision mediump float;\n
252   varying mediump vec2 vTexCoord;\n
253   varying mediump vec3 vLightDirection;\n
254   varying mediump vec3 vHalfVector;\n
255   uniform sampler2D sDiffuse;\n
256   uniform sampler2D sNormal;\n
257   uniform sampler2D sGloss;\n
258   uniform lowp vec4 uColor;\n
259
260   void main()\n
261   {\n
262     vec4 texture = texture2D( sDiffuse, vTexCoord );\n
263     vec3 normal = normalize( texture2D( sNormal, vTexCoord ).xyz * 2.0 - 1.0 );\n
264     vec4 glossMap = texture2D( sGloss, vTexCoord );\n
265
266     float lightDiffuse = max( 0.0, dot( normal, normalize( vLightDirection ) ) );\n
267     lightDiffuse = lightDiffuse * 0.5 + 0.5;\n
268
269     float shininess = pow ( max ( dot ( normalize( vHalfVector ), normal ), 0.0 ), 16.0 )  ;
270
271     gl_FragColor = vec4( texture.rgb * uColor.rgb * lightDiffuse + shininess * glossMap.rgb, texture.a * uColor.a );\n
272   }\n
273 );
274
275 } // namespace
276
277 MeshRenderer::MeshRenderer( RendererFactoryCache& factoryCache )
278 : ControlRenderer( factoryCache ),
279   mShaderType( ALL_TEXTURES ),
280   mUseTexture( true ),
281   mUseMipmapping( true )
282 {
283 }
284
285 MeshRenderer::~MeshRenderer()
286 {
287 }
288
289 void MeshRenderer::DoInitialize( Actor& actor, const Property::Map& propertyMap )
290 {
291   Property::Value* objectUrl = propertyMap.Find( OBJECT_URL );
292   if( !objectUrl || !objectUrl->Get( mObjectUrl ) )
293   {
294     DALI_LOG_ERROR( "Fail to provide object URL to the MeshRenderer object.\n" );
295   }
296
297   Property::Value* materialUrl = propertyMap.Find( MATERIAL_URL );
298
299   if( !materialUrl || !materialUrl->Get( mMaterialUrl ) || mMaterialUrl.empty() )
300   {
301     mUseTexture = false;
302   }
303
304   Property::Value* imagesUrl = propertyMap.Find( TEXTURES_PATH );
305   if( !imagesUrl || !imagesUrl->Get( mTexturesPath ) )
306   {
307     //Default behaviour is to assume files are in the same directory,
308     // or have their locations detailed in full when supplied.
309     mTexturesPath.clear();
310   }
311
312   Property::Value* useMipmapping = propertyMap.Find( USE_MIPMAPPING );
313   if( useMipmapping )
314   {
315     useMipmapping->Get( mUseMipmapping );
316   }
317
318   Property::Value* shaderType = propertyMap.Find( SHADER_TYPE );
319   if( shaderType )
320   {
321     std::string shaderTypeString;
322     if( shaderType->Get( shaderTypeString ) )
323     {
324       if( shaderTypeString == SHADER_TYPE_TEXTURELESS )
325       {
326         mShaderType = TEXTURELESS;
327       }
328       else if( shaderTypeString == SHADER_TYPE_DIFFUSE_TEXTURE )
329       {
330         mShaderType = DIFFUSE_TEXTURE;
331       }
332       else if( shaderTypeString == SHADER_TYPE_ALL_TEXTURES )
333       {
334         mShaderType = ALL_TEXTURES;
335       }
336       else
337       {
338         DALI_LOG_ERROR( "Unknown shader type provided to the MeshRenderer object.\n");
339       }
340     }
341   }
342 }
343
344 void MeshRenderer::SetSize( const Vector2& size )
345 {
346   ControlRenderer::SetSize( size );
347
348   // ToDo: renderer responds to the size change
349 }
350
351 void MeshRenderer::SetClipRect( const Rect<int>& clipRect )
352 {
353   ControlRenderer::SetClipRect( clipRect );
354
355   //ToDo: renderer responds to the clipRect change
356 }
357
358 void MeshRenderer::SetOffset( const Vector2& offset )
359 {
360   //ToDo: renderer applies the offset
361 }
362
363 void MeshRenderer::DoSetOnStage( Actor& actor )
364 {
365   InitializeRenderer();
366 }
367
368 void MeshRenderer::DoCreatePropertyMap( Property::Map& map ) const
369 {
370   map.Clear();
371   map.Insert( RENDERER_TYPE, MESH_RENDERER );
372   map.Insert( OBJECT_URL, mObjectUrl );
373   map.Insert( MATERIAL_URL, mMaterialUrl );
374   map.Insert( TEXTURES_PATH, mTexturesPath );
375
376   std::string shaderTypeString;
377   switch( mShaderType )
378   {
379     case ALL_TEXTURES:
380     {
381       shaderTypeString = SHADER_TYPE_ALL_TEXTURES;
382       break;
383     }
384
385     case DIFFUSE_TEXTURE:
386     {
387       shaderTypeString = SHADER_TYPE_DIFFUSE_TEXTURE;
388       break;
389     }
390
391     case TEXTURELESS:
392     {
393       shaderTypeString = SHADER_TYPE_TEXTURELESS;
394       break;
395     }
396   }
397   map.Insert( SHADER_TYPE, shaderTypeString );
398 }
399
400 void MeshRenderer::InitializeRenderer()
401 {
402   //Try to load the geometry from the file.
403   if( !LoadGeometry() )
404   {
405     SupplyEmptyGeometry();
406     return;
407   }
408
409   //If a texture is used by the obj file, load the supplied material file.
410   if( mObjLoader.IsTexturePresent() && !mMaterialUrl.empty() )
411   {
412     if( !LoadMaterial() )
413     {
414       SupplyEmptyGeometry();
415       return;
416     }
417   }
418
419   //Now that the required parts are loaded, create the geometry for the object.
420   if( !CreateGeometry() )
421   {
422     SupplyEmptyGeometry();
423     return;
424   }
425
426   CreateShader();
427
428   //Load the various texture files supplied by the material file.
429   if( !LoadTextures() )
430   {
431     SupplyEmptyGeometry();
432     return;
433   }
434
435   mImpl->mRenderer = Renderer::New( mGeometry, mShader );
436   mImpl->mRenderer.SetTextures( mTextureSet );
437   mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
438 }
439
440 void MeshRenderer::SupplyEmptyGeometry()
441 {
442   mGeometry = Geometry::New();
443   mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
444   mImpl->mRenderer = Renderer::New( mGeometry, mShader );
445
446   DALI_LOG_ERROR( "Initialisation error in mesh renderer.\n" );
447 }
448
449 void MeshRenderer::UpdateShaderUniforms()
450 {
451   Stage stage = Stage::GetCurrent();
452
453   Vector3 lightPosition( 0, 0, stage.GetSize().width );
454   mShader.RegisterProperty( LIGHT_POSITION, lightPosition );
455
456   Matrix scaleMatrix;
457   scaleMatrix.SetIdentityAndScale( Vector3( 1.0, -1.0, 1.0 ) );
458   mShader.RegisterProperty( OBJECT_MATRIX, scaleMatrix );
459 }
460
461 void MeshRenderer::CreateShader()
462 {
463   if( mShaderType == ALL_TEXTURES )
464   {
465     mShader = Shader::New( NORMAL_MAP_VERTEX_SHADER, NORMAL_MAP_FRAGMENT_SHADER );
466   }
467   else if( mShaderType == DIFFUSE_TEXTURE )
468   {
469     mShader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER );
470   }
471   else //Textureless
472   {
473     mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
474   }
475
476   UpdateShaderUniforms();
477 }
478
479 bool MeshRenderer::CreateGeometry()
480 {
481   //Determine if we need to use a simpler shader to handle the provided data
482   if( !mUseTexture || !mObjLoader.IsDiffuseMapPresent() )
483   {
484     mShaderType = TEXTURELESS;
485   }
486   else if( mShaderType == ALL_TEXTURES && (!mObjLoader.IsNormalMapPresent() || !mObjLoader.IsSpecularMapPresent()) )
487   {
488     mShaderType = DIFFUSE_TEXTURE;
489   }
490
491   int objectProperties = 0;
492
493   if( mShaderType == DIFFUSE_TEXTURE ||
494       mShaderType == ALL_TEXTURES )
495   {
496     objectProperties |= ObjLoader::TEXTURE_COORDINATES;
497   }
498
499   if( mShaderType == ALL_TEXTURES )
500   {
501     objectProperties |= ObjLoader::TANGENTS | ObjLoader::BINORMALS;
502   }
503
504   //Create geometry with attributes required by shader.
505   mGeometry = mObjLoader.CreateGeometry( objectProperties );
506
507   if( mGeometry )
508   {
509     return true;
510   }
511
512   DALI_LOG_ERROR( "Failed to load geometry in mesh renderer.\n" );
513   return false;
514 }
515
516 bool MeshRenderer::LoadGeometry()
517 {
518   std::streampos fileSize;
519   Dali::Vector<char> fileContent;
520
521   if( FileLoader::ReadFile( mObjectUrl, fileSize, fileContent, FileLoader::TEXT ) )
522   {
523     mObjLoader.ClearArrays();
524     mObjLoader.LoadObject( fileContent.Begin(), fileSize );
525
526     //Get size information from the obj loaded
527     mSceneCenter = mObjLoader.GetCenter();
528     mSceneSize = mObjLoader.GetSize();
529
530     return true;
531   }
532
533   DALI_LOG_ERROR( "Failed to find object to load in mesh renderer.\n" );
534   return false;
535 }
536
537 bool MeshRenderer::LoadMaterial()
538 {
539   std::streampos fileSize;
540   Dali::Vector<char> fileContent;
541
542   if( FileLoader::ReadFile( mMaterialUrl, fileSize, fileContent, FileLoader::TEXT ) )
543   {
544     //Load data into obj (usable) form
545     mObjLoader.LoadMaterial( fileContent.Begin(), fileSize, mDiffuseTextureUrl, mNormalTextureUrl, mGlossTextureUrl );
546     return true;
547   }
548
549   DALI_LOG_ERROR( "Failed to find texture set to load in mesh renderer.\n" );
550   mUseTexture = false;
551   return false;
552 }
553
554 bool MeshRenderer::LoadTextures()
555 {
556   mTextureSet = TextureSet::New();
557
558   if( mShaderType != TEXTURELESS )
559   {
560     Sampler sampler = Sampler::New();
561     if( mUseMipmapping )
562     {
563       sampler.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR );
564     }
565
566     if( !mDiffuseTextureUrl.empty() )
567     {
568       std::string imageUrl = mTexturesPath + mDiffuseTextureUrl;
569
570       //Load textures
571       Texture diffuseTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
572       if( diffuseTexture )
573       {
574         mTextureSet.SetTexture( DIFFUSE_INDEX, diffuseTexture );
575         mTextureSet.SetSampler( DIFFUSE_INDEX, sampler );
576       }
577       else
578       {
579         DALI_LOG_ERROR( "Failed to load diffuse map texture in mesh renderer.\n");
580         return false;
581       }
582     }
583
584     if( !mNormalTextureUrl.empty() && ( mShaderType == ALL_TEXTURES ) )
585     {
586       std::string imageUrl = mTexturesPath + mNormalTextureUrl;
587
588       //Load textures
589       Texture normalTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
590       if( normalTexture )
591       {
592         mTextureSet.SetTexture( NORMAL_INDEX, normalTexture );
593         mTextureSet.SetSampler( NORMAL_INDEX, sampler );
594       }
595       else
596       {
597         DALI_LOG_ERROR( "Failed to load normal map texture in mesh renderer.\n");
598         return false;
599       }
600     }
601
602     if( !mGlossTextureUrl.empty() && ( mShaderType == ALL_TEXTURES ) )
603     {
604       std::string imageUrl = mTexturesPath + mGlossTextureUrl;
605
606       //Load textures
607       Texture glossTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
608       if( glossTexture )
609       {
610         mTextureSet.SetTexture( GLOSS_INDEX, glossTexture );
611         mTextureSet.SetSampler( GLOSS_INDEX, sampler );
612       }
613       else
614       {
615         DALI_LOG_ERROR( "Failed to load gloss map texture in mesh renderer.\n");
616         return false;
617       }
618     }
619   }
620   return true;
621 }
622
623 } // namespace Internal
624
625 } // namespace Toolkit
626
627 } // namespace Dali