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