2 * Copyright (c) 2014 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 <dali/internal/render/shaders/program.h>
25 #include <dali/public-api/common/dali-common.h>
26 #include <dali/public-api/common/dali-vector.h>
27 #include <dali/public-api/common/constants.h>
28 #include <dali/integration-api/debug.h>
29 #include <dali/integration-api/shader-data.h>
30 #include <dali/integration-api/gl-defines.h>
31 #include <dali/internal/render/common/performance-monitor.h>
32 #include <dali/internal/render/shaders/program-cache.h>
33 #include <dali/internal/render/gl-resources/gl-call-debug.h>
37 void LogWithLineNumbers( const char * source )
39 unsigned int lineNumber = 0u;
40 const char *prev = source;
41 const char *ptr = prev;
49 // seek the next end of line or end of text
50 while( *ptr!='\n' && *ptr != '\0' )
55 std::string line( prev, ptr-prev );
56 Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugError, "%4d %s\n", lineNumber, line.c_str());
79 const char* gStdAttribs[ Program::ATTRIB_TYPE_LAST ] =
81 "aPosition", // ATTRIB_POSITION
82 "aNormal", // ATTRIB_NORMAL
83 "aTexCoord", // ATTRIB_TEXCOORD
84 "aColor", // ATTRIB_COLOR
85 "aBoneWeights", // ATTRIB_BONE_WEIGHTS
86 "aBoneIndices" // ATTRIB_BONE_INDICES
89 const char* gStdUniforms[ Program::UNIFORM_TYPE_LAST ] =
91 "uMvpMatrix", // UNIFORM_MVP_MATRIX
92 "uModelView", // UNIFORM_MODELVIEW_MATRIX
93 "uProjection", // UNIFORM_PROJECTION_MATRIX
94 "uModelMatrix", // UNIFORM_MODEL_MATRIX,
95 "uViewMatrix", // UNIFORM_VIEW_MATRIX,
96 "uNormalMatrix", // UNIFORM_NORMAL_MATRIX
97 "uColor", // UNIFORM_COLOR
98 "uCustomTextureCoords", // UNIFORM_CUSTOM_TEXTURE_COORDS
99 "sTexture", // UNIFORM_SAMPLER
100 "sTextureRect", // UNIFORM_SAMPLER_RECT
101 "sEffect", // UNIFORM_EFFECT_SAMPLER
102 "sEffectRect", // UNIFORM_EFFECT_SAMPLER_RECT
103 "uTimeDelta", // UNIFORM_TIME_DELTA
104 "sOpacityTexture", // UNIFORM_SAMPLER_OPACITY
105 "sNormalMapTexture" // UNIFORM_SAMPLER_NORMAL_MAP
108 } // <unnamed> namespace
112 Program* Program::New( ProgramCache& cache, Integration::ShaderDataPtr shaderData, bool modifiesGeometry )
114 size_t shaderHash = shaderData->GetHashValue();
115 Program* program = cache.GetProgram( shaderHash );
117 if( NULL == program )
119 // program not found so create it
120 program = new Program( cache, shaderData, modifiesGeometry );
122 // we want to lazy load programs so dont do a Load yet, it gets done in Use()
124 cache.AddProgram( shaderHash, program );
139 if ( this != mCache.GetCurrentProgram() )
141 LOG_GL( "UseProgram(%d)\n", mProgramId );
142 CHECK_GL( mGlAbstraction, mGlAbstraction.UseProgram(mProgramId) );
144 mCache.SetCurrentProgram( this );
149 bool Program::IsUsed()
151 return ( this == mCache.GetCurrentProgram() );
154 GLint Program::GetAttribLocation( AttribType type )
156 DALI_ASSERT_DEBUG(type != ATTRIB_UNKNOWN);
158 if( mAttribLocations[ type ] == ATTRIB_UNKNOWN )
160 GLint loc = CHECK_GL( mGlAbstraction, mGlAbstraction.GetAttribLocation( mProgramId, gStdAttribs[type] ) );
161 mAttribLocations[ type ] = loc;
162 LOG_GL( "GetAttribLocation(program=%d,%s) = %d\n", mProgramId, gStdAttribs[type], mAttribLocations[type] );
165 return mAttribLocations[type];
168 unsigned int Program::RegisterUniform( const std::string& name )
170 unsigned int index = 0;
171 // find the value from cache
172 for( ;index < mUniformLocations.size(); ++index )
174 if( mUniformLocations[ index ].first == name )
176 // name found so return index
180 // if we get here, index is one past end so push back the new name
181 mUniformLocations.push_back( std::make_pair( name, UNIFORM_NOT_QUERIED ) );
185 GLint Program::GetUniformLocation( unsigned int uniformIndex )
187 // debug check that index is within name cache
188 DALI_ASSERT_DEBUG( mUniformLocations.size() > uniformIndex );
190 // check if we have already queried the location of the uniform
191 GLint location = mUniformLocations[ uniformIndex ].second;
193 if( location == UNIFORM_NOT_QUERIED )
195 location = CHECK_GL( mGlAbstraction, mGlAbstraction.GetUniformLocation( mProgramId, mUniformLocations[ uniformIndex ].first.c_str() ) );
197 mUniformLocations[ uniformIndex ].second = location;
198 LOG_GL( "GetUniformLocation(program=%d,%s) = %d\n", mProgramId, mUniformLocations[ uniformIndex ].first.c_str(), mUniformLocations[ uniformIndex ].second );
204 void Program::SetUniform1i( GLint location, GLint value0 )
206 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
208 if( UNIFORM_UNKNOWN == location )
210 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
211 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
212 // specified uniform variable will not be changed.following opengl silently do nothing
216 // check if uniform location fits the cache
217 if( location >= MAX_UNIFORM_CACHE_SIZE )
219 // not cached, make the gl call
220 LOG_GL( "Uniform1i(%d,%d)\n", location, value0 );
221 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1i( location, value0 ) );
225 // check if the value is different from what's already been set
226 if( value0 != mUniformCacheInt[ location ] )
229 LOG_GL( "Uniform1i(%d,%d)\n", location, value0 );
230 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1i( location, value0 ) );
232 mUniformCacheInt[ location ] = value0;
237 void Program::SetUniform4i( GLint location, GLint value0, GLint value1, GLint value2, GLint value3 )
239 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
241 if( UNIFORM_UNKNOWN == location )
243 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
244 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
245 // specified uniform variable will not be changed.following opengl silently do nothing
249 // Not caching these as based on current analysis this is not called that often by our shaders
250 LOG_GL( "Uniform4i(%d,%d,%d,%d,%d)\n", location, value0, value1, value2, value3 );
251 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4i( location, value0, value1, value2, value3 ) );
254 void Program::SetUniform1f( GLint location, GLfloat value0 )
256 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
258 if( UNIFORM_UNKNOWN == location )
260 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
261 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
262 // specified uniform variable will not be changed.following opengl silently do nothing
266 // check if uniform location fits the cache
267 if( location >= MAX_UNIFORM_CACHE_SIZE )
269 // not cached, make the gl call
270 LOG_GL( "Uniform1f(%d,%f)\n", location, value0 );
271 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1f( location, value0 ) );
275 // check if the same value has already been set, reset if it is different
276 if( ( fabsf(value0 - mUniformCacheFloat[ location ]) >= Math::MACHINE_EPSILON_1 ) )
279 LOG_GL( "Uniform1f(%d,%f)\n", location, value0 );
280 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1f( location, value0 ) );
283 mUniformCacheFloat[ location ] = value0;
288 void Program::SetUniform2f( GLint location, GLfloat value0, GLfloat value1 )
290 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
292 if( UNIFORM_UNKNOWN == location )
294 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
295 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
296 // specified uniform variable will not be changed.following opengl silently do nothing
300 // Not caching these as based on current analysis this is not called that often by our shaders
301 LOG_GL( "Uniform2f(%d,%f,%f)\n", location, value0, value1 );
302 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform2f( location, value0, value1 ) );
305 void Program::SetUniform3f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2 )
307 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
309 if( UNIFORM_UNKNOWN == location )
311 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
312 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
313 // specified uniform variable will not be changed.following opengl silently do nothing
317 // Not caching these as based on current analysis this is not called that often by our shaders
318 LOG_GL( "Uniform3f(%d,%f,%f,%f)\n", location, value0, value1, value2 );
319 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform3f( location, value0, value1, value2 ) );
322 void Program::SetUniform4f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2, GLfloat value3 )
324 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
326 if( UNIFORM_UNKNOWN == location )
328 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
329 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
330 // specified uniform variable will not be changed.following opengl silently do nothing
334 // check if uniform location fits the cache
335 if( location >= MAX_UNIFORM_CACHE_SIZE )
337 // not cached, make the gl call
338 LOG_GL( "Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3 );
339 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
343 // check if the same value has already been set, reset if any component is different
344 // checking index 3 first because we're often animating alpha (rgba)
345 if( ( fabsf(value3 - mUniformCacheFloat4[ location ][ 3 ]) >= Math::MACHINE_EPSILON_1 )||
346 ( fabsf(value0 - mUniformCacheFloat4[ location ][ 0 ]) >= Math::MACHINE_EPSILON_1 )||
347 ( fabsf(value1 - mUniformCacheFloat4[ location ][ 1 ]) >= Math::MACHINE_EPSILON_1 )||
348 ( fabsf(value2 - mUniformCacheFloat4[ location ][ 2 ]) >= Math::MACHINE_EPSILON_1 ) )
351 LOG_GL( "Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3 );
352 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
354 mUniformCacheFloat4[ location ][ 0 ] = value0;
355 mUniformCacheFloat4[ location ][ 1 ] = value1;
356 mUniformCacheFloat4[ location ][ 2 ] = value2;
357 mUniformCacheFloat4[ location ][ 3 ] = value3;
362 void Program::SetUniformMatrix4fv( GLint location, GLsizei count, const GLfloat* value )
364 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
366 if( UNIFORM_UNKNOWN == location )
368 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
369 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
370 // specified uniform variable will not be changed.following opengl silently do nothing
374 // Not caching these calls. Based on current analysis this is called very often
375 // but with different values (we're using this for MVP matrices)
376 // NOTE! we never want driver or GPU to transpose
377 LOG_GL( "UniformMatrix4fv(%d,%d,GL_FALSE,%x)\n", location, count, value );
378 CHECK_GL( mGlAbstraction, mGlAbstraction.UniformMatrix4fv( location, count, GL_FALSE, value ) );
381 void Program::SetUniformMatrix3fv( GLint location, GLsizei count, const GLfloat* value )
383 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
385 if( UNIFORM_UNKNOWN == location )
387 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
388 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
389 // specified uniform variable will not be changed.following opengl silently do nothing
394 // Not caching these calls. Based on current analysis this is called very often
395 // but with different values (we're using this for MVP matrices)
396 // NOTE! we never want driver or GPU to transpose
397 LOG_GL( "UniformMatrix3fv(%d,%d,GL_FALSE,%x)\n", location, count, value );
398 CHECK_GL( mGlAbstraction, mGlAbstraction.UniformMatrix3fv( location, count, GL_FALSE, value ) );
401 void Program::GlContextCreated()
405 void Program::GlContextDestroyed()
409 mFragmentShaderId = 0;
412 ResetAttribsUniformCache();
415 bool Program::ModifiesGeometry()
417 return mModifiesGeometry;
420 Program::Program( ProgramCache& cache, Integration::ShaderDataPtr shaderData, bool modifiesGeometry )
422 mGlAbstraction( mCache.GetGlAbstraction() ),
423 mProjectionMatrix( NULL ),
426 mVertexShaderId( 0 ),
427 mFragmentShaderId( 0 ),
429 mProgramData(shaderData),
430 mModifiesGeometry( modifiesGeometry )
432 // reserve space for standard uniforms
433 mUniformLocations.reserve( UNIFORM_TYPE_LAST );
434 // reset built in uniform names in cache
435 for( int i = 0; i < UNIFORM_TYPE_LAST; ++i )
437 RegisterUniform( gStdUniforms[ i ] );
440 ResetAttribsUniformCache();
450 DALI_ASSERT_ALWAYS( NULL != mProgramData.Get() && "Program data is not initialized" );
452 LOG_GL( "CreateProgram()\n" );
453 mProgramId = CHECK_GL( mGlAbstraction, mGlAbstraction.CreateProgram() );
455 GLint linked = GL_FALSE;
457 const bool binariesSupported = mCache.IsBinarySupported();
459 // if shader binaries are supported and ShaderData contains compiled bytecode?
460 if( binariesSupported && mProgramData->HasBinary() )
462 DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - Using Compiled Shader, Size = %d\n", mProgramData->GetBufferSize());
464 CHECK_GL( mGlAbstraction, mGlAbstraction.ProgramBinary(mProgramId, mCache.ProgramBinaryFormat(), mProgramData->GetBufferData(), mProgramData->GetBufferSize()) );
466 CHECK_GL( mGlAbstraction, mGlAbstraction.ValidateProgram(mProgramId) );
469 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_VALIDATE_STATUS, &success ) );
471 DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "ValidateProgram Status = %d\n", success);
473 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
475 if( GL_FALSE == linked )
477 DALI_LOG_ERROR("Failed to load program binary \n");
480 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_INFO_LOG_LENGTH, &nLength) );
483 Dali::Vector< char > szLog;
484 szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
485 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog.Begin() ) );
486 DALI_LOG_ERROR( "Program Link Error: %s\n", szLog.Begin() );
495 // Fall back to compiling and linking the vertex and fragment sources
496 if( GL_FALSE == linked )
498 DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - Runtime compilation\n");
499 if( CompileShader( GL_VERTEX_SHADER, mVertexShaderId, mProgramData->GetVertexShader() ) )
501 if( CompileShader( GL_FRAGMENT_SHADER, mFragmentShaderId, mProgramData->GetFragmentShader() ) )
505 if( binariesSupported && mLinked )
507 GLint binaryLength = 0;
510 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv(mProgramId, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength) );
511 DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - GL_PROGRAM_BINARY_LENGTH_OES: %d\n", binaryLength);
512 if( binaryLength > 0 )
514 // Allocate space for the bytecode in ShaderData
515 mProgramData->AllocateBuffer(binaryLength);
516 // Copy the bytecode to ShaderData
517 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramBinary(mProgramId, binaryLength, NULL, &binaryFormat, mProgramData->GetBufferData()) );
518 mCache.StoreBinary( mProgramData );
529 void Program::Unload()
533 if( this == mCache.GetCurrentProgram() )
535 CHECK_GL( mGlAbstraction, mGlAbstraction.UseProgram(0) );
537 mCache.SetCurrentProgram( NULL );
542 LOG_GL( "DeleteProgram(%d)\n", mProgramId );
543 CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteProgram( mProgramId ) );
551 bool Program::CompileShader( GLenum shaderType, GLuint& shaderId, const char* src )
555 LOG_GL( "CreateShader(%d)\n", shaderType );
556 shaderId = CHECK_GL( mGlAbstraction, mGlAbstraction.CreateShader( shaderType ) );
557 LOG_GL( "AttachShader(%d,%d)\n", mProgramId, shaderId );
558 CHECK_GL( mGlAbstraction, mGlAbstraction.AttachShader( mProgramId, shaderId ) );
561 LOG_GL( "ShaderSource(%d)\n", shaderId );
562 CHECK_GL( mGlAbstraction, mGlAbstraction.ShaderSource(shaderId, 1, &src, NULL ) );
564 LOG_GL( "CompileShader(%d)\n", shaderId );
565 CHECK_GL( mGlAbstraction, mGlAbstraction.CompileShader( shaderId ) );
568 LOG_GL( "GetShaderiv(%d)\n", shaderId );
569 CHECK_GL( mGlAbstraction, mGlAbstraction.GetShaderiv( shaderId, GL_COMPILE_STATUS, &compiled ) );
571 if (compiled == GL_FALSE)
573 DALI_LOG_ERROR("Failed to compile shader\n");
574 LogWithLineNumbers(src);
577 mGlAbstraction.GetShaderiv( shaderId, GL_INFO_LOG_LENGTH, &nLength);
580 Dali::Vector< char > szLog;
581 szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
582 mGlAbstraction.GetShaderInfoLog( shaderId, nLength, &nLength, szLog.Begin() );
583 DALI_LOG_ERROR( "Shader Compiler Error: %s\n", szLog.Begin() );
586 DALI_ASSERT_ALWAYS( 0 && "Shader compilation failure" );
589 return compiled != 0;
594 LOG_GL( "LinkProgram(%d)\n", mProgramId );
595 CHECK_GL( mGlAbstraction, mGlAbstraction.LinkProgram( mProgramId ) );
598 LOG_GL( "GetProgramiv(%d)\n", mProgramId );
599 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
601 if (linked == GL_FALSE)
603 DALI_LOG_ERROR("Shader failed to link \n");
606 mGlAbstraction.GetProgramiv( mProgramId, GL_INFO_LOG_LENGTH, &nLength);
609 Dali::Vector< char > szLog;
610 szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
611 mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog.Begin() );
612 DALI_LOG_ERROR( "Shader Link Error: %s\n", szLog.Begin() );
615 DALI_ASSERT_ALWAYS( 0 && "Shader linking failure" );
618 mLinked = linked != GL_FALSE;
621 void Program::FreeShaders()
625 LOG_GL( "DeleteShader(%d)\n", mVertexShaderId );
626 CHECK_GL( mGlAbstraction, mGlAbstraction.DetachShader( mProgramId, mVertexShaderId ) );
627 CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteShader( mVertexShaderId ) );
631 if (mFragmentShaderId)
633 LOG_GL( "DeleteShader(%d)\n", mFragmentShaderId );
634 CHECK_GL( mGlAbstraction, mGlAbstraction.DetachShader( mProgramId, mFragmentShaderId ) );
635 CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteShader( mFragmentShaderId ) );
636 mFragmentShaderId = 0;
640 void Program::ResetAttribsUniformCache()
642 // reset attribute locations
643 for( unsigned i = 0; i < ATTRIB_TYPE_LAST; ++i )
645 mAttribLocations[ i ] = ATTRIB_UNKNOWN;
648 // reset all gl uniform locations
649 for( unsigned int i = 0; i < mUniformLocations.size(); ++i )
651 // reset gl program locations and names
652 mUniformLocations[ i ].second = UNIFORM_NOT_QUERIED;
655 // reset uniform cache
656 for( int i = 0; i < MAX_UNIFORM_CACHE_SIZE; ++i )
658 // GL initializes uniforms to 0
659 mUniformCacheInt[ i ] = 0;
660 mUniformCacheFloat[ i ] = 0.0f;
661 mUniformCacheFloat4[ i ][ 0 ] = 0.0f;
662 mUniformCacheFloat4[ i ][ 1 ] = 0.0f;
663 mUniformCacheFloat4[ i ][ 2 ] = 0.0f;
664 mUniformCacheFloat4[ i ][ 3 ] = 0.0f;
668 } // namespace Internal