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