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