[Tizen] Add codes for Dali Windows Backend
[platform/core/uifw/dali-core.git] / dali / internal / render / shaders / program.cpp
old mode 100644 (file)
new mode 100755 (executable)
index b1a76cb..530b629
@@ -1,32 +1,37 @@
-//
-// Copyright (c) 2014 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Flora License, Version 1.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://floralicense.org/license/
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an AS IS BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
 
 // CLASS HEADER
 #include <dali/internal/render/shaders/program.h>
 
 // EXTERNAL INCLUDES
-#include <dali/public-api/common/vector-wrapper.h>
 #include <iomanip>
+#include <cstring>
 
 // INTERNAL INCLUDES
 #include <dali/public-api/common/dali-common.h>
+#include <dali/public-api/common/dali-vector.h>
 #include <dali/public-api/common/constants.h>
-#include <dali/internal/render/common/performance-monitor.h>
 #include <dali/integration-api/debug.h>
-#include <dali/integration-api/shader-data.h>
+#include <dali/internal/common/shader-data.h>
+#include <dali/integration-api/gl-defines.h>
+#include <dali/internal/render/common/performance-monitor.h>
+#include <dali/internal/render/shaders/program-cache.h>
+#include <dali/internal/render/gl-resources/gl-call-debug.h>
 
 namespace
 {
@@ -75,11 +80,7 @@ namespace
 const char* gStdAttribs[ Program::ATTRIB_TYPE_LAST ] =
 {
   "aPosition",    // ATTRIB_POSITION
-  "aNormal",      // ATTRIB_NORMAL
   "aTexCoord",    // ATTRIB_TEXCOORD
-  "aColor",       // ATTRIB_COLOR
-  "aBoneWeights", // ATTRIB_BONE_WEIGHTS
-  "aBoneIndices"  // ATTRIB_BONE_INDICES
 };
 
 const char* gStdUniforms[ Program::UNIFORM_TYPE_LAST ] =
@@ -91,48 +92,27 @@ const char* gStdUniforms[ Program::UNIFORM_TYPE_LAST ] =
   "uViewMatrix",          // UNIFORM_VIEW_MATRIX,
   "uNormalMatrix",        // UNIFORM_NORMAL_MATRIX
   "uColor",               // UNIFORM_COLOR
-  "uCustomTextureCoords", // UNIFORM_CUSTOM_TEXTURE_COORDS
   "sTexture",             // UNIFORM_SAMPLER
   "sTextureRect",         // UNIFORM_SAMPLER_RECT
   "sEffect",              // UNIFORM_EFFECT_SAMPLER
-  "sEffectRect",          // UNIFORM_EFFECT_SAMPLER_RECT
-  "uTimeDelta",           // UNIFORM_TIME_DELTA
-  "sOpacityTexture",      // UNIFORM_SAMPLER_OPACITY
-  "sNormalMapTexture",    // UNIFORM_SAMPLER_NORMAL_MAP
-  "uTextColor",           // UNIFORM_TEXT_COLOR
-  "uSmoothing",           // UNIFORM_SMOOTHING
-  "uOutline",             // UNIFORM_OUTLINE
-  "uOutlineColor",        // UNIFORM_OUTLINE_COLOR
-  "uGlow",                // UNIFORM_GLOW
-  "uGlowColor",           // UNIFORM_GLOW_COLOR
-  "uShadow",              // UNIFORM_SHADOW
-  "uShadowColor",         // UNIFORM_SHADOW_COLOR
-  "uShadowSmoothing",     // UNIFORM_SHADOW_SMOOTHING
-  "uGradientColor",       // UNIFORM_GRADIENT_COLOR
-  "uGradientLine",        // UNIFORM_GRADIENT_LINE
-  "uInvTextSize"          // UNIFORM_INVERSE_TEXT_SIZE
+  "uSize"                 // UNIFORM_SIZE
 };
 
 }  // <unnamed> namespace
 
 // IMPLEMENTATION
 
-std::set< std::string > Program::mExternalUniformNames;
-
-Program* Program::New( const Integration::ResourceId& resourceId, Integration::ShaderData* shaderData, Context& context )
+Program* Program::New( ProgramCache& cache, Internal::ShaderDataPtr shaderData, bool modifiesGeometry )
 {
   size_t shaderHash = shaderData->GetHashValue();
-  Program* program = context.GetCachedProgram( shaderHash );
+  Program* program = cache.GetProgram( shaderHash );
 
   if( NULL == program )
   {
     // program not found so create it
-    program = new Program( shaderData, context );
-
+    program = new Program( cache, shaderData, modifiesGeometry );
     program->Load();
-
-    // tell context to cache it
-    context.CacheProgram( shaderHash, program );
+    cache.AddProgram( shaderHash, program );
   }
 
   return program;
@@ -140,105 +120,220 @@ Program* Program::New( const Integration::ResourceId& resourceId, Integration::S
 
 void Program::Use()
 {
-  if ( !mLinked &&
-       mContext.IsGlContextCreated() )
-  {
-    Load();
-  }
-
   if ( mLinked )
   {
-    if ( this != mContext.GetCurrentProgram() )
+    if ( this != mCache.GetCurrentProgram() )
     {
       LOG_GL( "UseProgram(%d)\n", mProgramId );
-      CHECK_GL( mContext, mGlAbstraction.UseProgram(mProgramId) );
-      INCREASE_COUNTER(PerformanceMonitor::SHADER_STATE_CHANGES);
+      CHECK_GL( mGlAbstraction, mGlAbstraction.UseProgram(mProgramId) );
 
-      mContext.SetCurrentProgram( this );
+      mCache.SetCurrentProgram( this );
     }
   }
 }
 
 bool Program::IsUsed()
 {
-  return ( this == mContext.GetCurrentProgram() );
+  return ( this == mCache.GetCurrentProgram() );
 }
 
 GLint Program::GetAttribLocation( AttribType type )
 {
   DALI_ASSERT_DEBUG(type != ATTRIB_UNKNOWN);
 
-  if( mAttribLocations[ type ] == ATTRIB_UNKNOWN )
+  return GetCustomAttributeLocation( type );
+}
+
+unsigned int Program::RegisterCustomAttribute( const std::string& name )
+{
+  unsigned int index = 0;
+  // find the value from cache
+  for( ;index < mAttributeLocations.size(); ++index )
   {
-    LOG_GL( "GetAttribLocation(program=%d,%s) = %d\n", mProgramId, gStdAttribs[type], mAttribLocations[type] );
-    GLint loc = CHECK_GL( mContext, mGlAbstraction.GetAttribLocation( mProgramId, gStdAttribs[type] ) );
-    mAttribLocations[ type ] = loc;
+    if( mAttributeLocations[ index ].first == name )
+    {
+      // name found so return index
+      return index;
+    }
   }
-
-  return mAttribLocations[type];
+  // if we get here, index is one past end so push back the new name
+  mAttributeLocations.push_back( std::make_pair( name, ATTRIB_UNKNOWN ) );
+  return index;
 }
 
-unsigned int Program::RegisterExternalUniform( const std::string& name )
+GLint Program::GetCustomAttributeLocation( unsigned int attributeIndex )
 {
-  // insert the name in the table to keep it alive as long as this program exists
-  // we rely on C++ strings COW behaviour to keep the char* alive.
-  // TODO In C++ 11 this is no longer the case so this code needs changing if we upgrade
-  mExternalUniformNames.insert( name );
-  return RegisterUniform( name.c_str() );
+  // debug check that index is within name cache
+  DALI_ASSERT_DEBUG( mAttributeLocations.size() > attributeIndex );
+
+  // check if we have already queried the location of the attribute
+  GLint location = mAttributeLocations[ attributeIndex ].second;
+
+  if( location == ATTRIB_UNKNOWN )
+  {
+    location = CHECK_GL( mGlAbstraction, mGlAbstraction.GetAttribLocation( mProgramId, mAttributeLocations[ attributeIndex ].first.c_str() ) );
+
+    mAttributeLocations[ attributeIndex ].second = location;
+    LOG_GL( "GetAttributeLocation(program=%d,%s) = %d\n", mProgramId, mAttributeLocations[ attributeIndex ].first.c_str(), mAttributeLocations[ attributeIndex ].second );
+  }
+
+  return location;
 }
 
-unsigned int Program::RegisterUniform( const char* name )
+
+unsigned int Program::RegisterUniform( const std::string& name )
 {
   unsigned int index = 0;
   // find the value from cache
-  for( ;index < mCustomUniformLocations.size(); ++index )
+  for( ;index < mUniformLocations.size(); ++index )
   {
-    if( !strcmp( mCustomUniformLocations[ index ].first, name ) )
+    if( mUniformLocations[ index ].first == name )
     {
-      // name found so return index plus built in index count
-      return index + UNIFORM_TYPE_LAST;
+      // name found so return index
+      return index;
     }
   }
   // if we get here, index is one past end so push back the new name
-  mCustomUniformLocations.push_back( std::make_pair( name, UNIFORM_NOT_QUERIED ) );
-  return index + UNIFORM_TYPE_LAST; // remember to add the count of the built in ones
+  mUniformLocations.push_back( std::make_pair( name, UNIFORM_NOT_QUERIED ) );
+  return index;
 }
 
 GLint Program::GetUniformLocation( unsigned int uniformIndex )
 {
-  GLint location = UNIFORM_NOT_QUERIED;
-  // is it built in
-  if( uniformIndex < UNIFORM_TYPE_LAST )
+  // debug check that index is within name cache
+  DALI_ASSERT_DEBUG( mUniformLocations.size() > uniformIndex );
+
+  // check if we have already queried the location of the uniform
+  GLint location = mUniformLocations[ uniformIndex ].second;
+
+  if( location == UNIFORM_NOT_QUERIED )
+  {
+    location = CHECK_GL( mGlAbstraction, mGlAbstraction.GetUniformLocation( mProgramId, mUniformLocations[ uniformIndex ].first.c_str() ) );
+
+    mUniformLocations[ uniformIndex ].second = location;
+    LOG_GL( "GetUniformLocation(program=%d,%s) = %d\n", mProgramId, mUniformLocations[ uniformIndex ].first.c_str(), mUniformLocations[ uniformIndex ].second );
+  }
+
+  return location;
+}
+
+namespace
+{
+/**
+ * This struct is used to record the position of a uniform declaration
+ * within the fragment shader source code.
+ */
+struct LocationPosition
+{
+  GLint uniformLocation; ///< The location of the uniform (used as an identifier)
+  int position;          ///< the position of the uniform declaration
+  LocationPosition( GLint uniformLocation, int position )
+  : uniformLocation(uniformLocation), position(position)
   {
-    // check if we have already queried the location of the uniform
-    location = mBuiltinUniformLocations[ uniformIndex ];
-    if( location  == UNIFORM_NOT_QUERIED )
+  }
+};
+
+bool sortByPosition( LocationPosition a, LocationPosition b )
+{
+  return a.position < b.position;
+}
+}
+
+void Program::GetActiveSamplerUniforms()
+{
+  GLint numberOfActiveUniforms = -1;
+  GLint uniformMaxNameLength=-1;
+
+  mGlAbstraction.GetProgramiv( mProgramId, GL_ACTIVE_UNIFORMS, &numberOfActiveUniforms );
+  mGlAbstraction.GetProgramiv( mProgramId, GL_ACTIVE_UNIFORM_MAX_LENGTH, &uniformMaxNameLength );
+
+  std::vector<std::string> samplerNames;
+  std::vector<char> name(uniformMaxNameLength + 1); // Allow for null terminator
+  std::vector< LocationPosition >  samplerUniformLocations;
+
+  {
+    int nameLength = -1;
+    int number = -1;
+    GLenum type = GL_ZERO;
+
+    for( int i=0; i<numberOfActiveUniforms; ++i )
     {
-      LOG_GL( "GetUniformLocation(program=%d,%s) = %d\n", mProgramId, mBuiltinUniformLocations[ uniformIndex ], gStdUniforms[ uniformIndex ] );
-      location = CHECK_GL( mContext, mGlAbstraction.GetUniformLocation( mProgramId, gStdUniforms[ uniformIndex ] ) );
+      mGlAbstraction.GetActiveUniform( mProgramId, static_cast< GLuint >( i ), uniformMaxNameLength,
+                                       &nameLength, &number, &type, name.data() );
 
-      mBuiltinUniformLocations[ uniformIndex ] = location;
+      if( type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE || type == GL_SAMPLER_EXTERNAL_OES )
+      {
+        GLuint location = mGlAbstraction.GetUniformLocation( mProgramId, name.data() );
+        samplerNames.push_back( name.data() );
+        samplerUniformLocations.push_back(LocationPosition(location, -1));
+      }
     }
   }
-  else
+
+  //Determine declaration order of each sampler
+  char* fragShader = strdup( mProgramData->GetFragmentShader() );
+  char* nextPtr = NULL;
+  const char* token = strtok_r( fragShader, " ;\n", &nextPtr );
+  int samplerPosition = 0;
+  while( token )
   {
-    // translate the index to custom locations vector
-    unsigned int customIndex = uniformIndex - UNIFORM_TYPE_LAST;
-    if( customIndex < mCustomUniformLocations.size() ) // custom uniform
+    if( ( strncmp( token, "sampler2D", 9u )    == 0 ) ||
+        ( strncmp( token, "samplerCube", 11u ) == 0 ) ||
+        ( strncmp( token, "samplerExternalOES", 18u ) == 0 ) )
     {
-      // check if we have already queried the location of the uniform
-      location = mCustomUniformLocations[ customIndex ].second;
-      if( location == UNIFORM_NOT_QUERIED )
+      bool found( false );
+      token = strtok_r( NULL, " ;\n", &nextPtr );
+      for( size_t i=0; i<samplerUniformLocations.size(); ++i )
       {
-        LOG_GL( "GetUniformLocation(program=%d,%s) = %d\n", mProgramId, mCustomUniformLocations[ customIndex ].first, mCustomUniformLocations[ customIndex ].second );
-        location = CHECK_GL( mContext, mGlAbstraction.GetUniformLocation( mProgramId, mCustomUniformLocations[ customIndex ].first ) );
-
-        mCustomUniformLocations[ customIndex ].second = location;
+        if( samplerUniformLocations[i].position == -1 &&
+            strncmp( token, samplerNames[i].c_str(), samplerNames[i].size() ) == 0 )
+        {
+          samplerUniformLocations[i].position = samplerPosition++;
+          found = true;
+          break;
+        }
+      }
+      if( !found )
+      {
+        DALI_LOG_ERROR("Sampler uniform %s declared but not used in the shader\n", token );
       }
     }
+    else
+    {
+      token = strtok_r( NULL, " ;\n", &nextPtr );
+    }
   }
 
-  return location;
+  free( fragShader );
+
+  // Re-order according to declaration order in the fragment source.
+  size_t samplerUniformCount = samplerUniformLocations.size();
+  if( samplerUniformCount > 1 )
+  {
+    std::sort( samplerUniformLocations.begin(), samplerUniformLocations.end(), sortByPosition);
+  }
+
+  mSamplerUniformLocations.resize( samplerUniformCount );
+  for( size_t i=0; i<samplerUniformCount; ++i )
+  {
+    mSamplerUniformLocations[i] = samplerUniformLocations[i].uniformLocation;
+  }
+}
+
+bool Program::GetSamplerUniformLocation( unsigned int index, GLint& location  )
+{
+  bool result = false;
+  if( index < mSamplerUniformLocations.size() )
+  {
+    location = mSamplerUniformLocations[index];
+    result = true;
+  }
+  return result;
+}
+
+size_t Program::GetActiveSamplerCount() const
+{
+  return mSamplerUniformLocations.size();
 }
 
 void Program::SetUniform1i( GLint location, GLint value0 )
@@ -256,18 +351,18 @@ void Program::SetUniform1i( GLint location, GLint value0 )
   // check if uniform location fits the cache
   if( location >= MAX_UNIFORM_CACHE_SIZE )
   {
-    // not cached, make the gl call through context
+    // not cached, make the gl call
     LOG_GL( "Uniform1i(%d,%d)\n", location, value0 );
-    CHECK_GL( mContext, mGlAbstraction.Uniform1i( location, value0 ) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1i( location, value0 ) );
   }
   else
   {
     // check if the value is different from what's already been set
     if( value0 != mUniformCacheInt[ location ] )
     {
-      // make the gl call through context
+      // make the gl call
       LOG_GL( "Uniform1i(%d,%d)\n", location, value0 );
-      CHECK_GL( mContext, mGlAbstraction.Uniform1i( location, value0 ) );
+      CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1i( location, value0 ) );
       // update cache
       mUniformCacheInt[ location ] = value0;
     }
@@ -288,7 +383,7 @@ void Program::SetUniform4i( GLint location, GLint value0, GLint value1, GLint va
 
   // Not caching these as based on current analysis this is not called that often by our shaders
   LOG_GL( "Uniform4i(%d,%d,%d,%d,%d)\n", location, value0, value1, value2, value3 );
-  CHECK_GL( mContext, mGlAbstraction.Uniform4i( location, value0, value1, value2, value3 ) );
+  CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4i( location, value0, value1, value2, value3 ) );
 }
 
 void Program::SetUniform1f( GLint location, GLfloat value0 )
@@ -306,18 +401,18 @@ void Program::SetUniform1f( GLint location, GLfloat value0 )
   // check if uniform location fits the cache
   if( location >= MAX_UNIFORM_CACHE_SIZE )
   {
-    // not cached, make the gl call through context
+    // not cached, make the gl call
     LOG_GL( "Uniform1f(%d,%f)\n", location, value0 );
-    CHECK_GL( mContext, mGlAbstraction.Uniform1f( location, value0 ) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1f( location, value0 ) );
   }
   else
   {
     // check if the same value has already been set, reset if it is different
     if( ( fabsf(value0 - mUniformCacheFloat[ location ]) >= Math::MACHINE_EPSILON_1 ) )
     {
-      // make the gl call through context
+      // make the gl call
       LOG_GL( "Uniform1f(%d,%f)\n", location, value0 );
-      CHECK_GL( mContext, mGlAbstraction.Uniform1f( location, value0 ) );
+      CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1f( location, value0 ) );
 
       // update cache
       mUniformCacheFloat[ location ] = value0;
@@ -337,9 +432,41 @@ void Program::SetUniform2f( GLint location, GLfloat value0, GLfloat value1 )
     return;
   }
 
-  // Not caching these as based on current analysis this is not called that often by our shaders
-  LOG_GL( "Uniform2f(%d,%f,%f)\n", location, value0, value1 );
-  CHECK_GL( mContext, mGlAbstraction.Uniform2f( location, value0, value1 ) );
+  // check if uniform location fits the cache
+  if( location >= MAX_UNIFORM_CACHE_SIZE )
+  {
+    // not cached, make the gl call
+    LOG_GL( "Uniform2f(%d,%f,%f)\n", location, value0, value1 );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform2f( location, value0, value1 ) );
+  }
+  else
+  {
+    // check if the same value has already been set, reset if it is different
+    if( ( fabsf(value0 - mUniformCacheFloat2[ location ][ 0 ]) >= Math::MACHINE_EPSILON_1 )||
+        ( fabsf(value1 - mUniformCacheFloat2[ location ][ 1 ]) >= Math::MACHINE_EPSILON_1 ) )
+    {
+      // make the gl call
+      LOG_GL( "Uniform2f(%d,%f,%f)\n", location, value0, value1 );
+      CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform2f( location, value0, value1 ) );
+
+      // update cache
+      mUniformCacheFloat2[ location ][ 0 ] = value0;
+      mUniformCacheFloat2[ location ][ 1 ] = value1;
+    }
+  }
+}
+
+void Program::SetSizeUniform3f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2 )
+{
+  if( ( fabsf(value0 - mSizeUniformCache.x) >= Math::MACHINE_EPSILON_1 )||
+      ( fabsf(value1 - mSizeUniformCache.y) >= Math::MACHINE_EPSILON_1 )||
+      ( fabsf(value2 - mSizeUniformCache.z) >= Math::MACHINE_EPSILON_1 ) )
+  {
+    mSizeUniformCache.x = value0;
+    mSizeUniformCache.y = value1;
+    mSizeUniformCache.z = value2;
+    SetUniform3f( location, value0, value1, value2 );
+  }
 }
 
 void Program::SetUniform3f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2 )
@@ -356,7 +483,7 @@ void Program::SetUniform3f( GLint location, GLfloat value0, GLfloat value1, GLfl
 
   // Not caching these as based on current analysis this is not called that often by our shaders
   LOG_GL( "Uniform3f(%d,%f,%f,%f)\n", location, value0, value1, value2 );
-  CHECK_GL( mContext, mGlAbstraction.Uniform3f( location, value0, value1, value2 ) );
+  CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform3f( location, value0, value1, value2 ) );
 }
 
 void Program::SetUniform4f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2, GLfloat value3 )
@@ -374,9 +501,9 @@ void Program::SetUniform4f( GLint location, GLfloat value0, GLfloat value1, GLfl
   // check if uniform location fits the cache
   if( location >= MAX_UNIFORM_CACHE_SIZE )
   {
-    // not cached, make the gl call through context
+    // not cached, make the gl call
     LOG_GL( "Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3 );
-    CHECK_GL( mContext, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
   }
   else
   {
@@ -387,9 +514,9 @@ void Program::SetUniform4f( GLint location, GLfloat value0, GLfloat value1, GLfl
         ( fabsf(value1 - mUniformCacheFloat4[ location ][ 1 ]) >= Math::MACHINE_EPSILON_1 )||
         ( fabsf(value2 - mUniformCacheFloat4[ location ][ 2 ]) >= Math::MACHINE_EPSILON_1 ) )
     {
-      // make the gl call through context
+      // make the gl call
       LOG_GL( "Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3 );
-      CHECK_GL( mContext, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
+      CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
       // update cache
       mUniformCacheFloat4[ location ][ 0 ] = value0;
       mUniformCacheFloat4[ location ][ 1 ] = value1;
@@ -411,12 +538,11 @@ void Program::SetUniformMatrix4fv( GLint location, GLsizei count, const GLfloat*
     return;
   }
 
-
   // Not caching these calls. Based on current analysis this is called very often
   // but with different values (we're using this for MVP matrices)
-  // NOTE! we never want GPU to transpose
+  // NOTE! we never want driver or GPU to transpose
   LOG_GL( "UniformMatrix4fv(%d,%d,GL_FALSE,%x)\n", location, count, value );
-  CHECK_GL( mContext, mGlAbstraction.UniformMatrix4fv( location, count, GL_FALSE, value ) );
+  CHECK_GL( mGlAbstraction, mGlAbstraction.UniformMatrix4fv( location, count, GL_FALSE, value ) );
 }
 
 void Program::SetUniformMatrix3fv( GLint location, GLsizei count, const GLfloat* value )
@@ -434,99 +560,112 @@ void Program::SetUniformMatrix3fv( GLint location, GLsizei count, const GLfloat*
 
   // Not caching these calls. Based on current analysis this is called very often
   // but with different values (we're using this for MVP matrices)
-  // NOTE! we never want GPU to transpose
+  // NOTE! we never want driver or GPU to transpose
   LOG_GL( "UniformMatrix3fv(%d,%d,GL_FALSE,%x)\n", location, count, value );
-  CHECK_GL( mContext, mGlAbstraction.UniformMatrix3fv( location, count, GL_FALSE, value ) );
+  CHECK_GL( mGlAbstraction, mGlAbstraction.UniformMatrix3fv( location, count, GL_FALSE, value ) );
 }
 
 void Program::GlContextCreated()
 {
-  if (!mLinked)
-  {
-    Load();
-  }
 }
 
-void Program::GlContextToBeDestroyed()
+void Program::GlContextDestroyed()
 {
-  Unload();
-
+  mLinked = false;
   mVertexShaderId = 0;
   mFragmentShaderId = 0;
   mProgramId = 0;
-  mContext.SetCurrentProgram( NULL );
 
-  ResetAttribsUniforms();
+  ResetAttribsUniformCache();
 }
 
-Program::Program(Integration::ShaderData* shaderData, Context& context )
-: mContext( context ),
-  mGlAbstraction( context.GetAbstraction() ),
+bool Program::ModifiesGeometry()
+{
+  return mModifiesGeometry;
+}
+
+Program::Program( ProgramCache& cache, Internal::ShaderDataPtr shaderData, bool modifiesGeometry )
+: mCache( cache ),
+  mGlAbstraction( mCache.GetGlAbstraction() ),
+  mProjectionMatrix( NULL ),
+  mViewMatrix( NULL ),
   mLinked( false ),
   mVertexShaderId( 0 ),
   mFragmentShaderId( 0 ),
   mProgramId( 0 ),
-  mProgramData(shaderData)
+  mProgramData(shaderData),
+  mModifiesGeometry( modifiesGeometry )
 {
-  // reset values
-  ResetAttribsUniforms();
+  // reserve space for standard attributes
+  mAttributeLocations.reserve( ATTRIB_TYPE_LAST );
+  for( int i=0; i<ATTRIB_TYPE_LAST; ++i )
+  {
+    RegisterCustomAttribute( gStdAttribs[i] );
+  }
 
-  mContext.AddObserver( *this );
+  // reserve space for standard uniforms
+  mUniformLocations.reserve( UNIFORM_TYPE_LAST );
+  // reset built in uniform names in cache
+  for( int i = 0; i < UNIFORM_TYPE_LAST; ++i )
+  {
+    RegisterUniform( gStdUniforms[ i ] );
+  }
+
+  // reset values
+  ResetAttribsUniformCache();
 }
 
 Program::~Program()
 {
-  mContext.RemoveObserver( *this );
-
-  Unload(); // Resets gCurrentProgram
+  Unload();
 }
 
 void Program::Load()
 {
-  DALI_ASSERT_ALWAYS( NULL != mProgramData && "Program data is not initialized" );
-
-  Unload();
+  DALI_ASSERT_ALWAYS( NULL != mProgramData.Get() && "Program data is not initialized" );
+  DALI_ASSERT_DEBUG( mProgramId == 0 && "mProgramId != 0, so about to leak a GL resource by overwriting it." );
 
   LOG_GL( "CreateProgram()\n" );
-  mProgramId = CHECK_GL( mContext, mGlAbstraction.CreateProgram() );
+  mProgramId = CHECK_GL( mGlAbstraction, mGlAbstraction.CreateProgram() );
 
   GLint linked = GL_FALSE;
 
-  // ShaderData contains compiled bytecode?
-  if( 0 != mContext.CachedNumberOfProgramBinaryFormats() && mProgramData->HasBinary() )
+  const bool binariesSupported = mCache.IsBinarySupported();
+
+  // if shader binaries are supported and ShaderData contains compiled bytecode?
+  if( binariesSupported && mProgramData->HasBinary() )
   {
-    DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - Using Compiled Shader, Size = %d\n", mProgramData->buffer.size());
+    DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - Using Compiled Shader, Size = %d\n", mProgramData->GetBufferSize());
 
-    CHECK_GL( mContext, mGlAbstraction.ProgramBinary(mProgramId, mContext.CachedProgramBinaryFormat(), mProgramData->buffer.data(), mProgramData->buffer.size()) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.ProgramBinary(mProgramId, mCache.ProgramBinaryFormat(), mProgramData->GetBufferData(), mProgramData->GetBufferSize()) );
 
-    CHECK_GL( mContext, mGlAbstraction.ValidateProgram(mProgramId) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.ValidateProgram(mProgramId) );
 
     GLint success;
-    CHECK_GL( mContext, mGlAbstraction.GetProgramiv( mProgramId, GL_VALIDATE_STATUS, &success ) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_VALIDATE_STATUS, &success ) );
 
     DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "ValidateProgram Status = %d\n", success);
 
-    CHECK_GL( mContext, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
 
     if( GL_FALSE == linked )
     {
       DALI_LOG_ERROR("Failed to load program binary \n");
 
-      char* szLog = NULL;
       GLint nLength;
-      CHECK_GL( mContext, mGlAbstraction.GetProgramiv( mProgramId, GL_INFO_LOG_LENGTH, &nLength) );
+      CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_INFO_LOG_LENGTH, &nLength) );
       if(nLength > 0)
       {
-        szLog = new char[ nLength ];
-        CHECK_GL( mContext, mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog ) );
-        DALI_LOG_ERROR( "Program Link Error: %s\n", szLog );
-
-        delete [] szLog;
+        Dali::Vector< char > szLog;
+        szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
+        CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog.Begin() ) );
+        DALI_LOG_ERROR( "Program Link Error: %s\n", szLog.Begin() );
       }
     }
     else
     {
       mLinked = true;
+      DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "Reused binary.\n" );
     }
   }
 
@@ -534,49 +673,55 @@ void Program::Load()
   if( GL_FALSE == linked )
   {
     DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - Runtime compilation\n");
-    if( CompileShader( GL_VERTEX_SHADER, mVertexShaderId, mProgramData->vertexShader.c_str() ) )
+    if( CompileShader( GL_VERTEX_SHADER, mVertexShaderId, mProgramData->GetVertexShader() ) )
     {
-      if( CompileShader( GL_FRAGMENT_SHADER, mFragmentShaderId, mProgramData->fragmentShader.c_str() ) )
+      if( CompileShader( GL_FRAGMENT_SHADER, mFragmentShaderId, mProgramData->GetFragmentShader() ) )
       {
         Link();
 
-        if( mLinked )
+        if( binariesSupported && mLinked )
         {
           GLint  binaryLength = 0;
           GLenum binaryFormat;
+          DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "Compiled and linked.\n\nVS:\n%s\nFS:\n%s\n", mProgramData->GetVertexShader(), mProgramData->GetFragmentShader() );
 
-          CHECK_GL( mContext, mGlAbstraction.GetProgramiv(mProgramId, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength) );
+          CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv(mProgramId, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength) );
           DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - GL_PROGRAM_BINARY_LENGTH_OES: %d\n", binaryLength);
-
-          // Allocate space for the bytecode in ShaderData
-          mProgramData->AllocateBuffer(binaryLength);
-          // Copy the bytecode to ShaderData
-          CHECK_GL( mContext, mGlAbstraction.GetProgramBinary(mProgramId, binaryLength, NULL, &binaryFormat, mProgramData->buffer.data()) );
+          if( binaryLength > 0 )
+          {
+            // Allocate space for the bytecode in ShaderData
+            mProgramData->AllocateBuffer(binaryLength);
+            // Copy the bytecode to ShaderData
+            CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramBinary(mProgramId, binaryLength, NULL, &binaryFormat, mProgramData->GetBufferData()) );
+            mCache.StoreBinary( mProgramData );
+            DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "Saved binary.\n" );
+          }
         }
       }
     }
   }
 
+  GetActiveSamplerUniforms();
+
   // No longer needed
   FreeShaders();
-
 }
 
 void Program::Unload()
 {
   FreeShaders();
 
-  if( this == mContext.GetCurrentProgram() )
+  if( this == mCache.GetCurrentProgram() )
   {
-    CHECK_GL( mContext, mGlAbstraction.UseProgram(0) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.UseProgram(0) );
 
-    mContext.SetCurrentProgram( NULL );
+    mCache.SetCurrentProgram( NULL );
   }
 
   if (mProgramId)
   {
     LOG_GL( "DeleteProgram(%d)\n", mProgramId );
-    CHECK_GL( mContext, mGlAbstraction.DeleteProgram( mProgramId ) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteProgram( mProgramId ) );
     mProgramId = 0;
   }
 
@@ -589,37 +734,37 @@ bool Program::CompileShader( GLenum shaderType, GLuint& shaderId, const char* sr
   if (!shaderId)
   {
     LOG_GL( "CreateShader(%d)\n", shaderType );
-    shaderId = CHECK_GL( mContext, mGlAbstraction.CreateShader( shaderType ) );
+    shaderId = CHECK_GL( mGlAbstraction, mGlAbstraction.CreateShader( shaderType ) );
     LOG_GL( "AttachShader(%d,%d)\n", mProgramId, shaderId );
-    CHECK_GL( mContext, mGlAbstraction.AttachShader( mProgramId, shaderId ) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.AttachShader( mProgramId, shaderId ) );
   }
 
   LOG_GL( "ShaderSource(%d)\n", shaderId );
-  CHECK_GL( mContext, mGlAbstraction.ShaderSource(shaderId, 1, &src, NULL ) );
+  CHECK_GL( mGlAbstraction, mGlAbstraction.ShaderSource(shaderId, 1, &src, NULL ) );
 
   LOG_GL( "CompileShader(%d)\n", shaderId );
-  CHECK_GL( mContext, mGlAbstraction.CompileShader( shaderId ) );
+  CHECK_GL( mGlAbstraction, mGlAbstraction.CompileShader( shaderId ) );
 
   GLint compiled;
   LOG_GL( "GetShaderiv(%d)\n", shaderId );
-  CHECK_GL( mContext, mGlAbstraction.GetShaderiv( shaderId, GL_COMPILE_STATUS, &compiled ) );
+  CHECK_GL( mGlAbstraction, mGlAbstraction.GetShaderiv( shaderId, GL_COMPILE_STATUS, &compiled ) );
 
   if (compiled == GL_FALSE)
   {
     DALI_LOG_ERROR("Failed to compile shader\n");
     LogWithLineNumbers(src);
 
-    std::vector< char > szLog;
     GLint nLength;
     mGlAbstraction.GetShaderiv( shaderId, GL_INFO_LOG_LENGTH, &nLength);
     if(nLength > 0)
     {
-      szLog.reserve( nLength );
-      mGlAbstraction.GetShaderInfoLog( shaderId, nLength, &nLength, &szLog[ 0 ] );
-      DALI_LOG_ERROR( "Shader Compiler Error: %s\n", &szLog[ 0 ] );
+      Dali::Vector< char > szLog;
+      szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
+      mGlAbstraction.GetShaderInfoLog( shaderId, nLength, &nLength, szLog.Begin() );
+      DALI_LOG_ERROR( "Shader Compiler Error: %s\n", szLog.Begin() );
     }
 
-    throw DaliException( "Shader compilation failure", &szLog[ 0 ] );
+    DALI_ASSERT_ALWAYS( 0 && "Shader compilation failure" );
   }
 
   return compiled != 0;
@@ -628,28 +773,27 @@ bool Program::CompileShader( GLenum shaderType, GLuint& shaderId, const char* sr
 void Program::Link()
 {
   LOG_GL( "LinkProgram(%d)\n", mProgramId );
-  CHECK_GL( mContext, mGlAbstraction.LinkProgram( mProgramId ) );
+  CHECK_GL( mGlAbstraction, mGlAbstraction.LinkProgram( mProgramId ) );
 
   GLint linked;
   LOG_GL( "GetProgramiv(%d)\n", mProgramId );
-  CHECK_GL( mContext, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
+  CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
 
   if (linked == GL_FALSE)
   {
     DALI_LOG_ERROR("Shader failed to link \n");
 
-    char* szLog = NULL;
     GLint nLength;
     mGlAbstraction.GetProgramiv( mProgramId, GL_INFO_LOG_LENGTH, &nLength);
     if(nLength > 0)
     {
-      szLog = new char[ nLength ];
-      mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog );
-      DALI_LOG_ERROR( "Shader Link Error: %s\n", szLog );
-      delete [] szLog;
+      Dali::Vector< char > szLog;
+      szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
+      mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog.Begin() );
+      DALI_LOG_ERROR( "Shader Link Error: %s\n", szLog.Begin() );
     }
 
-    DALI_ASSERT_DEBUG(0);
+    DALI_ASSERT_ALWAYS( 0 && "Shader linking failure" );
   }
 
   mLinked = linked != GL_FALSE;
@@ -660,44 +804,47 @@ void Program::FreeShaders()
   if (mVertexShaderId)
   {
     LOG_GL( "DeleteShader(%d)\n", mVertexShaderId );
-    CHECK_GL( mContext, mGlAbstraction.DetachShader( mProgramId, mVertexShaderId ) );
-    CHECK_GL( mContext, mGlAbstraction.DeleteShader( mVertexShaderId ) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.DetachShader( mProgramId, mVertexShaderId ) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteShader( mVertexShaderId ) );
     mVertexShaderId = 0;
   }
 
   if (mFragmentShaderId)
   {
     LOG_GL( "DeleteShader(%d)\n", mFragmentShaderId );
-    CHECK_GL( mContext, mGlAbstraction.DetachShader( mProgramId, mFragmentShaderId ) );
-    CHECK_GL( mContext, mGlAbstraction.DeleteShader( mFragmentShaderId ) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.DetachShader( mProgramId, mFragmentShaderId ) );
+    CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteShader( mFragmentShaderId ) );
     mFragmentShaderId = 0;
   }
 }
 
-void Program::ResetAttribsUniforms()
+void Program::ResetAttribsUniformCache()
 {
   // reset attribute locations
-  for( unsigned i = 0; i < ATTRIB_TYPE_LAST; ++i )
+  for( unsigned i = 0; i < mAttributeLocations.size() ; ++i )
   {
-    mAttribLocations[ i ] = ATTRIB_UNKNOWN;
+    mAttributeLocations[ i ].second = ATTRIB_UNKNOWN;
   }
 
   // reset all gl uniform locations
-  for( unsigned int i = 0; i < UNIFORM_TYPE_LAST; ++i )
+  for( unsigned int i = 0; i < mUniformLocations.size(); ++i )
   {
-    mBuiltinUniformLocations[ i ] = UNIFORM_NOT_QUERIED;
-  }
-  for( unsigned int i = 0; i < mCustomUniformLocations.size(); ++i )
-  {
-    mCustomUniformLocations[ i ].second = UNIFORM_NOT_QUERIED;
+    // reset gl program locations and names
+    mUniformLocations[ i ].second = UNIFORM_NOT_QUERIED;
   }
 
-  // reset uniform cache
+  mSamplerUniformLocations.clear();
+
+  // reset uniform caches
+  mSizeUniformCache.x = mSizeUniformCache.y = mSizeUniformCache.z = 0.f;
+
   for( int i = 0; i < MAX_UNIFORM_CACHE_SIZE; ++i )
   {
     // GL initializes uniforms to 0
     mUniformCacheInt[ i ] = 0;
     mUniformCacheFloat[ i ] = 0.0f;
+    mUniformCacheFloat2[ i ][ 0 ] = 0.0f;
+    mUniformCacheFloat2[ i ][ 1 ] = 0.0f;
     mUniformCacheFloat4[ i ][ 0 ] = 0.0f;
     mUniformCacheFloat4[ i ][ 1 ] = 0.0f;
     mUniformCacheFloat4[ i ][ 2 ] = 0.0f;