Create UBO for uniform buffer bindings
[platform/core/uifw/dali-core.git] / dali / internal / render / shaders / program.cpp
1 /*
2  * Copyright (c) 2021 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 <dali/internal/render/shaders/program.h>
20
21 // EXTERNAL INCLUDES
22 #include <cstring>
23 #include <iomanip>
24 #include <map>
25
26 // INTERNAL INCLUDES
27 #include <dali/devel-api/common/hash.h>
28 #include <dali/graphics-api/graphics-controller.h>
29 #include <dali/graphics-api/graphics-program.h>
30 #include <dali/graphics-api/graphics-reflection.h>
31 #include <dali/integration-api/debug.h>
32 #include <dali/integration-api/gl-defines.h>
33 #include <dali/internal/common/shader-data.h>
34 #include <dali/internal/render/common/performance-monitor.h>
35 #include <dali/internal/render/gl-resources/gl-call-debug.h>
36 #include <dali/internal/render/shaders/program-cache.h>
37 #include <dali/public-api/common/constants.h>
38 #include <dali/public-api/common/dali-common.h>
39 #include <dali/public-api/common/dali-vector.h>
40
41 namespace
42 {
43 void LogWithLineNumbers(const char* source)
44 {
45   uint32_t    lineNumber = 0u;
46   const char* prev       = source;
47   const char* ptr        = prev;
48
49   while(true)
50   {
51     if(lineNumber > 200u)
52     {
53       break;
54     }
55     // seek the next end of line or end of text
56     while(*ptr != '\n' && *ptr != '\0')
57     {
58       ++ptr;
59     }
60
61     std::string line(prev, ptr - prev);
62     Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugError, "%4d %s\n", lineNumber, line.c_str());
63
64     if(*ptr == '\0')
65     {
66       break;
67     }
68     prev = ++ptr;
69     ++lineNumber;
70   }
71 }
72
73 } //namespace
74
75 namespace Dali
76 {
77 namespace Internal
78 {
79 // LOCAL STUFF
80 namespace
81 {
82 const char* const gStdAttribs[Program::ATTRIB_TYPE_LAST] =
83   {
84     "aPosition", // ATTRIB_POSITION
85     "aTexCoord", // ATTRIB_TEXCOORD
86 };
87
88 const char* const gStdUniforms[Program::UNIFORM_TYPE_LAST] =
89   {
90     "uMvpMatrix",    // UNIFORM_MVP_MATRIX
91     "uModelView",    // UNIFORM_MODELVIEW_MATRIX
92     "uProjection",   // UNIFORM_PROJECTION_MATRIX
93     "uModelMatrix",  // UNIFORM_MODEL_MATRIX,
94     "uViewMatrix",   // UNIFORM_VIEW_MATRIX,
95     "uNormalMatrix", // UNIFORM_NORMAL_MATRIX
96     "uColor",        // UNIFORM_COLOR
97     "sTexture",      // UNIFORM_SAMPLER
98     "sTextureRect",  // UNIFORM_SAMPLER_RECT
99     "sEffect",       // UNIFORM_EFFECT_SAMPLER
100     "uSize"          // UNIFORM_SIZE
101 };
102
103 /**
104  * List of all default uniforms used for quicker lookup
105  */
106 std::array<size_t, 8> DEFAULT_UNIFORM_HASHTABLE =
107   {
108     CalculateHash(std::string("uModelMatrix")),
109     CalculateHash(std::string("uMvpMatrix")),
110     CalculateHash(std::string("uViewMatrix")),
111     CalculateHash(std::string("uModelView")),
112     CalculateHash(std::string("uNormalMatrix")),
113     CalculateHash(std::string("uProjection")),
114     CalculateHash(std::string("uSize")),
115     CalculateHash(std::string("uColor"))};
116
117 } // namespace
118
119 // IMPLEMENTATION
120
121 Program* Program::New(ProgramCache& cache, Internal::ShaderDataPtr shaderData, Graphics::Controller& gfxController, Graphics::UniquePtr<Graphics::Program>&& gfxProgram, bool modifiesGeometry)
122 {
123   uint32_t programId{0u};
124
125   // Get program id and use it as hash for the cache
126   // in order to maintain current functionality as long as needed
127   gfxController.GetProgramParameter(*gfxProgram, 1, &programId);
128
129   size_t shaderHash = programId;
130
131   Program* program = cache.GetProgram(shaderHash);
132
133   if(nullptr == program)
134   {
135     // program not found so create it
136     program = new Program(cache, shaderData, gfxController, std::move(gfxProgram), modifiesGeometry);
137     program->GetActiveSamplerUniforms();
138     cache.AddProgram(shaderHash, program);
139   }
140
141   return program;
142 }
143
144 void Program::Use()
145 {
146   LOG_GL("UseProgram(%d)\n", mProgramId);
147   CHECK_GL(mGlAbstraction, mGlAbstraction.UseProgram(mProgramId));
148   mCache.SetCurrentProgram(this);
149 }
150
151 bool Program::IsUsed()
152 {
153   return (this == mCache.GetCurrentProgram());
154 }
155
156 GLint Program::GetAttribLocation(AttribType type)
157 {
158   DALI_ASSERT_DEBUG(type != ATTRIB_UNKNOWN);
159
160   return GetCustomAttributeLocation(type);
161 }
162
163 uint32_t Program::RegisterCustomAttribute(ConstString name)
164 {
165   uint32_t index = 0;
166   // find the value from cache
167   for(; index < static_cast<uint32_t>(mAttributeLocations.size()); ++index)
168   {
169     if(mAttributeLocations[index].first == name)
170     {
171       // name found so return index
172       return index;
173     }
174   }
175   // if we get here, index is one past end so push back the new name
176   mAttributeLocations.push_back(std::make_pair(name, ATTRIB_UNKNOWN));
177   return index;
178 }
179
180 GLint Program::GetCustomAttributeLocation(uint32_t attributeIndex)
181 {
182   // debug check that index is within name cache
183   DALI_ASSERT_DEBUG(mAttributeLocations.size() > attributeIndex);
184
185   // check if we have already queried the location of the attribute
186   GLint location = mAttributeLocations[attributeIndex].second;
187
188   if(location == ATTRIB_UNKNOWN)
189   {
190     location = CHECK_GL(mGlAbstraction, mGlAbstraction.GetAttribLocation(mProgramId, mAttributeLocations[attributeIndex].first.GetCString()));
191
192     mAttributeLocations[attributeIndex].second = location;
193     LOG_GL("GetAttributeLocation(program=%d,%s) = %d\n", mProgramId, mAttributeLocations[attributeIndex].first.GetCString(), mAttributeLocations[attributeIndex].second);
194   }
195
196   return location;
197 }
198
199 uint32_t Program::RegisterUniform(ConstString name)
200 {
201   uint32_t index = 0;
202   // find the value from cache
203   for(; index < static_cast<uint32_t>(mUniformLocations.size()); ++index)
204   {
205     if(mUniformLocations[index].first == name)
206     {
207       // name found so return index
208       return index;
209     }
210   }
211   // if we get here, index is one past end so push back the new name
212   mUniformLocations.push_back(std::make_pair(name, UNIFORM_NOT_QUERIED));
213   return index;
214 }
215
216 GLint Program::GetUniformLocation(uint32_t uniformIndex)
217 {
218   // debug check that index is within name cache
219   DALI_ASSERT_DEBUG(mUniformLocations.size() > uniformIndex);
220
221   // check if we have already queried the location of the uniform
222   GLint location = mUniformLocations[uniformIndex].second;
223
224   if(location == UNIFORM_NOT_QUERIED)
225   {
226     location = CHECK_GL(mGlAbstraction, mGlAbstraction.GetUniformLocation(mProgramId, mUniformLocations[uniformIndex].first.GetCString()));
227
228     mUniformLocations[uniformIndex].second = location;
229     LOG_GL("GetUniformLocation(program=%d,%s) = %d\n", mProgramId, mUniformLocations[uniformIndex].first.GetCString(), mUniformLocations[uniformIndex].second);
230   }
231
232   return location;
233 }
234
235 namespace
236 {
237 /**
238  * This struct is used to record the position of a uniform declaration
239  * within the fragment shader source code.
240  */
241 struct LocationPosition
242 {
243   GLint   uniformLocation; ///< The location of the uniform (used as an identifier)
244   int32_t position;        ///< the position of the uniform declaration
245   LocationPosition(GLint uniformLocation, int32_t position)
246   : uniformLocation(uniformLocation),
247     position(position)
248   {
249   }
250 };
251
252 bool sortByPosition(LocationPosition a, LocationPosition b)
253 {
254   return a.position < b.position;
255 }
256
257 const char* const DELIMITERS = " \t\n";
258
259 struct StringSize
260 {
261   const char* const mString;
262   const uint32_t    mLength;
263
264   template<uint32_t kLength>
265   constexpr StringSize(const char (&string)[kLength])
266   : mString(string),
267     mLength(kLength - 1) // remove terminating null; N.B. there should be no other null.
268   {
269   }
270
271   operator const char*() const
272   {
273     return mString;
274   }
275 };
276
277 bool operator==(const StringSize& lhs, const char* rhs)
278 {
279   return strncmp(lhs.mString, rhs, lhs.mLength) == 0;
280 }
281
282 constexpr StringSize UNIFORM{"uniform"};
283 constexpr StringSize SAMPLER_PREFIX{"sampler"};
284 constexpr StringSize SAMPLER_TYPES[] = {
285   "2D",
286   "Cube",
287   "ExternalOES"};
288
289 constexpr auto END_SAMPLER_TYPES = SAMPLER_TYPES + std::extent<decltype(SAMPLER_TYPES)>::value;
290
291 } // namespace
292
293 void Program::GetActiveSamplerUniforms()
294 {
295   GLint numberOfActiveUniforms = -1;
296   GLint uniformMaxNameLength   = -1;
297
298   mGlAbstraction.GetProgramiv(mProgramId, GL_ACTIVE_UNIFORMS, &numberOfActiveUniforms);
299   mGlAbstraction.GetProgramiv(mProgramId, GL_ACTIVE_UNIFORM_MAX_LENGTH, &uniformMaxNameLength);
300
301   std::vector<std::string>      samplerNames;
302   std::vector<char>             name(uniformMaxNameLength + 1); // Allow for null terminator
303   std::vector<LocationPosition> samplerUniformLocations;
304
305   {
306     int    nameLength = -1;
307     int    number     = -1;
308     GLenum type       = GL_ZERO;
309
310     for(int i = 0; i < numberOfActiveUniforms; ++i)
311     {
312       mGlAbstraction.GetActiveUniform(mProgramId, static_cast<GLuint>(i), uniformMaxNameLength, &nameLength, &number, &type, name.data());
313
314       if(type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE || type == GL_SAMPLER_EXTERNAL_OES)
315       {
316         GLuint location = mGlAbstraction.GetUniformLocation(mProgramId, name.data());
317         samplerNames.push_back(name.data());
318         samplerUniformLocations.push_back(LocationPosition(location, -1));
319       }
320     }
321   }
322
323   //Determine declaration order of each sampler
324   char* fragShader      = strdup(mProgramData->GetFragmentShader());
325   char* uniform         = strstr(fragShader, UNIFORM);
326   int   samplerPosition = 0;
327   while(uniform)
328   {
329     char* outerToken = strtok_r(uniform + UNIFORM.mLength, ";", &uniform);
330
331     char* nextPtr = nullptr;
332     char* token   = strtok_r(outerToken, DELIMITERS, &nextPtr);
333     while(token)
334     {
335       if(SAMPLER_PREFIX == token)
336       {
337         token += SAMPLER_PREFIX.mLength;
338         if(std::find(SAMPLER_TYPES, END_SAMPLER_TYPES, token) != END_SAMPLER_TYPES)
339         {
340           bool found(false);
341           token = strtok_r(nullptr, DELIMITERS, &nextPtr);
342           for(uint32_t i = 0; i < static_cast<uint32_t>(samplerUniformLocations.size()); ++i)
343           {
344             if(samplerUniformLocations[i].position == -1 &&
345                strncmp(token, samplerNames[i].c_str(), samplerNames[i].size()) == 0)
346             {
347               samplerUniformLocations[i].position = samplerPosition++;
348               found                               = true;
349               break;
350             }
351           }
352
353           if(!found)
354           {
355             DALI_LOG_ERROR("Sampler uniform %s declared but not used in the shader\n", token);
356           }
357           break;
358         }
359       }
360
361       token = strtok_r(nullptr, DELIMITERS, &nextPtr);
362     }
363
364     uniform = strstr(uniform, UNIFORM);
365   }
366
367   free(fragShader);
368
369   // Re-order according to declaration order in the fragment source.
370   uint32_t samplerUniformCount = static_cast<uint32_t>(samplerUniformLocations.size());
371   if(samplerUniformCount > 1)
372   {
373     std::sort(samplerUniformLocations.begin(), samplerUniformLocations.end(), sortByPosition);
374   }
375
376   mSamplerUniformLocations.resize(samplerUniformCount);
377   for(uint32_t i = 0; i < samplerUniformCount; ++i)
378   {
379     mSamplerUniformLocations[i] = samplerUniformLocations[i].uniformLocation;
380   }
381 }
382
383 bool Program::GetSamplerUniformLocation(uint32_t index, GLint& location)
384 {
385   bool result = false;
386   if(index < mSamplerUniformLocations.size())
387   {
388     location = mSamplerUniformLocations[index];
389     result   = true;
390   }
391   return result;
392 }
393
394 uint32_t Program::GetActiveSamplerCount() const
395 {
396   return static_cast<uint32_t>(mSamplerUniformLocations.size());
397 }
398
399 void Program::SetUniform1i(GLint location, GLint value0)
400 {
401   DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
402
403   if(UNIFORM_UNKNOWN == location)
404   {
405     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
406     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
407     // specified uniform variable will not be changed.following opengl silently do nothing
408     return;
409   }
410
411   // check if uniform location fits the cache
412   if(location >= MAX_UNIFORM_CACHE_SIZE)
413   {
414     // not cached, make the gl call
415     LOG_GL("Uniform1i(%d,%d)\n", location, value0);
416     CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform1i(location, value0));
417   }
418   else
419   {
420     // check if the value is different from what's already been set
421     if(value0 != mUniformCacheInt[location])
422     {
423       // make the gl call
424       LOG_GL("Uniform1i(%d,%d)\n", location, value0);
425       CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform1i(location, value0));
426       // update cache
427       mUniformCacheInt[location] = value0;
428     }
429   }
430 }
431
432 void Program::SetUniform4i(GLint location, GLint value0, GLint value1, GLint value2, GLint value3)
433 {
434   DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
435
436   if(UNIFORM_UNKNOWN == location)
437   {
438     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
439     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
440     // specified uniform variable will not be changed.following opengl silently do nothing
441     return;
442   }
443
444   // Not caching these as based on current analysis this is not called that often by our shaders
445   LOG_GL("Uniform4i(%d,%d,%d,%d,%d)\n", location, value0, value1, value2, value3);
446   CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform4i(location, value0, value1, value2, value3));
447 }
448
449 void Program::SetUniform1f(GLint location, GLfloat value0)
450 {
451   DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
452
453   if(UNIFORM_UNKNOWN == location)
454   {
455     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
456     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
457     // specified uniform variable will not be changed.following opengl silently do nothing
458     return;
459   }
460
461   // check if uniform location fits the cache
462   if(location >= MAX_UNIFORM_CACHE_SIZE)
463   {
464     // not cached, make the gl call
465     LOG_GL("Uniform1f(%d,%f)\n", location, value0);
466     CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform1f(location, value0));
467   }
468   else
469   {
470     // check if the same value has already been set, reset if it is different
471     if((fabsf(value0 - mUniformCacheFloat[location]) >= Math::MACHINE_EPSILON_1))
472     {
473       // make the gl call
474       LOG_GL("Uniform1f(%d,%f)\n", location, value0);
475       CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform1f(location, value0));
476
477       // update cache
478       mUniformCacheFloat[location] = value0;
479     }
480   }
481 }
482
483 void Program::SetUniform2f(GLint location, GLfloat value0, GLfloat value1)
484 {
485   DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
486
487   if(UNIFORM_UNKNOWN == location)
488   {
489     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
490     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
491     // specified uniform variable will not be changed.following opengl silently do nothing
492     return;
493   }
494
495   // check if uniform location fits the cache
496   if(location >= MAX_UNIFORM_CACHE_SIZE)
497   {
498     // not cached, make the gl call
499     LOG_GL("Uniform2f(%d,%f,%f)\n", location, value0, value1);
500     CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform2f(location, value0, value1));
501   }
502   else
503   {
504     // check if the same value has already been set, reset if it is different
505     if((fabsf(value0 - mUniformCacheFloat2[location][0]) >= Math::MACHINE_EPSILON_1) ||
506        (fabsf(value1 - mUniformCacheFloat2[location][1]) >= Math::MACHINE_EPSILON_1))
507     {
508       // make the gl call
509       LOG_GL("Uniform2f(%d,%f,%f)\n", location, value0, value1);
510       CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform2f(location, value0, value1));
511
512       // update cache
513       mUniformCacheFloat2[location][0] = value0;
514       mUniformCacheFloat2[location][1] = value1;
515     }
516   }
517 }
518
519 void Program::SetSizeUniform3f(GLint location, GLfloat value0, GLfloat value1, GLfloat value2)
520 {
521   if((fabsf(value0 - mSizeUniformCache.x) >= Math::MACHINE_EPSILON_1) ||
522      (fabsf(value1 - mSizeUniformCache.y) >= Math::MACHINE_EPSILON_1) ||
523      (fabsf(value2 - mSizeUniformCache.z) >= Math::MACHINE_EPSILON_1))
524   {
525     mSizeUniformCache.x = value0;
526     mSizeUniformCache.y = value1;
527     mSizeUniformCache.z = value2;
528     SetUniform3f(location, value0, value1, value2);
529   }
530 }
531
532 void Program::SetUniform3f(GLint location, GLfloat value0, GLfloat value1, GLfloat value2)
533 {
534   DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
535
536   if(UNIFORM_UNKNOWN == location)
537   {
538     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
539     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
540     // specified uniform variable will not be changed.following opengl silently do nothing
541     return;
542   }
543
544   // Not caching these as based on current analysis this is not called that often by our shaders
545   LOG_GL("Uniform3f(%d,%f,%f,%f)\n", location, value0, value1, value2);
546   CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform3f(location, value0, value1, value2));
547 }
548
549 void Program::SetUniform4f(GLint location, GLfloat value0, GLfloat value1, GLfloat value2, GLfloat value3)
550 {
551   DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
552
553   if(UNIFORM_UNKNOWN == location)
554   {
555     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
556     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
557     // specified uniform variable will not be changed.following opengl silently do nothing
558     return;
559   }
560
561   // check if uniform location fits the cache
562   if(location >= MAX_UNIFORM_CACHE_SIZE)
563   {
564     // not cached, make the gl call
565     LOG_GL("Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3);
566     CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform4f(location, value0, value1, value2, value3));
567   }
568   else
569   {
570     // check if the same value has already been set, reset if any component is different
571     // checking index 3 first because we're often animating alpha (rgba)
572     if((fabsf(value3 - mUniformCacheFloat4[location][3]) >= Math::MACHINE_EPSILON_1) ||
573        (fabsf(value0 - mUniformCacheFloat4[location][0]) >= Math::MACHINE_EPSILON_1) ||
574        (fabsf(value1 - mUniformCacheFloat4[location][1]) >= Math::MACHINE_EPSILON_1) ||
575        (fabsf(value2 - mUniformCacheFloat4[location][2]) >= Math::MACHINE_EPSILON_1))
576     {
577       // make the gl call
578       LOG_GL("Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3);
579       CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform4f(location, value0, value1, value2, value3));
580       // update cache
581       mUniformCacheFloat4[location][0] = value0;
582       mUniformCacheFloat4[location][1] = value1;
583       mUniformCacheFloat4[location][2] = value2;
584       mUniformCacheFloat4[location][3] = value3;
585     }
586   }
587 }
588
589 void Program::SetUniformMatrix4fv(GLint location, GLsizei count, const GLfloat* value)
590 {
591   DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
592
593   if(UNIFORM_UNKNOWN == location)
594   {
595     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
596     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
597     // specified uniform variable will not be changed.following opengl silently do nothing
598     return;
599   }
600
601   // Not caching these calls. Based on current analysis this is called very often
602   // but with different values (we're using this for MVP matrices)
603   // NOTE! we never want driver or GPU to transpose
604   LOG_GL("UniformMatrix4fv(%d,%d,GL_FALSE,%x)\n", location, count, value);
605   CHECK_GL(mGlAbstraction, mGlAbstraction.UniformMatrix4fv(location, count, GL_FALSE, value));
606 }
607
608 void Program::SetUniformMatrix3fv(GLint location, GLsizei count, const GLfloat* value)
609 {
610   DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
611
612   if(UNIFORM_UNKNOWN == location)
613   {
614     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
615     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
616     // specified uniform variable will not be changed.following opengl silently do nothing
617     return;
618   }
619
620   // Not caching these calls. Based on current analysis this is called very often
621   // but with different values (we're using this for MVP matrices)
622   // NOTE! we never want driver or GPU to transpose
623   LOG_GL("UniformMatrix3fv(%d,%d,GL_FALSE,%x)\n", location, count, value);
624   CHECK_GL(mGlAbstraction, mGlAbstraction.UniformMatrix3fv(location, count, GL_FALSE, value));
625 }
626
627 void Program::GlContextCreated()
628 {
629 }
630
631 void Program::GlContextDestroyed()
632 {
633   ResetAttribsUniformCache();
634 }
635
636 bool Program::ModifiesGeometry()
637 {
638   return mModifiesGeometry;
639 }
640
641 Program::Program(ProgramCache& cache, Internal::ShaderDataPtr shaderData, Graphics::Controller& controller, Graphics::UniquePtr<Graphics::Program>&& gfxProgram, bool modifiesGeometry)
642 : mCache(cache),
643   mGlAbstraction(mCache.GetGlAbstraction()),
644   mProjectionMatrix(nullptr),
645   mViewMatrix(nullptr),
646   mProgramId(0),
647   mGfxProgram(std::move(gfxProgram)),
648   mGfxController(controller),
649   mProgramData(shaderData),
650   mModifiesGeometry(modifiesGeometry)
651 {
652   // reserve space for standard attributes
653   mAttributeLocations.reserve(ATTRIB_TYPE_LAST);
654   for(uint32_t i = 0; i < ATTRIB_TYPE_LAST; ++i)
655   {
656     RegisterCustomAttribute(ConstString(gStdAttribs[i]));
657   }
658
659   // reserve space for standard uniforms
660   mUniformLocations.reserve(UNIFORM_TYPE_LAST);
661   // reset built in uniform names in cache
662   for(uint32_t i = 0; i < UNIFORM_TYPE_LAST; ++i)
663   {
664     RegisterUniform(ConstString(gStdUniforms[i]));
665   }
666
667   // reset values
668   ResetAttribsUniformCache();
669
670   // Get program id and use it as hash for the cache
671   // in order to maintain current functionality as long as needed
672   mGfxController.GetProgramParameter(*mGfxProgram, 1, &mProgramId);
673
674   BuildReflection(controller.GetProgramReflection(*mGfxProgram.get()));
675 }
676
677 Program::~Program()
678 {
679 }
680
681 void Program::ResetAttribsUniformCache()
682 {
683   // reset attribute locations
684   for(uint32_t i = 0; i < mAttributeLocations.size(); ++i)
685   {
686     mAttributeLocations[i].second = ATTRIB_UNKNOWN;
687   }
688
689   // reset all gl uniform locations
690   for(uint32_t i = 0; i < mUniformLocations.size(); ++i)
691   {
692     // reset gl program locations and names
693     mUniformLocations[i].second = UNIFORM_NOT_QUERIED;
694   }
695
696   mSamplerUniformLocations.clear();
697
698   // reset uniform caches
699   mSizeUniformCache.x = mSizeUniformCache.y = mSizeUniformCache.z = 0.f;
700
701   for(uint32_t i = 0; i < MAX_UNIFORM_CACHE_SIZE; ++i)
702   {
703     // GL initializes uniforms to 0
704     mUniformCacheInt[i]       = 0;
705     mUniformCacheFloat[i]     = 0.0f;
706     mUniformCacheFloat2[i][0] = 0.0f;
707     mUniformCacheFloat2[i][1] = 0.0f;
708     mUniformCacheFloat4[i][0] = 0.0f;
709     mUniformCacheFloat4[i][1] = 0.0f;
710     mUniformCacheFloat4[i][2] = 0.0f;
711     mUniformCacheFloat4[i][3] = 0.0f;
712   }
713 }
714
715 void Program::BuildReflection(const Graphics::Reflection& graphicsReflection)
716 {
717   mReflectionDefaultUniforms.clear();
718   mReflectionDefaultUniforms.resize(DEFAULT_UNIFORM_HASHTABLE.size());
719
720   auto uniformBlockCount = graphicsReflection.GetUniformBlockCount();
721
722   // add uniform block fields
723   for(auto i = 0u; i < uniformBlockCount; ++i)
724   {
725     Graphics::UniformBlockInfo uboInfo;
726     graphicsReflection.GetUniformBlock(i, uboInfo);
727
728     // for each member store data
729     for(const auto& item : uboInfo.members)
730     {
731       auto hashValue = CalculateHash(item.name);
732       mReflection.emplace_back(ReflectionUniformInfo{hashValue, false, item});
733
734       // update buffer index
735       mReflection.back().uniformInfo.bufferIndex = i;
736
737       // Update default uniforms
738       for(auto i = 0u; i < DEFAULT_UNIFORM_HASHTABLE.size(); ++i)
739       {
740         if(hashValue == DEFAULT_UNIFORM_HASHTABLE[i])
741         {
742           mReflectionDefaultUniforms[i] = mReflection.back();
743           break;
744         }
745       }
746     }
747   }
748
749   // add samplers
750   auto samplers = graphicsReflection.GetSamplers();
751   for(const auto& sampler : samplers)
752   {
753     mReflection.emplace_back(ReflectionUniformInfo{CalculateHash(sampler.name), false, sampler});
754   }
755
756   // check for potential collisions
757   std::map<size_t, bool> hashTest;
758   bool                   hasCollisions(false);
759   for(auto&& item : mReflection)
760   {
761     if(hashTest.find(item.hashValue) == hashTest.end())
762     {
763       hashTest[item.hashValue] = false;
764     }
765     else
766     {
767       hashTest[item.hashValue] = true;
768       hasCollisions            = true;
769     }
770   }
771
772   // update collision flag for further use
773   if(hasCollisions)
774   {
775     for(auto&& item : mReflection)
776     {
777       item.hasCollision = hashTest[item.hashValue];
778     }
779   }
780 }
781
782 bool Program::GetUniform(const std::string& name, size_t hashedName, Graphics::UniformInfo& out) const
783 {
784   if(mReflection.empty())
785   {
786     return false;
787   }
788
789   hashedName = !hashedName ? CalculateHash(name) : hashedName;
790
791   for(const ReflectionUniformInfo& item : mReflection)
792   {
793     if(item.hashValue == hashedName)
794     {
795       if(!item.hasCollision || item.uniformInfo.name == name)
796       {
797         out = item.uniformInfo;
798         return true;
799       }
800       else
801       {
802         return false;
803       }
804     }
805   }
806   return false;
807 }
808
809 bool Program::GetDefaultUniform(DefaultUniformIndex defaultUniformIndex, Graphics::UniformInfo& out) const
810 {
811   if(mReflectionDefaultUniforms.empty())
812   {
813     return false;
814   }
815
816   auto& value = mReflectionDefaultUniforms[static_cast<uint32_t>(defaultUniformIndex)];
817   out         = value.uniformInfo;
818   return true;
819 }
820
821 const Graphics::UniformInfo* Program::GetDefaultUniform(DefaultUniformIndex defaultUniformIndex) const
822 {
823   if(mReflectionDefaultUniforms.empty())
824   {
825     return nullptr;
826   }
827
828   const auto value = &mReflectionDefaultUniforms[static_cast<uint32_t>(defaultUniformIndex)];
829   return &value->uniformInfo;
830 }
831
832 } // namespace Internal
833
834 } // namespace Dali