[SRUK] Initial copy from Tizen 2.2 version
[platform/core/uifw/dali-core.git] / dali / internal / render / gl-resources / context.cpp
1 //
2 // Copyright (c) 2014 Samsung Electronics Co., Ltd.
3 //
4 // Licensed under the Flora License, Version 1.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://floralicense.org/license/
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 // CLASS HEADER
18 #include <dali/internal/render/gl-resources/context.h>
19
20 // EXTERNAL INCLUDES
21 #include <algorithm>
22 #include <limits>
23
24 // INTERNAL INCLUDES
25 #include <dali/public-api/common/constants.h>
26 #include <dali/internal/render/gl-resources/context-observer.h>
27 #include <dali/internal/render/shaders/program.h>
28 #include <dali/integration-api/platform-abstraction.h>
29 #include <dali/internal/render/common/render-manager.h>
30 #include <dali/integration-api/debug.h>
31
32 using namespace std;
33
34 namespace Dali
35 {
36
37 namespace Internal
38 {
39
40 namespace // unnamed namespace
41 {
42
43 /**
44  * GL error strings
45  */
46 struct errorStrings
47 {
48   const GLenum errorCode;
49   const char* errorString;
50 };
51 errorStrings errors[] =
52 {
53    { GL_NO_ERROR,           "GL_NO_ERROR" },
54    { GL_INVALID_ENUM,       "GL_INVALID_ENUM" },
55    { GL_INVALID_VALUE,      "GL_INVALID_VALUE" },
56    { GL_INVALID_OPERATION,  "GL_INVALID_OPERATION" },
57    { GL_OUT_OF_MEMORY,      "GL_OUT_OF_MEMORY" }
58 };
59
60 /*
61  * Called by std::for_each from ~Context
62  */
63 void deletePrograms(std::pair< std::size_t, Program* > hashProgram)
64 {
65   DALI_ASSERT_DEBUG( hashProgram.second );
66   delete hashProgram.second;
67 }
68
69 const unsigned int UNINITIALIZED_TEXTURE_UNIT = std::numeric_limits<unsigned int>::max();// GL_MAX_TEXTURE_UNITS can't be used because it's depreciated in gles2
70
71 } // unnamed namespace
72
73 #ifdef DEBUG_ENABLED
74 Debug::Filter* Context::gGlLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_CONTEXT");
75 #endif
76
77 Context::Context(Integration::GlAbstraction& glAbstraction)
78 : mGlAbstraction(glAbstraction),
79   mGlContextCreated(false),
80   mColorMask(true),
81   mStencilMask(0xFF),
82   mBlendEnabled(false),
83   mDepthTestEnabled(false),
84   mDepthMaskEnabled(false),
85   mDitherEnabled(true), // This the only GL capability which defaults to true
86   mPolygonOffsetFillEnabled(false),
87   mSampleAlphaToCoverageEnabled(false),
88   mSampleCoverageEnabled(false),
89   mScissorTestEnabled(false),
90   mStencilTestEnabled(false),
91   mClearColorSet(false),
92   mBoundArrayBufferId(0),
93   mBoundElementArrayBufferId(0),
94   mBoundTransformFeedbackBufferId(0),
95   mActiveTextureUnit( UNINITIALIZED_TEXTURE_UNIT ),
96   mUsingDefaultBlendColor(true),
97   mBlendFuncSeparateSrcRGB(GL_ONE),
98   mBlendFuncSeparateDstRGB(GL_ZERO),
99   mBlendFuncSeparateSrcAlpha(GL_ONE),
100   mBlendFuncSeparateDstAlpha(GL_ZERO),
101   mBlendEquationSeparateModeRGB( GL_FUNC_ADD ),
102   mBlendEquationSeparateModeAlpha( GL_FUNC_ADD ),
103   mMaxTextureSize(0),
104   mMaxTextureUnits(0),
105   mClearColor(Color::WHITE),    // initial color, never used until it's been set by the user
106   mCullFaceMode(CullNone),
107   mViewPort( 0, 0, 0, 0 ),
108   mCurrentProgram( NULL )
109 {
110 }
111
112 Context::~Context()
113 {
114   // release the cached programs
115   std::for_each(mProgramCache.begin(), mProgramCache.end(), deletePrograms);
116   mProgramCache.clear();
117
118   DALI_ASSERT_DEBUG(mObservers.empty());
119 }
120
121 void Context::GlContextCreated()
122 {
123   DALI_ASSERT_DEBUG(!mGlContextCreated);
124
125   mGlContextCreated = true;
126
127   // Set the initial GL state, and check it.
128   ResetGlState();
129
130   const std::set<ContextObserver*>::iterator end = mObservers.end();
131   for ( std::set<ContextObserver*>::iterator it = mObservers.begin();
132       it != end; ++it )
133   {
134     (*it)->GlContextCreated();
135   }
136 }
137
138 void Context::GlContextToBeDestroyed()
139 {
140   DALI_ASSERT_DEBUG(mGlContextCreated);
141
142   const std::set<ContextObserver*>::iterator end = mObservers.end();
143   for ( std::set<ContextObserver*>::iterator it = mObservers.begin();
144       it != end; ++it )
145   {
146     (*it)->GlContextToBeDestroyed();
147   }
148
149   mGlContextCreated = false;
150 }
151
152 void Context::AddObserver(ContextObserver& observer)
153 {
154   mObservers.insert(&observer);
155 }
156
157 void Context::RemoveObserver(ContextObserver& observer)
158 {
159   mObservers.erase(&observer);
160 }
161
162 const char* Context::ErrorToString( GLenum errorCode )
163 {
164   for( unsigned int i = 0; i < sizeof(errors) / sizeof(errors[0]); ++i)
165   {
166     if (errorCode == errors[i].errorCode)
167     {
168       return errors[i].errorString;
169     }
170   }
171   return "Unknown Open GLES error";
172 }
173
174 Program* Context::GetCachedProgram( std::size_t hash ) const
175 {
176   std::map< std::size_t, Program* >::const_iterator iter = mProgramCache.find(hash);
177
178   if (iter != mProgramCache.end())
179   {
180      return iter->second;
181   }
182   return NULL;
183 }
184
185 void Context::CacheProgram( std::size_t hash, Program* pointer )
186 {
187   mProgramCache[ hash ] = pointer;
188 }
189
190 const Rect< int >& Context::GetViewport()
191 {
192   return mViewPort;
193 }
194
195 void Context::FlushVertexAttributeLocations()
196 {
197   for( unsigned int i = 0; i < MAX_ATTRIBUTE_CACHE_SIZE; ++i )
198   {
199     // see if our cached state is different to the actual state
200     if (mVertexAttributeCurrentState[ i ] != mVertexAttributeCachedState[ i ] )
201     {
202       // it's different so make the change to the driver
203       // and update the cached state
204       mVertexAttributeCurrentState[ i ] = mVertexAttributeCachedState[ i ];
205
206       if (mVertexAttributeCurrentState[ i ] )
207       {
208         LOG_GL("EnableVertexAttribArray %d\n", i);
209         CHECK_GL( *this, mGlAbstraction.EnableVertexAttribArray( i ) );
210       }
211       else
212       {
213         LOG_GL("DisableVertexAttribArray %d\n", i);
214         CHECK_GL( *this, mGlAbstraction.DisableVertexAttribArray( i ) );
215       }
216     }
217   }
218
219 }
220
221 void Context::SetVertexAttributeLocation(unsigned int location, bool state)
222 {
223
224   if( location >= MAX_ATTRIBUTE_CACHE_SIZE )
225   {
226     // not cached, make the gl call through context
227     if ( state )
228     {
229        LOG_GL("EnableVertexAttribArray %d\n", location);
230        CHECK_GL( *this, mGlAbstraction.EnableVertexAttribArray( location ) );
231     }
232     else
233     {
234       LOG_GL("DisableVertexAttribArray %d\n", location);
235       CHECK_GL( *this, mGlAbstraction.DisableVertexAttribArray( location ) );
236     }
237   }
238   else
239   {
240     // set the cached state, it will be set at the next draw call
241     // if it's different from the current driver state
242     mVertexAttributeCachedState[ location ] = state;
243   }
244 }
245
246 void Context::ResetVertexAttributeState()
247 {
248   // reset attribute cache
249   for( unsigned int i=0; i < MAX_ATTRIBUTE_CACHE_SIZE; ++i )
250   {
251     mVertexAttributeCachedState[ i ] = false;
252     mVertexAttributeCurrentState[ i ] = false;
253
254     LOG_GL("DisableVertexAttribArray %d\n", i);
255     CHECK_GL( *this, mGlAbstraction.DisableVertexAttribArray( i ) );
256   }
257 }
258
259 void Context::ResetGlState()
260 {
261   DALI_ASSERT_DEBUG(mGlContextCreated);
262
263   mClearColorSet = false;
264   // Render manager will call clear in next render
265
266   // Reset internal state and Synchronize it with real OpenGL context.
267   // This may seem like overkill, but the GL context is not owned by dali-core,
268   // and no assumptions should be made about the initial state.
269   mColorMask = true;
270   mGlAbstraction.ColorMask( true, true, true, true );
271
272   mStencilMask = 0xFF;
273   mGlAbstraction.StencilMask( 0xFF );
274
275   mBlendEnabled = false;
276   mGlAbstraction.Disable(GL_BLEND);
277
278   mDepthTestEnabled = false;
279   mGlAbstraction.Disable(GL_DEPTH_TEST);
280
281   mDepthMaskEnabled = false;
282   mGlAbstraction.DepthMask(GL_FALSE);
283
284   mDitherEnabled = false; // This the only GL capability which defaults to true
285   mGlAbstraction.Disable(GL_DITHER);
286
287   mPolygonOffsetFillEnabled = false;
288   mGlAbstraction.Disable(GL_POLYGON_OFFSET_FILL);
289
290   mSampleAlphaToCoverageEnabled = false;
291   mGlAbstraction.Disable(GL_SAMPLE_ALPHA_TO_COVERAGE);
292
293   mSampleCoverageEnabled = false;
294   mGlAbstraction.Disable(GL_SAMPLE_COVERAGE);
295
296   mScissorTestEnabled = false;
297   mGlAbstraction.Disable(GL_SCISSOR_TEST);
298
299   mStencilTestEnabled = false;
300   mGlAbstraction.Disable(GL_STENCIL_TEST);
301
302   mBoundArrayBufferId = 0;
303   LOG_GL("BindBuffer GL_ARRAY_BUFFER 0\n");
304   mGlAbstraction.BindBuffer(GL_ARRAY_BUFFER, mBoundArrayBufferId);
305
306   mBoundElementArrayBufferId = 0;
307   LOG_GL("BindBuffer GL_ELEMENT_ARRAY_BUFFER 0\n");
308   mGlAbstraction.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, mBoundElementArrayBufferId);
309
310   mBoundTransformFeedbackBufferId = 0;
311   LOG_GL("BindBuffer GL_TRANSFORM_FEEDBACK_BUFFER 0\n");
312   mGlAbstraction.BindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, mBoundTransformFeedbackBufferId);
313
314   mActiveTextureUnit = UNINITIALIZED_TEXTURE_UNIT;
315
316   mUsingDefaultBlendColor = true;
317   mGlAbstraction.BlendColor( 0.0f, 0.0f, 0.0f, 0.0f );
318
319   mBlendFuncSeparateSrcRGB = GL_ONE;
320   mBlendFuncSeparateDstRGB = GL_ZERO;
321   mBlendFuncSeparateSrcAlpha = GL_ONE;
322   mBlendFuncSeparateDstAlpha = GL_ZERO;
323   mGlAbstraction.BlendFuncSeparate( mBlendFuncSeparateSrcRGB, mBlendFuncSeparateDstRGB,
324                                     mBlendFuncSeparateSrcAlpha, mBlendFuncSeparateDstAlpha );
325
326   // initial state is GL_FUNC_ADD for both RGB and Alpha blend modes
327   mBlendEquationSeparateModeRGB = GL_FUNC_ADD;
328   mBlendEquationSeparateModeAlpha = GL_FUNC_ADD;
329   mGlAbstraction.BlendEquationSeparate( mBlendEquationSeparateModeRGB, mBlendEquationSeparateModeAlpha);
330
331   mCullFaceMode = CullNone;
332   mGlAbstraction.Disable(GL_CULL_FACE);
333   mGlAbstraction.FrontFace(GL_CCW);
334   mGlAbstraction.CullFace(GL_BACK);
335
336   // get max texture units
337   mGlAbstraction.GetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &mMaxTextureUnits);
338   DALI_ASSERT_DEBUG(mMaxTextureUnits > 7);  // according to GLES 2.0 specification
339   mBound2dTextureId.reserve(mMaxTextureUnits);
340   // rebind texture units
341   for( int i=0; i < mMaxTextureUnits; ++i )
342   {
343     mBound2dTextureId[ i ] = 0;
344     // set active texture
345     mGlAbstraction.ActiveTexture( GL_TEXTURE0 + i );
346     // bind the previous texture
347     mGlAbstraction.BindTexture(GL_TEXTURE_2D, mBound2dTextureId[ i ] );
348   }
349
350   // get maximum texture size
351   mGlAbstraction.GetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
352
353   GLint numProgramBinaryFormats;
354   mGlAbstraction.GetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS_OES, &numProgramBinaryFormats);
355   if( GL_NO_ERROR == mGlAbstraction.GetError() && 0 != numProgramBinaryFormats )
356   {
357     mProgramBinaryFormats.resize(numProgramBinaryFormats);
358     mGlAbstraction.GetIntegerv(GL_PROGRAM_BINARY_FORMATS_OES, &mProgramBinaryFormats[0]);
359   }
360
361   // reset viewport, this will be set to something useful when rendering
362   mViewPort.x = mViewPort.y = mViewPort.width = mViewPort.height = 0;
363
364   ResetVertexAttributeState();
365 }
366
367 #ifdef DALI_CONTEXT_LOGGING
368
369 void Context::PrintCurrentState()
370 {
371   DALI_LOG_INFO(SceneGraph::Context::gGlLogFilter, Debug::General,
372                 "----------------- Context State BEGIN -----------------\n"
373                 "Blend = %s\n"
374                 "Cull Face = %s\n"
375                 "Depth Test = %s\n"
376                 "Depth Mask = %s\n"
377                 "Dither = %s\n"
378                 "Polygon Offset Fill = %s\n"
379                 "Sample Alpha To Coverage = %s\n"
380                 "Sample Coverage = %s\n"
381                 "Scissor Test = %s\n"
382                 "Stencil Test = %s\n"
383                 "----------------- Context State END -----------------\n",
384                 mBlendEnabled ? "Enabled" : "Disabled",
385                 mDepthTestEnabled ? "Enabled" : "Disabled",
386                 mDepthMaskEnabled ? "Enabled" : "Disabled",
387                 mDitherEnabled ? "Enabled" : "Disabled",
388                 mPolygonOffsetFillEnabled ? "Enabled" : "Disabled",
389                 mSampleAlphaToCoverageEnabled ? "Enabled" : "Disabled",
390                 mSampleCoverageEnabled ? "Enabled" : "Disabled",
391                 mScissorTestEnabled ? "Enabled" : "Disabled",
392                 mStencilTestEnabled ? "Enabled" : "Disabled");
393 }
394
395 #endif // DALI_CONTEXT_LOGGING
396
397 } // namespace Internal
398
399 } // namespace Dali