Merge "Add Visual descriptions to generate doxygen page" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / mesh / mesh-visual.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-visual.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23 #include <dali/public-api/common/stage.h>
24 #include <dali/devel-api/adaptor-framework/bitmap-loader.h>
25 #include <dali/devel-api/adaptor-framework/file-loader.h>
26 #include <dali/devel-api/scripting/enum-helper.h>
27 #include <dali/devel-api/scripting/scripting.h>
28 #include <fstream>
29
30 //INTERNAL INCLUDES
31 #include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
32 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
33 #include <dali-toolkit/internal/visuals/visual-string-constants.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 //Property names
87 const char * const OBJECT_URL_NAME( "objectUrl" );
88 const char * const MATERIAL_URL_NAME( "materialUrl" );
89 const char * const TEXTURES_PATH_NAME( "texturesPath" );
90 const char * const SHADING_MODE_NAME( "shadingMode" );
91 const char * const USE_MIPMAPPING_NAME( "useMipmapping" );
92 const char * const USE_SOFT_NORMALS_NAME( "useSoftNormals" );
93 const char * const LIGHT_POSITION_NAME( "lightPosition" );
94
95 //Shading mode
96 DALI_ENUM_TO_STRING_TABLE_BEGIN( SHADING_MODE )
97 DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURELESS_WITH_DIFFUSE_LIGHTING )
98 DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_SPECULAR_LIGHTING )
99 DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
100 DALI_ENUM_TO_STRING_TABLE_END( SHADING_MODE )
101
102 //Shader properties
103 const char * const OBJECT_MATRIX_UNIFORM_NAME( "uObjectMatrix" );
104 const char * const STAGE_OFFSET_UNIFORM_NAME( "uStageOffset" );
105
106 //Shaders
107 //If a shader requires certain textures, they must be listed in order,
108 //as detailed in the TextureIndex enum documentation.
109
110 //A basic shader that doesn't use textures at all.
111 const char* SIMPLE_VERTEX_SHADER = DALI_COMPOSE_SHADER(
112   attribute highp vec3 aPosition;\n
113   attribute highp vec3 aNormal;\n
114   varying mediump vec3 vIllumination;\n
115   uniform mediump vec3 uSize;\n
116   uniform mediump mat4 uMvpMatrix;\n
117   uniform mediump mat4 uModelView;\n
118   uniform mediump mat4 uViewMatrix;\n
119   uniform mediump mat3 uNormalMatrix;
120   uniform mediump mat4 uObjectMatrix;\n
121   uniform mediump vec3 lightPosition;\n
122   uniform mediump vec2 uStageOffset;\n
123
124   //Visual size and offset
125   uniform mediump vec2 offset;\n
126   uniform mediump vec2 size;\n
127   uniform mediump vec4 offsetSizeMode;\n
128   uniform mediump vec2 origin;\n
129   uniform mediump vec2 anchorPoint;\n
130
131   vec4 ComputeVertexPosition()\n
132   {\n
133     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
134     float scaleFactor = min( visualSize.x, visualSize.y );\n
135     vec3 originFlipY =  vec3(origin.x, -origin.y, 0.0);
136     vec3 anchorPointFlipY = vec3( anchorPoint.x, -anchorPoint.y, 0.0);
137     vec3 offset = vec3( ( offset / uSize.xy ) * offsetSizeMode.xy + offset * (1.0-offsetSizeMode.xy), 0.0) * vec3(1.0,-1.0,1.0);\n
138     return vec4( (aPosition + anchorPointFlipY)*scaleFactor + (offset + originFlipY)*uSize, 1.0 );\n
139   }\n
140
141   void main()\n
142   {\n
143     vec4 normalisedVertexPosition = ComputeVertexPosition();\n
144     vec4 vertexPosition = uObjectMatrix * normalisedVertexPosition;\n
145     vertexPosition = uMvpMatrix * vertexPosition;\n
146
147     //Illumination in Model-View space - Transform attributes and uniforms\n
148     vec4 mvVertexPosition = uModelView * normalisedVertexPosition;\n
149     vec3 normal = uNormalMatrix * mat3( uObjectMatrix ) * aNormal;\n
150
151     vec4 mvLightPosition = vec4( ( lightPosition.xy - uStageOffset ), lightPosition.z, 1.0 );\n
152     mvLightPosition = uViewMatrix * mvLightPosition;\n
153     vec3 vectorToLight = normalize( mvLightPosition.xyz - mvVertexPosition.xyz );\n
154
155     float lightDiffuse = max( dot( vectorToLight, normal ), 0.0 );\n
156     vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
157
158     gl_Position = vertexPosition;\n
159   }\n
160 );
161
162 //Fragment shader corresponding to the texture-less shader.
163 const char* SIMPLE_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
164   precision mediump float;\n
165   varying mediump vec3 vIllumination;\n
166   uniform lowp vec4 uColor;\n
167   uniform lowp vec4 mixColor;\n
168   uniform lowp float preMultipliedAlpha;\n
169
170   lowp vec4 visualMixColor()\n
171   {\n
172     return vec4( mixColor.rgb * mix( 1.0, mixColor.a, preMultipliedAlpha ), mixColor.a );\n
173   }\n
174   void main()\n
175   {\n
176     gl_FragColor = vec4( vIllumination.rgb * uColor.rgb, uColor.a ) * visualMixColor();\n
177   }\n
178 );
179
180 //Diffuse and specular illumination shader with albedo texture. Texture is index 0.
181 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
182   attribute highp vec3 aPosition;\n
183   attribute highp vec2 aTexCoord;\n
184   attribute highp vec3 aNormal;\n
185   varying mediump vec2 vTexCoord;\n
186   varying mediump vec3 vIllumination;\n
187   varying mediump float vSpecular;\n
188   uniform mediump vec3 uSize;\n
189   uniform mediump mat4 uMvpMatrix;\n
190   uniform mediump mat4 uModelView;
191   uniform mediump mat4 uViewMatrix;\n
192   uniform mediump mat3 uNormalMatrix;
193   uniform mediump mat4 uObjectMatrix;\n
194   uniform mediump vec3 lightPosition;\n
195   uniform mediump vec2 uStageOffset;\n
196
197   //Visual size and offset
198   uniform mediump vec2 offset;\n
199   uniform mediump vec2 size;\n
200   uniform mediump vec4 offsetSizeMode;\n
201   uniform mediump vec2 origin;\n
202   uniform mediump vec2 anchorPoint;\n
203
204   vec4 ComputeVertexPosition()\n
205   {\n
206     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
207     float scaleFactor = min( visualSize.x, visualSize.y );\n
208     vec3 originFlipY =  vec3(origin.x, -origin.y, 0.0);
209     vec3 anchorPointFlipY = vec3( anchorPoint.x, -anchorPoint.y, 0.0);
210     vec3 offset = vec3( ( offset / uSize.xy ) * offsetSizeMode.xy + offset * (1.0-offsetSizeMode.xy), 0.0) * vec3(1.0,-1.0,1.0);\n
211     return vec4( (aPosition + anchorPointFlipY)*scaleFactor + (offset + originFlipY)*uSize, 1.0 );\n
212   }\n
213
214   void main()
215   {\n
216     vec4 normalisedVertexPosition = ComputeVertexPosition();\n
217     vec4 vertexPosition = uObjectMatrix * normalisedVertexPosition;\n
218     vertexPosition = uMvpMatrix * vertexPosition;\n
219
220     //Illumination in Model-View space - Transform attributes and uniforms\n
221     vec4 mvVertexPosition = uModelView * normalisedVertexPosition;\n
222     vec3 normal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aNormal );\n
223
224     vec4 mvLightPosition = vec4( ( lightPosition.xy - uStageOffset ), lightPosition.z, 1.0 );\n
225     mvLightPosition = uViewMatrix * mvLightPosition;\n
226     vec3 vectorToLight = normalize( mvLightPosition.xyz - mvVertexPosition.xyz );\n
227
228     vec3 viewDirection = normalize( -mvVertexPosition.xyz );
229
230     float lightDiffuse = dot( vectorToLight, normal );\n
231     lightDiffuse = max( 0.0,lightDiffuse );\n
232     vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
233
234     vec3 reflectDirection = reflect( -vectorToLight, normal );
235     vSpecular = pow( max( dot( reflectDirection, viewDirection ), 0.0 ), 4.0 );
236
237     vTexCoord = aTexCoord;\n
238     gl_Position = vertexPosition;\n
239   }\n
240 );
241
242 //Fragment shader corresponding to the diffuse and specular illumination shader with albedo texture
243 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
244   precision mediump float;\n
245   varying mediump vec2 vTexCoord;\n
246   varying mediump vec3 vIllumination;\n
247   varying mediump float vSpecular;\n
248   uniform sampler2D sDiffuse;\n
249   uniform lowp vec4 uColor;\n
250   uniform lowp vec4 mixColor;\n
251   uniform lowp float preMultipliedAlpha;\n
252
253   lowp vec4 visualMixColor()\n
254   {\n
255     return vec4( mixColor.rgb * mix( 1.0, mixColor.a, preMultipliedAlpha ), mixColor.a );\n
256   }\n
257   void main()\n
258   {\n
259     vec4 texture = texture2D( sDiffuse, vTexCoord );\n
260     vec4 visualMixColor = visualMixColor();\n
261     gl_FragColor = vec4( vIllumination.rgb * texture.rgb * uColor.rgb * visualMixColor.rgb + vSpecular * 0.3, texture.a * uColor.a * visualMixColor.a );\n
262   }\n
263 );
264
265 //Diffuse and specular illumination shader with albedo texture, normal map and gloss map shader.
266 //Diffuse (albedo) texture is index 0, normal is 1, gloss is 2. They must be declared in this order.
267 const char* NORMAL_MAP_VERTEX_SHADER = DALI_COMPOSE_SHADER(
268   attribute highp vec3 aPosition;\n
269   attribute highp vec2 aTexCoord;\n
270   attribute highp vec3 aNormal;\n
271   attribute highp vec3 aTangent;\n
272   attribute highp vec3 aBiNormal;\n
273   varying mediump vec2 vTexCoord;\n
274   varying mediump vec3 vLightDirection;\n
275   varying mediump vec3 vHalfVector;\n
276   uniform mediump vec3 uSize;\n
277   uniform mediump mat4 uMvpMatrix;\n
278   uniform mediump mat4 uModelView;
279   uniform mediump mat4 uViewMatrix;\n
280   uniform mediump mat3 uNormalMatrix;
281   uniform mediump mat4 uObjectMatrix;\n
282   uniform mediump vec3 lightPosition;\n
283   uniform mediump vec2 uStageOffset;\n
284
285   //Visual size and offset
286   uniform mediump vec2 offset;\n
287   uniform mediump vec2 size;\n
288   uniform mediump vec4 offsetSizeMode;\n
289   uniform mediump vec2 origin;\n
290   uniform mediump vec2 anchorPoint;\n
291
292   vec4 ComputeVertexPosition()\n
293   {\n
294     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
295     float scaleFactor = min( visualSize.x, visualSize.y );\n
296     vec3 originFlipY =  vec3(origin.x, -origin.y, 0.0);
297     vec3 anchorPointFlipY = vec3( anchorPoint.x, -anchorPoint.y, 0.0);
298     vec3 offset = vec3( ( offset / uSize.xy ) * offsetSizeMode.xy + offset * (1.0-offsetSizeMode.xy), 0.0) * vec3(1.0,-1.0,1.0);\n
299     return vec4( (aPosition + anchorPointFlipY)*scaleFactor + (offset + originFlipY)*uSize, 1.0 );\n
300   }\n
301
302   void main()
303   {\n
304     vec4 normalisedVertexPosition = ComputeVertexPosition();\n
305     vec4 vertexPosition = uObjectMatrix * normalisedVertexPosition;\n
306     vertexPosition = uMvpMatrix * vertexPosition;\n
307
308     vec4 mvVertexPosition = uModelView * normalisedVertexPosition;\n
309
310     vec3 tangent = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aTangent );
311     vec3 binormal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aBiNormal );
312     vec3 normal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aNormal );
313
314     vec4 mvLightPosition = vec4( ( lightPosition.xy - uStageOffset ), lightPosition.z, 1.0 );\n
315     mvLightPosition = uViewMatrix * mvLightPosition;\n
316     vec3 vectorToLight = normalize( mvLightPosition.xyz - mvVertexPosition.xyz );\n
317     vLightDirection.x = dot( vectorToLight, tangent );
318     vLightDirection.y = dot( vectorToLight, binormal );
319     vLightDirection.z = dot( vectorToLight, normal );
320
321     vec3 viewDirection = normalize( -mvVertexPosition.xyz );
322     vec3 halfVector = normalize( viewDirection + vectorToLight );
323     vHalfVector.x = dot( halfVector, tangent );
324     vHalfVector.y = dot( halfVector, binormal );
325     vHalfVector.z = dot( halfVector, normal );
326
327     vTexCoord = aTexCoord;\n
328     gl_Position = vertexPosition;\n
329   }\n
330 );
331
332 //Fragment shader corresponding to the shader that uses all textures (diffuse, normal and gloss maps)
333 const char* NORMAL_MAP_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
334   precision mediump float;\n
335   varying mediump vec2 vTexCoord;\n
336   varying mediump vec3 vLightDirection;\n
337   varying mediump vec3 vHalfVector;\n
338   uniform sampler2D sDiffuse;\n
339   uniform sampler2D sNormal;\n
340   uniform sampler2D sGloss;\n
341   uniform lowp vec4 uColor;\n
342   uniform lowp vec4 mixColor;\n
343   uniform lowp float preMultipliedAlpha;\n
344
345   lowp vec4 visualMixColor()\n
346   {\n
347     return vec4( mixColor.rgb * mix( 1.0, mixColor.a, preMultipliedAlpha ), mixColor.a );\n
348   }\n
349   void main()\n
350   {\n
351     vec4 texture = texture2D( sDiffuse, vTexCoord );\n
352     vec3 normal = normalize( texture2D( sNormal, vTexCoord ).xyz * 2.0 - 1.0 );\n
353     vec4 glossMap = texture2D( sGloss, vTexCoord );\n
354     vec4 visualMixColor = visualMixColor();\n
355
356     float lightDiffuse = max( 0.0, dot( normal, normalize( vLightDirection ) ) );\n
357     lightDiffuse = lightDiffuse * 0.5 + 0.5;\n
358
359     float shininess = pow ( max ( dot ( normalize( vHalfVector ), normal ), 0.0 ), 16.0 )  ;
360
361     gl_FragColor = vec4( texture.rgb * uColor.rgb * visualMixColor.rgb * lightDiffuse + shininess * glossMap.rgb, texture.a * uColor.a * visualMixColor.a );\n
362   }\n
363 );
364
365 } // unnamed namespace
366
367 MeshVisualPtr MeshVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
368 {
369   MeshVisualPtr meshVisualPtr( new MeshVisual( factoryCache ) );
370   meshVisualPtr->SetProperties( properties );
371   return meshVisualPtr;
372 }
373
374 MeshVisual::MeshVisual( VisualFactoryCache& factoryCache )
375 : Visual::Base( factoryCache ),
376   mShadingMode( Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ),
377   mUseTexture( true ),
378   mUseMipmapping( true ),
379   mUseSoftNormals( true )
380 {
381 }
382
383 MeshVisual::~MeshVisual()
384 {
385 }
386
387 void MeshVisual::DoSetProperties( const Property::Map& propertyMap )
388 {
389   for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
390   {
391     KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
392     if( keyValue.first.type == Property::Key::INDEX )
393     {
394       DoSetProperty( keyValue.first.indexKey, keyValue.second );
395     }
396     else
397     {
398       if( keyValue.first == OBJECT_URL_NAME )
399       {
400         DoSetProperty( Toolkit::MeshVisual::Property::OBJECT_URL, keyValue.second );
401       }
402       else if( keyValue.first == MATERIAL_URL_NAME )
403       {
404         DoSetProperty( Toolkit::MeshVisual::Property::MATERIAL_URL, keyValue.second );
405       }
406       else if( keyValue.first == TEXTURES_PATH_NAME )
407       {
408         DoSetProperty( Toolkit::MeshVisual::Property::TEXTURES_PATH, keyValue.second );
409       }
410       else if( keyValue.first == SHADING_MODE_NAME )
411       {
412         DoSetProperty( Toolkit::MeshVisual::Property::SHADING_MODE, keyValue.second );
413       }
414       else if( keyValue.first == USE_MIPMAPPING_NAME )
415       {
416         DoSetProperty( Toolkit::MeshVisual::Property::USE_MIPMAPPING, keyValue.second );
417       }
418       else if( keyValue.first == USE_SOFT_NORMALS_NAME )
419       {
420         DoSetProperty( Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, keyValue.second );
421       }
422       else if( keyValue.first == LIGHT_POSITION_NAME )
423       {
424         DoSetProperty( Toolkit::MeshVisual::Property::LIGHT_POSITION, keyValue.second );
425       }
426     }
427   }
428
429   if( mMaterialUrl.empty() )
430   {
431     mUseTexture = false;
432   }
433
434   if( mLightPosition == Vector3::ZERO )
435   {
436     // Default behaviour is to place the light directly in front of the object,
437     // at a reasonable distance to light everything on screen.
438     Stage stage = Stage::GetCurrent();
439
440     mLightPosition = Vector3( stage.GetSize().width / 2, stage.GetSize().height / 2, stage.GetSize().width * 5 );
441   }
442 }
443
444 void MeshVisual::DoSetProperty( Property::Index index, const Property::Value& value )
445 {
446   switch( index )
447   {
448     case Toolkit::MeshVisual::Property::OBJECT_URL:
449     {
450       if( !value.Get( mObjectUrl ) )
451       {
452         DALI_LOG_ERROR("MeshVisual: property objectUrl is the wrong type, use STRING\n");
453       }
454       break;
455     }
456     case Toolkit::MeshVisual::Property::MATERIAL_URL:
457     {
458       if( ! value.Get( mMaterialUrl ) )
459       {
460         DALI_LOG_ERROR("MeshVisual: property materialUrl is the wrong type, use STRING\n");
461       }
462       break;
463     }
464     case Toolkit::MeshVisual::Property::TEXTURES_PATH:
465     {
466       if( ! value.Get( mTexturesPath ) )
467       {
468         mTexturesPath.clear();
469       }
470       break;
471     }
472     case Toolkit::MeshVisual::Property::SHADING_MODE:
473     {
474       Scripting::GetEnumerationProperty( value, SHADING_MODE_TABLE, SHADING_MODE_TABLE_COUNT, mShadingMode );
475       break;
476     }
477     case Toolkit::MeshVisual::Property::USE_MIPMAPPING:
478     {
479       if( !value.Get( mUseMipmapping ) )
480       {
481         DALI_LOG_ERROR("MeshVisual: property useMipmapping is the wrong type, use BOOLEAN\n");
482       }
483       break;
484     }
485     case Toolkit::MeshVisual::Property::USE_SOFT_NORMALS:
486     {
487       if( !value.Get( mUseSoftNormals ) )
488       {
489         DALI_LOG_ERROR("MeshVisual: property useSoftNormals is the wrong type, use BOOLEAN\n");
490       }
491       break;
492     }
493     case Toolkit::MeshVisual::Property::LIGHT_POSITION:
494     {
495       if( !value.Get( mLightPosition ) )
496       {
497         mLightPosition = Vector3::ZERO;
498         DALI_LOG_ERROR("MeshVisual: property lightPosition is the wrong type, use VECTOR3\n");
499       }
500       break;
501     }
502   }
503 }
504
505 void MeshVisual::OnSetTransform()
506 {
507   if( mImpl->mRenderer )
508   {
509     mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
510   }
511 }
512
513 void MeshVisual::DoSetOnStage( Actor& actor )
514 {
515   InitializeRenderer();
516
517   actor.AddRenderer( mImpl->mRenderer );
518 }
519
520 void MeshVisual::DoCreatePropertyMap( Property::Map& map ) const
521 {
522   map.Clear();
523   map.Insert( Toolkit::DevelVisual::Property::TYPE, Toolkit::Visual::MESH );
524   map.Insert( Toolkit::MeshVisual::Property::OBJECT_URL, mObjectUrl );
525   map.Insert( Toolkit::MeshVisual::Property::MATERIAL_URL, mMaterialUrl );
526   map.Insert( Toolkit::MeshVisual::Property::TEXTURES_PATH, mTexturesPath );
527   map.Insert( Toolkit::MeshVisual::Property::SHADING_MODE, mShadingMode );
528   map.Insert( Toolkit::MeshVisual::Property::USE_MIPMAPPING, mUseMipmapping );
529   map.Insert( Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, mUseSoftNormals );
530   map.Insert( Toolkit::MeshVisual::Property::LIGHT_POSITION, mLightPosition );
531 }
532
533 void MeshVisual::InitializeRenderer()
534 {
535   //Try to load the geometry from the file.
536   if( !LoadGeometry() )
537   {
538     SupplyEmptyGeometry();
539     return;
540   }
541
542   //If a texture is used by the obj file, load the supplied material file.
543   if( mObjLoader.IsTexturePresent() && !mMaterialUrl.empty() )
544   {
545     if( !LoadMaterial() )
546     {
547       SupplyEmptyGeometry();
548       return;
549     }
550   }
551
552   //Now that the required parts are loaded, create the geometry for the object.
553   if( !CreateGeometry() )
554   {
555     SupplyEmptyGeometry();
556     return;
557   }
558
559   CreateShader();
560
561   //Load the various texture files supplied by the material file.
562   if( !LoadTextures() )
563   {
564     SupplyEmptyGeometry();
565     return;
566   }
567
568   mImpl->mRenderer = Renderer::New( mGeometry, mShader );
569   mImpl->mRenderer.SetTextures( mTextureSet );
570   mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
571   mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON );
572
573   //Register transform properties
574   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
575 }
576
577 void MeshVisual::SupplyEmptyGeometry()
578 {
579   mGeometry = Geometry::New();
580   mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
581   mImpl->mRenderer = Renderer::New( mGeometry, mShader );
582
583   DALI_LOG_ERROR( "Initialisation error in mesh visual.\n" );
584 }
585
586 void MeshVisual::UpdateShaderUniforms()
587 {
588   Stage stage = Stage::GetCurrent();
589   float width = stage.GetSize().width;
590   float height = stage.GetSize().height;
591
592   Matrix scaleMatrix;
593   scaleMatrix.SetIdentityAndScale( Vector3( 1.0, -1.0, 1.0 ) );
594
595   mShader.RegisterProperty( STAGE_OFFSET_UNIFORM_NAME, Vector2( width, height ) / 2.0f );
596   mShader.RegisterProperty( LIGHT_POSITION_NAME, mLightPosition );
597   mShader.RegisterProperty( OBJECT_MATRIX_UNIFORM_NAME, scaleMatrix );
598 }
599
600 void MeshVisual::CreateShader()
601 {
602   if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
603   {
604     mShader = Shader::New( NORMAL_MAP_VERTEX_SHADER, NORMAL_MAP_FRAGMENT_SHADER );
605   }
606   else if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING )
607   {
608     mShader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER );
609   }
610   else //Textureless
611   {
612     mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
613   }
614
615   UpdateShaderUniforms();
616 }
617
618 bool MeshVisual::CreateGeometry()
619 {
620   //Determine if we need to use a simpler shader to handle the provided data
621   if( !mUseTexture || !mObjLoader.IsDiffuseMapPresent() )
622   {
623     mShadingMode = Toolkit::MeshVisual::ShadingMode::TEXTURELESS_WITH_DIFFUSE_LIGHTING;
624   }
625   else if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING && (!mObjLoader.IsNormalMapPresent() || !mObjLoader.IsSpecularMapPresent()) )
626   {
627     mShadingMode = Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING;
628   }
629
630   int objectProperties = 0;
631
632   if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING ||
633       mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
634   {
635     objectProperties |= ObjLoader::TEXTURE_COORDINATES;
636   }
637
638   if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
639   {
640     objectProperties |= ObjLoader::TANGENTS | ObjLoader::BINORMALS;
641   }
642
643   //Create geometry with attributes required by shader.
644   mGeometry = mObjLoader.CreateGeometry( objectProperties, mUseSoftNormals );
645
646   if( mGeometry )
647   {
648     return true;
649   }
650
651   DALI_LOG_ERROR( "Failed to load geometry in mesh visual.\n" );
652   return false;
653 }
654
655 bool MeshVisual::LoadGeometry()
656 {
657   std::streampos fileSize;
658   Dali::Vector<char> fileContent;
659
660   if( FileLoader::ReadFile( mObjectUrl, fileSize, fileContent, FileLoader::TEXT ) )
661   {
662     mObjLoader.ClearArrays();
663     mObjLoader.LoadObject( fileContent.Begin(), fileSize );
664
665     //Get size information from the obj loaded
666     mSceneCenter = mObjLoader.GetCenter();
667     mSceneSize = mObjLoader.GetSize();
668
669     return true;
670   }
671
672   DALI_LOG_ERROR( "Failed to find object to load in mesh visual.\n" );
673   return false;
674 }
675
676 bool MeshVisual::LoadMaterial()
677 {
678   std::streampos fileSize;
679   Dali::Vector<char> fileContent;
680
681   if( FileLoader::ReadFile( mMaterialUrl, fileSize, fileContent, FileLoader::TEXT ) )
682   {
683     //Load data into obj (usable) form
684     mObjLoader.LoadMaterial( fileContent.Begin(), fileSize, mDiffuseTextureUrl, mNormalTextureUrl, mGlossTextureUrl );
685     return true;
686   }
687
688   DALI_LOG_ERROR( "Failed to find texture set to load in mesh visual.\n" );
689   mUseTexture = false;
690   return false;
691 }
692
693 bool MeshVisual::LoadTextures()
694 {
695   mTextureSet = TextureSet::New();
696
697   if( mShadingMode != Toolkit::MeshVisual::ShadingMode::TEXTURELESS_WITH_DIFFUSE_LIGHTING )
698   {
699     Sampler sampler = Sampler::New();
700     if( mUseMipmapping )
701     {
702       sampler.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR );
703     }
704
705     if( !mDiffuseTextureUrl.empty() )
706     {
707       std::string imageUrl = mTexturesPath + mDiffuseTextureUrl;
708
709       //Load textures
710       Texture diffuseTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
711       if( diffuseTexture )
712       {
713         mTextureSet.SetTexture( DIFFUSE_INDEX, diffuseTexture );
714         mTextureSet.SetSampler( DIFFUSE_INDEX, sampler );
715       }
716       else
717       {
718         DALI_LOG_ERROR( "Failed to load diffuse map texture in mesh visual.\n");
719         return false;
720       }
721     }
722
723     if( !mNormalTextureUrl.empty() && ( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) )
724     {
725       std::string imageUrl = mTexturesPath + mNormalTextureUrl;
726
727       //Load textures
728       Texture normalTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
729       if( normalTexture )
730       {
731         mTextureSet.SetTexture( NORMAL_INDEX, normalTexture );
732         mTextureSet.SetSampler( NORMAL_INDEX, sampler );
733       }
734       else
735       {
736         DALI_LOG_ERROR( "Failed to load normal map texture in mesh visual.\n");
737         return false;
738       }
739     }
740
741     if( !mGlossTextureUrl.empty() && ( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) )
742     {
743       std::string imageUrl = mTexturesPath + mGlossTextureUrl;
744
745       //Load textures
746       Texture glossTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
747       if( glossTexture )
748       {
749         mTextureSet.SetTexture( GLOSS_INDEX, glossTexture );
750         mTextureSet.SetSampler( GLOSS_INDEX, sampler );
751       }
752       else
753       {
754         DALI_LOG_ERROR( "Failed to load gloss map texture in mesh visual.\n");
755         return false;
756       }
757     }
758   }
759   return true;
760 }
761
762 } // namespace Internal
763
764 } // namespace Toolkit
765
766 } // namespace Dali