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