2 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "mesh-renderer.h"
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>
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>
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
46 Texture LoadTexture( const char* imageUrl, bool generateMipmaps )
49 Dali::BitmapLoader loader = Dali::BitmapLoader::New( imageUrl );
51 PixelData pixelData = loader.GetPixelData();
54 texture = Texture::New( TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight() );
55 texture.Upload( pixelData );
59 texture.GenerateMipmaps();
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.
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
91 //If a shader requires certain textures, they must be listed in order,
92 //as detailed in the TextureIndex enum documentation.
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
108 vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
109 vertexPosition = uObjectMatrix * vertexPosition;\n
110 vertexPosition = uMvpMatrix * vertexPosition;\n
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
119 float lightDiffuse = max( dot( vecToLight, normal ), 0.0 );\n
120 vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
122 gl_Position = vertexPosition;\n
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
134 gl_FragColor = vec4( vIllumination.rgb * uColor.rgb, uColor.a );\n
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
155 vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
156 vertexPosition = uObjectMatrix * vertexPosition;\n
157 vertexPosition = uMvpMatrix * vertexPosition;\n
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
165 vec3 vecToLight = normalize( lightPos.xyz - vertPos.xyz );\n
166 vec3 viewDir = normalize( -vertPos.xyz );
168 vec3 halfVector = normalize( viewDir + vecToLight );
170 float lightDiffuse = dot( vecToLight, normal );\n
171 lightDiffuse = max( 0.0,lightDiffuse );\n
172 vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
174 vec3 reflectDir = reflect( -vecToLight, normal );
175 vSpecular = pow( max( dot( reflectDir, viewDir ), 0.0 ), 4.0 );
177 vTexCoord = aTexCoord;\n
178 gl_Position = vertexPosition;\n
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
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
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
218 vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
219 vertexPosition = uObjectMatrix * vertexPosition;\n
220 vertexPosition = uMvpMatrix * vertexPosition;\n
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
226 vec3 tangent = normalize( uNormalMatrix * aTangent );
227 vec3 binormal = normalize( uNormalMatrix * aBiNormal );
228 vec3 normal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aNormal );
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 );
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 );
241 vTexCoord = aTexCoord;\n
242 gl_Position = vertexPosition;\n
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
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
263 float lightDiffuse = max( 0.0, dot( normal, normalize( vLightDirection ) ) );\n
264 lightDiffuse = lightDiffuse * 0.5 + 0.5;\n
266 float shininess = pow ( max ( dot ( normalize( vHalfVector ), normal ), 0.0 ), 16.0 ) ;
268 gl_FragColor = vec4( texture.rgb * uColor.rgb * lightDiffuse + shininess * glossMap.rgb, texture.a * uColor.a );\n
274 MeshRenderer::MeshRenderer( RendererFactoryCache& factoryCache )
275 : ControlRenderer( factoryCache ),
276 mShaderType( ALL_TEXTURES ),
278 mUseMipmapping( true )
282 MeshRenderer::~MeshRenderer()
286 void MeshRenderer::DoInitialize( Actor& actor, const Property::Map& propertyMap )
288 Property::Value* objectUrl = propertyMap.Find( OBJECT_URL );
289 if( !objectUrl || !objectUrl->Get( mObjectUrl ) )
291 DALI_LOG_ERROR( "Fail to provide object URL to the MeshRenderer object.\n" );
294 Property::Value* materialUrl = propertyMap.Find( MATERIAL_URL );
296 if( !materialUrl || !materialUrl->Get( mMaterialUrl ) || mMaterialUrl.empty() )
301 Property::Value* imagesUrl = propertyMap.Find( TEXTURES_PATH );
302 if( !imagesUrl || !imagesUrl->Get( mTexturesPath ) )
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();
309 Property::Value* useMipmapping = propertyMap.Find( USE_MIPMAPPING );
312 useMipmapping->Get( mUseMipmapping );
315 Property::Value* shaderType = propertyMap.Find( SHADER_TYPE );
316 if( shaderType && shaderType->Get( mShaderTypeString ) )
318 if( mShaderTypeString == "textureless" )
320 mShaderType = TEXTURELESS;
322 else if( mShaderTypeString == "diffuseTexture" )
324 mShaderType = DIFFUSE_TEXTURE;
326 else if( mShaderTypeString == "allTextures" )
328 mShaderType = ALL_TEXTURES;
332 DALI_LOG_ERROR( "Unknown shader type provided to the MeshRenderer object.\n");
337 void MeshRenderer::SetSize( const Vector2& size )
339 ControlRenderer::SetSize( size );
341 // ToDo: renderer responds to the size change
344 void MeshRenderer::SetClipRect( const Rect<int>& clipRect )
346 ControlRenderer::SetClipRect( clipRect );
348 //ToDo: renderer responds to the clipRect change
351 void MeshRenderer::SetOffset( const Vector2& offset )
353 //ToDo: renderer applies the offset
356 void MeshRenderer::DoSetOnStage( Actor& actor )
358 InitializeRenderer();
361 void MeshRenderer::DoCreatePropertyMap( Property::Map& map ) const
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 );
371 void MeshRenderer::InitializeRenderer()
373 //Try to load the geometry from the file.
374 if( !LoadGeometry() )
376 SupplyEmptyGeometry();
380 //If a texture is used by the obj file, load the supplied material file.
381 if( mObjLoader.IsTexturePresent() && !mMaterialUrl.empty() )
383 if( !LoadMaterial() )
385 SupplyEmptyGeometry();
390 //Now that the required parts are loaded, create the geometry for the object.
391 if( !CreateGeometry() )
393 SupplyEmptyGeometry();
399 //Load the various texture files supplied by the material file.
400 if( !LoadTextures() )
402 SupplyEmptyGeometry();
406 mImpl->mRenderer = Renderer::New( mGeometry, mShader );
407 mImpl->mRenderer.SetTextures( mTextureSet );
408 mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
411 void MeshRenderer::SupplyEmptyGeometry()
413 mGeometry = Geometry::New();
414 mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
415 mImpl->mRenderer = Renderer::New( mGeometry, mShader );
417 DALI_LOG_ERROR( "Initialisation error in mesh renderer.\n" );
420 void MeshRenderer::UpdateShaderUniforms()
422 Stage stage = Stage::GetCurrent();
424 Vector3 lightPosition( 0, 0, stage.GetSize().width );
425 mShader.RegisterProperty( LIGHT_POSITION, lightPosition );
428 scaleMatrix.SetIdentityAndScale( Vector3( 1.0, -1.0, 1.0 ) );
429 mShader.RegisterProperty( OBJECT_MATRIX, scaleMatrix );
432 void MeshRenderer::CreateShader()
434 if( mShaderType == ALL_TEXTURES )
436 mShader = Shader::New( NORMAL_MAP_VERTEX_SHADER, NORMAL_MAP_FRAGMENT_SHADER );
438 else if( mShaderType == DIFFUSE_TEXTURE )
440 mShader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER );
444 mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
447 UpdateShaderUniforms();
450 bool MeshRenderer::CreateGeometry()
452 //Determine if we need to use a simpler shader to handle the provided data
453 if( !mUseTexture || !mObjLoader.IsDiffuseMapPresent() )
455 mShaderType = TEXTURELESS;
457 else if( mShaderType == ALL_TEXTURES && (!mObjLoader.IsNormalMapPresent() || !mObjLoader.IsSpecularMapPresent()) )
459 mShaderType = DIFFUSE_TEXTURE;
462 int objectProperties = 0;
464 if( mShaderType == DIFFUSE_TEXTURE ||
465 mShaderType == ALL_TEXTURES )
467 objectProperties |= ObjLoader::TEXTURE_COORDINATES;
470 if( mShaderType == ALL_TEXTURES )
472 objectProperties |= ObjLoader::TANGENTS | ObjLoader::BINORMALS;
475 //Create geometry with attributes required by shader.
476 mGeometry = mObjLoader.CreateGeometry( objectProperties );
483 DALI_LOG_ERROR( "Failed to load geometry in mesh renderer.\n" );
487 bool MeshRenderer::LoadGeometry()
489 std::streampos fileSize;
490 Dali::Vector<char> fileContent;
492 if( FileLoader::ReadFile( mObjectUrl, fileSize, fileContent, FileLoader::TEXT ) )
494 mObjLoader.ClearArrays();
495 mObjLoader.LoadObject( fileContent.Begin(), fileSize );
497 //Get size information from the obj loaded
498 mSceneCenter = mObjLoader.GetCenter();
499 mSceneSize = mObjLoader.GetSize();
504 DALI_LOG_ERROR( "Failed to find object to load in mesh renderer.\n" );
508 bool MeshRenderer::LoadMaterial()
510 std::streampos fileSize;
511 Dali::Vector<char> fileContent;
513 if( FileLoader::ReadFile( mMaterialUrl, fileSize, fileContent, FileLoader::TEXT ) )
515 //Load data into obj (usable) form
516 mObjLoader.LoadMaterial( fileContent.Begin(), fileSize, mDiffuseTextureUrl, mNormalTextureUrl, mGlossTextureUrl );
520 DALI_LOG_ERROR( "Failed to find texture set to load in mesh renderer.\n" );
525 bool MeshRenderer::LoadTextures()
527 mTextureSet = TextureSet::New();
529 if( mShaderType != TEXTURELESS )
531 Sampler sampler = Sampler::New();
534 sampler.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR );
537 if( !mDiffuseTextureUrl.empty() )
539 std::string imageUrl = mTexturesPath + mDiffuseTextureUrl;
542 Texture diffuseTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
545 mTextureSet.SetTexture( DIFFUSE_INDEX, diffuseTexture );
546 mTextureSet.SetSampler( DIFFUSE_INDEX, sampler );
550 DALI_LOG_ERROR( "Failed to load diffuse map texture in mesh renderer.\n");
555 if( !mNormalTextureUrl.empty() && ( mShaderType == ALL_TEXTURES ) )
557 std::string imageUrl = mTexturesPath + mNormalTextureUrl;
560 Texture normalTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
563 mTextureSet.SetTexture( NORMAL_INDEX, normalTexture );
564 mTextureSet.SetSampler( NORMAL_INDEX, sampler );
568 DALI_LOG_ERROR( "Failed to load normal map texture in mesh renderer.\n");
573 if( !mGlossTextureUrl.empty() && ( mShaderType == ALL_TEXTURES ) )
575 std::string imageUrl = mTexturesPath + mGlossTextureUrl;
578 Texture glossTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
581 mTextureSet.SetTexture( GLOSS_INDEX, glossTexture );
582 mTextureSet.SetSampler( GLOSS_INDEX, sampler );
586 DALI_LOG_ERROR( "Failed to load gloss map texture in mesh renderer.\n");
594 } // namespace Internal
596 } // namespace Toolkit