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