[dali_1.0.1] Merge branch 'tizen'
[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 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/gl-resources/context.h>
20
21 // EXTERNAL INCLUDES
22 #include <algorithm>
23 #include <limits>
24
25 // INTERNAL INCLUDES
26 #include <dali/public-api/common/constants.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
119 void Context::GlContextCreated()
120 {
121   DALI_ASSERT_DEBUG(!mGlContextCreated);
122
123   mGlContextCreated = true;
124
125   // Set the initial GL state, and check it.
126   ResetGlState();
127
128   const ProgramContainer::iterator endp = mProgramCache.end();
129   for ( ProgramContainer::iterator itp = mProgramCache.begin(); itp != endp; ++itp )
130   {
131     (*itp).second->GlContextCreated();
132   }
133 }
134
135 void Context::GlContextDestroyed()
136 {
137   const ProgramContainer::iterator endp = mProgramCache.end();
138   for ( ProgramContainer::iterator itp = mProgramCache.begin(); itp != endp; ++itp )
139   {
140     (*itp).second->GlContextDestroyed();
141   }
142
143   mGlContextCreated = false;
144 }
145
146 const char* Context::ErrorToString( GLenum errorCode )
147 {
148   for( unsigned int i = 0; i < sizeof(errors) / sizeof(errors[0]); ++i)
149   {
150     if (errorCode == errors[i].errorCode)
151     {
152       return errors[i].errorString;
153     }
154   }
155   return "Unknown Open GLES error";
156 }
157
158 void Context::ResetProgramMatrices()
159 {
160   const ProgramContainer::iterator endp = mProgramCache.end();
161   for ( ProgramContainer::iterator itp = mProgramCache.begin(); itp != endp; ++itp )
162   {
163     (*itp).second->SetProjectionMatrix( NULL );
164     (*itp).second->SetViewMatrix( NULL );
165   }
166 }
167
168 Program* Context::GetCachedProgram( std::size_t hash ) const
169 {
170   std::map< std::size_t, Program* >::const_iterator iter = mProgramCache.find(hash);
171
172   if (iter != mProgramCache.end())
173   {
174      return iter->second;
175   }
176   return NULL;
177 }
178
179 void Context::CacheProgram( std::size_t hash, Program* pointer )
180 {
181   mProgramCache[ hash ] = pointer;
182 }
183
184 const Rect< int >& Context::GetViewport()
185 {
186   return mViewPort;
187 }
188
189 void Context::FlushVertexAttributeLocations()
190 {
191   for( unsigned int i = 0; i < MAX_ATTRIBUTE_CACHE_SIZE; ++i )
192   {
193     // see if our cached state is different to the actual state
194     if (mVertexAttributeCurrentState[ i ] != mVertexAttributeCachedState[ i ] )
195     {
196       // it's different so make the change to the driver
197       // and update the cached state
198       mVertexAttributeCurrentState[ i ] = mVertexAttributeCachedState[ i ];
199
200       if (mVertexAttributeCurrentState[ i ] )
201       {
202         LOG_GL("EnableVertexAttribArray %d\n", i);
203         CHECK_GL( *this, mGlAbstraction.EnableVertexAttribArray( i ) );
204       }
205       else
206       {
207         LOG_GL("DisableVertexAttribArray %d\n", i);
208         CHECK_GL( *this, mGlAbstraction.DisableVertexAttribArray( i ) );
209       }
210     }
211   }
212
213 }
214
215 void Context::SetVertexAttributeLocation(unsigned int location, bool state)
216 {
217
218   if( location >= MAX_ATTRIBUTE_CACHE_SIZE )
219   {
220     // not cached, make the gl call through context
221     if ( state )
222     {
223        LOG_GL("EnableVertexAttribArray %d\n", location);
224        CHECK_GL( *this, mGlAbstraction.EnableVertexAttribArray( location ) );
225     }
226     else
227     {
228       LOG_GL("DisableVertexAttribArray %d\n", location);
229       CHECK_GL( *this, mGlAbstraction.DisableVertexAttribArray( location ) );
230     }
231   }
232   else
233   {
234     // set the cached state, it will be set at the next draw call
235     // if it's different from the current driver state
236     mVertexAttributeCachedState[ location ] = state;
237   }
238 }
239
240 void Context::ResetVertexAttributeState()
241 {
242   // reset attribute cache
243   for( unsigned int i=0; i < MAX_ATTRIBUTE_CACHE_SIZE; ++i )
244   {
245     mVertexAttributeCachedState[ i ] = false;
246     mVertexAttributeCurrentState[ i ] = false;
247
248     LOG_GL("DisableVertexAttribArray %d\n", i);
249     CHECK_GL( *this, mGlAbstraction.DisableVertexAttribArray( i ) );
250   }
251 }
252
253 void Context::ResetGlState()
254 {
255   DALI_ASSERT_DEBUG(mGlContextCreated);
256
257   mClearColorSet = false;
258   // Render manager will call clear in next render
259
260   // Reset internal state and Synchronize it with real OpenGL context.
261   // This may seem like overkill, but the GL context is not owned by dali-core,
262   // and no assumptions should be made about the initial state.
263   mColorMask = true;
264   mGlAbstraction.ColorMask( true, true, true, true );
265
266   mStencilMask = 0xFF;
267   mGlAbstraction.StencilMask( 0xFF );
268
269   mBlendEnabled = false;
270   mGlAbstraction.Disable(GL_BLEND);
271
272   mDepthTestEnabled = false;
273   mGlAbstraction.Disable(GL_DEPTH_TEST);
274
275   mDepthMaskEnabled = false;
276   mGlAbstraction.DepthMask(GL_FALSE);
277
278   mDitherEnabled = false; // This the only GL capability which defaults to true
279   mGlAbstraction.Disable(GL_DITHER);
280
281   mPolygonOffsetFillEnabled = false;
282   mGlAbstraction.Disable(GL_POLYGON_OFFSET_FILL);
283
284   mSampleAlphaToCoverageEnabled = false;
285   mGlAbstraction.Disable(GL_SAMPLE_ALPHA_TO_COVERAGE);
286
287   mSampleCoverageEnabled = false;
288   mGlAbstraction.Disable(GL_SAMPLE_COVERAGE);
289
290   mScissorTestEnabled = false;
291   mGlAbstraction.Disable(GL_SCISSOR_TEST);
292
293   mStencilTestEnabled = false;
294   mGlAbstraction.Disable(GL_STENCIL_TEST);
295
296   mBoundArrayBufferId = 0;
297   LOG_GL("BindBuffer GL_ARRAY_BUFFER 0\n");
298   mGlAbstraction.BindBuffer(GL_ARRAY_BUFFER, mBoundArrayBufferId);
299
300   mBoundElementArrayBufferId = 0;
301   LOG_GL("BindBuffer GL_ELEMENT_ARRAY_BUFFER 0\n");
302   mGlAbstraction.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, mBoundElementArrayBufferId);
303
304 #ifndef EMSCRIPTEN // not in WebGL
305   mBoundTransformFeedbackBufferId = 0;
306   LOG_GL("BindBuffer GL_TRANSFORM_FEEDBACK_BUFFER 0\n");
307   mGlAbstraction.BindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, mBoundTransformFeedbackBufferId);
308 #endif
309
310   mActiveTextureUnit = UNINITIALIZED_TEXTURE_UNIT;
311
312   mUsingDefaultBlendColor = true;
313   mGlAbstraction.BlendColor( 0.0f, 0.0f, 0.0f, 0.0f );
314
315   mBlendFuncSeparateSrcRGB = GL_ONE;
316   mBlendFuncSeparateDstRGB = GL_ZERO;
317   mBlendFuncSeparateSrcAlpha = GL_ONE;
318   mBlendFuncSeparateDstAlpha = GL_ZERO;
319   mGlAbstraction.BlendFuncSeparate( mBlendFuncSeparateSrcRGB, mBlendFuncSeparateDstRGB,
320                                     mBlendFuncSeparateSrcAlpha, mBlendFuncSeparateDstAlpha );
321
322   // initial state is GL_FUNC_ADD for both RGB and Alpha blend modes
323   mBlendEquationSeparateModeRGB = GL_FUNC_ADD;
324   mBlendEquationSeparateModeAlpha = GL_FUNC_ADD;
325   mGlAbstraction.BlendEquationSeparate( mBlendEquationSeparateModeRGB, mBlendEquationSeparateModeAlpha);
326
327   mCullFaceMode = CullNone;
328   mGlAbstraction.Disable(GL_CULL_FACE);
329   mGlAbstraction.FrontFace(GL_CCW);
330   mGlAbstraction.CullFace(GL_BACK);
331
332   // get max texture units
333   mGlAbstraction.GetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &mMaxTextureUnits);
334   DALI_ASSERT_DEBUG(mMaxTextureUnits > 7);  // according to GLES 2.0 specification
335   mBound2dTextureId.reserve(mMaxTextureUnits);
336   // rebind texture units
337   for( int i=0; i < mMaxTextureUnits; ++i )
338   {
339     mBound2dTextureId[ i ] = 0;
340     // set active texture
341     mGlAbstraction.ActiveTexture( GL_TEXTURE0 + i );
342     // bind the previous texture
343     mGlAbstraction.BindTexture(GL_TEXTURE_2D, mBound2dTextureId[ i ] );
344   }
345
346   // get maximum texture size
347   mGlAbstraction.GetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
348
349   GLint numProgramBinaryFormats;
350   mGlAbstraction.GetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS_OES, &numProgramBinaryFormats);
351   if( GL_NO_ERROR == mGlAbstraction.GetError() && 0 != numProgramBinaryFormats )
352   {
353     mProgramBinaryFormats.resize(numProgramBinaryFormats);
354     mGlAbstraction.GetIntegerv(GL_PROGRAM_BINARY_FORMATS_OES, &mProgramBinaryFormats[0]);
355   }
356
357   // reset viewport, this will be set to something useful when rendering
358   mViewPort.x = mViewPort.y = mViewPort.width = mViewPort.height = 0;
359
360   ResetVertexAttributeState();
361 }
362
363 #ifdef DALI_CONTEXT_LOGGING
364
365 void Context::PrintCurrentState()
366 {
367   DALI_LOG_INFO(SceneGraph::Context::gGlLogFilter, Debug::General,
368                 "----------------- Context State BEGIN -----------------\n"
369                 "Blend = %s\n"
370                 "Cull Face = %s\n"
371                 "Depth Test = %s\n"
372                 "Depth Mask = %s\n"
373                 "Dither = %s\n"
374                 "Polygon Offset Fill = %s\n"
375                 "Sample Alpha To Coverage = %s\n"
376                 "Sample Coverage = %s\n"
377                 "Scissor Test = %s\n"
378                 "Stencil Test = %s\n"
379                 "----------------- Context State END -----------------\n",
380                 mBlendEnabled ? "Enabled" : "Disabled",
381                 mDepthTestEnabled ? "Enabled" : "Disabled",
382                 mDepthMaskEnabled ? "Enabled" : "Disabled",
383                 mDitherEnabled ? "Enabled" : "Disabled",
384                 mPolygonOffsetFillEnabled ? "Enabled" : "Disabled",
385                 mSampleAlphaToCoverageEnabled ? "Enabled" : "Disabled",
386                 mSampleCoverageEnabled ? "Enabled" : "Disabled",
387                 mScissorTestEnabled ? "Enabled" : "Disabled",
388                 mStencilTestEnabled ? "Enabled" : "Disabled");
389 }
390
391 #endif // DALI_CONTEXT_LOGGING
392
393 } // namespace Internal
394
395 } // namespace Dali