]> git.lizzy.rs Git - irrlicht.git/blob - source/Irrlicht/OpenGL/Driver.cpp
Use a buffer for quads indices
[irrlicht.git] / source / Irrlicht / OpenGL / Driver.cpp
1 // Copyright (C) 2023 Vitaliy Lobachevskiy
2 // Copyright (C) 2014 Patryk Nadrowski
3 // Copyright (C) 2009-2010 Amundis
4 // This file is part of the "Irrlicht Engine".
5 // For conditions of distribution and use, see copyright notice in Irrlicht.h
6
7 #include "Driver.h"
8 #include <cassert>
9 #include "CNullDriver.h"
10 #include "IContextManager.h"
11
12 #include "COpenGLCoreTexture.h"
13 #include "COpenGLCoreRenderTarget.h"
14 #include "COpenGLCoreCacheHandler.h"
15
16 #include "MaterialRenderer.h"
17 #include "FixedPipelineRenderer.h"
18 #include "Renderer2D.h"
19
20 #include "EVertexAttributes.h"
21 #include "CImage.h"
22 #include "os.h"
23
24 #ifdef _IRR_COMPILE_WITH_ANDROID_DEVICE_
25 #include "android_native_app_glue.h"
26 #endif
27
28 #include "mt_opengl.h"
29
30 namespace irr
31 {
32 namespace video
33 {
34         struct VertexAttribute {
35                 enum class Mode {
36                         Regular,
37                         Normalized,
38                         Integral,
39                 };
40                 int Index;
41                 int ComponentCount;
42                 GLenum ComponentType;
43                 Mode mode;
44                 int Offset;
45         };
46
47         struct VertexType {
48                 int VertexSize;
49                 int AttributeCount;
50                 VertexAttribute Attributes[];
51
52                 VertexType(const VertexType &) = delete;
53                 VertexType &operator= (const VertexType &) = delete;
54         };
55
56         static const VertexAttribute *begin(const VertexType &type)
57         {
58                 return type.Attributes;
59         }
60
61         static const VertexAttribute *end(const VertexType &type)
62         {
63                 return type.Attributes + type.AttributeCount;
64         }
65
66         static constexpr VertexType vtStandard = {
67                 sizeof(S3DVertex), 4, {
68                         {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)},
69                         {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Normal)},
70                         {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)},
71                         {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)},
72                 },
73         };
74
75 #pragma GCC diagnostic push
76 #pragma GCC diagnostic ignored "-Winvalid-offsetof"
77
78         static constexpr VertexType vt2TCoords = {
79                 sizeof(S3DVertex2TCoords), 5, {
80                         {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Pos)},
81                         {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Normal)},
82                         {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex2TCoords, Color)},
83                         {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords)},
84                         {EVA_TCOORD1, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords2)},
85                 },
86         };
87
88         static constexpr VertexType vtTangents = {
89                 sizeof(S3DVertexTangents), 6, {
90                         {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Pos)},
91                         {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Normal)},
92                         {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertexTangents, Color)},
93                         {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, TCoords)},
94                         {EVA_TANGENT, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Tangent)},
95                         {EVA_BINORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Binormal)},
96                 },
97         };
98
99 #pragma GCC diagnostic pop
100
101         static const VertexType &getVertexTypeDescription(E_VERTEX_TYPE type)
102         {
103                 switch (type) {
104                         case EVT_STANDARD: return vtStandard;
105                         case EVT_2TCOORDS: return vt2TCoords;
106                         case EVT_TANGENTS: return vtTangents;
107                         default: assert(false);
108                 }
109         }
110
111         static constexpr VertexType vt2DImage = {
112                 sizeof(S3DVertex), 3, {
113                         {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)},
114                         {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)},
115                         {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)},
116                 },
117         };
118
119         static constexpr VertexType vtPrimitive = {
120                 sizeof(S3DVertex), 2, {
121                         {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)},
122                         {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)},
123                 },
124         };
125
126
127 void APIENTRY COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam)
128 {
129         ((COpenGL3DriverBase *)userParam)->debugCb(source, type, id, severity, length, message);
130 }
131
132 void COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message)
133 {
134         printf("%04x %04x %x %x %.*s\n", source, type, id, severity, length, message);
135 }
136
137 COpenGL3DriverBase::COpenGL3DriverBase(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) :
138         CNullDriver(io, params.WindowSize), COpenGL3ExtensionHandler(), CacheHandler(0),
139         Params(params), ResetRenderStates(true), LockRenderStateMode(false), AntiAlias(params.AntiAlias),
140         MaterialRenderer2DActive(0), MaterialRenderer2DTexture(0), MaterialRenderer2DNoTexture(0),
141         CurrentRenderMode(ERM_NONE), Transformation3DChanged(true),
142         OGLES2ShaderPath(params.OGLES2ShaderPath),
143         ColorFormat(ECF_R8G8B8), ContextManager(contextManager)
144 {
145 #ifdef _DEBUG
146         setDebugName("Driver");
147 #endif
148
149         if (!ContextManager)
150                 return;
151
152         ContextManager->grab();
153         ContextManager->generateSurface();
154         ContextManager->generateContext();
155         ExposedData = ContextManager->getContext();
156         ContextManager->activateContext(ExposedData, false);
157         GL.LoadAllProcedures(ContextManager);
158         GL.DebugMessageCallback(debugCb, this);
159         initQuadsIndices();
160 }
161
162 COpenGL3DriverBase::~COpenGL3DriverBase()
163 {
164         deleteMaterialRenders();
165
166         CacheHandler->getTextureCache().clear();
167
168         removeAllRenderTargets();
169         deleteAllTextures();
170         removeAllOcclusionQueries();
171         removeAllHardwareBuffers();
172
173         delete MaterialRenderer2DTexture;
174         delete MaterialRenderer2DNoTexture;
175         delete CacheHandler;
176
177         if (ContextManager)
178         {
179                 ContextManager->destroyContext();
180                 ContextManager->destroySurface();
181                 ContextManager->terminate();
182                 ContextManager->drop();
183         }
184 }
185
186         void COpenGL3DriverBase::initQuadsIndices(int max_vertex_count)
187         {
188                 int max_quad_count = max_vertex_count / 4;
189                 std::vector<GLushort> QuadsIndices;
190                 QuadsIndices.reserve(6 * max_quad_count);
191                 for (int k = 0; k < max_quad_count; k++) {
192                         QuadsIndices.push_back(4 * k + 0);
193                         QuadsIndices.push_back(4 * k + 1);
194                         QuadsIndices.push_back(4 * k + 2);
195                         QuadsIndices.push_back(4 * k + 0);
196                         QuadsIndices.push_back(4 * k + 2);
197                         QuadsIndices.push_back(4 * k + 3);
198                 }
199                 glGenBuffers(1, &QuadIndexBuffer);
200                 glBindBuffer(GL_ARRAY_BUFFER, QuadIndexBuffer);
201                 glBufferData(GL_ARRAY_BUFFER, sizeof(QuadsIndices[0]) * QuadsIndices.size(), QuadsIndices.data(), GL_STATIC_DRAW);
202                 glBindBuffer(GL_ARRAY_BUFFER, 0);
203                 QuadIndexCount = QuadsIndices.size();
204         }
205
206         bool COpenGL3DriverBase::genericDriverInit(const core::dimension2d<u32>& screenSize, bool stencilBuffer)
207         {
208                 Name = glGetString(GL_VERSION);
209                 printVersion();
210
211                 // print renderer information
212                 VendorName = glGetString(GL_VENDOR);
213                 os::Printer::log(VendorName.c_str(), ELL_INFORMATION);
214
215                 // load extensions
216                 initExtensions();
217
218                 // reset cache handler
219                 delete CacheHandler;
220                 CacheHandler = new COpenGL3CacheHandler(this);
221
222                 StencilBuffer = stencilBuffer;
223
224                 DriverAttributes->setAttribute("MaxTextures", (s32)Feature.MaxTextureUnits);
225                 DriverAttributes->setAttribute("MaxSupportedTextures", (s32)Feature.MaxTextureUnits);
226 //              DriverAttributes->setAttribute("MaxLights", MaxLights);
227                 DriverAttributes->setAttribute("MaxAnisotropy", MaxAnisotropy);
228 //              DriverAttributes->setAttribute("MaxUserClipPlanes", MaxUserClipPlanes);
229 //              DriverAttributes->setAttribute("MaxAuxBuffers", MaxAuxBuffers);
230 //              DriverAttributes->setAttribute("MaxMultipleRenderTargets", MaxMultipleRenderTargets);
231                 DriverAttributes->setAttribute("MaxIndices", (s32)MaxIndices);
232                 DriverAttributes->setAttribute("MaxTextureSize", (s32)MaxTextureSize);
233                 DriverAttributes->setAttribute("MaxTextureLODBias", MaxTextureLODBias);
234                 DriverAttributes->setAttribute("Version", Version);
235                 DriverAttributes->setAttribute("AntiAlias", AntiAlias);
236
237                 glPixelStorei(GL_PACK_ALIGNMENT, 1);
238
239                 UserClipPlane.reallocate(0);
240
241                 for (s32 i = 0; i < ETS_COUNT; ++i)
242                         setTransform(static_cast<E_TRANSFORMATION_STATE>(i), core::IdentityMatrix);
243
244                 setAmbientLight(SColorf(0.0f, 0.0f, 0.0f, 0.0f));
245                 glClearDepthf(1.0f);
246
247                 glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
248                 glFrontFace(GL_CW);
249
250                 // create material renderers
251                 createMaterialRenderers();
252
253                 // set the renderstates
254                 setRenderStates3DMode();
255
256                 // set fog mode
257                 setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog);
258
259                 // create matrix for flipping textures
260                 TextureFlipMatrix.buildTextureTransform(0.0f, core::vector2df(0, 0), core::vector2df(0, 1.0f), core::vector2df(1.0f, -1.0f));
261
262                 // We need to reset once more at the beginning of the first rendering.
263                 // This fixes problems with intermediate changes to the material during texture load.
264                 ResetRenderStates = true;
265
266                 testGLError(__LINE__);
267
268                 return true;
269         }
270
271         void COpenGL3DriverBase::loadShaderData(const io::path& vertexShaderName, const io::path& fragmentShaderName, c8** vertexShaderData, c8** fragmentShaderData)
272         {
273                 io::path vsPath(OGLES2ShaderPath);
274                 vsPath += vertexShaderName;
275
276                 io::path fsPath(OGLES2ShaderPath);
277                 fsPath += fragmentShaderName;
278
279                 *vertexShaderData = 0;
280                 *fragmentShaderData = 0;
281
282                 io::IReadFile* vsFile = FileSystem->createAndOpenFile(vsPath);
283                 if ( !vsFile )
284                 {
285                         core::stringw warning(L"Warning: Missing shader files needed to simulate fixed function materials:\n");
286                         warning += core::stringw(vsPath) + L"\n";
287                         warning += L"Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath";
288                         os::Printer::log(warning.c_str(), ELL_WARNING);
289                         return;
290                 }
291
292                 io::IReadFile* fsFile = FileSystem->createAndOpenFile(fsPath);
293                 if ( !fsFile )
294                 {
295                         core::stringw warning(L"Warning: Missing shader files needed to simulate fixed function materials:\n");
296                         warning += core::stringw(fsPath) + L"\n";
297                         warning += L"Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath";
298                         os::Printer::log(warning.c_str(), ELL_WARNING);
299                         return;
300                 }
301
302                 long size = vsFile->getSize();
303                 if (size)
304                 {
305                         *vertexShaderData = new c8[size+1];
306                         vsFile->read(*vertexShaderData, size);
307                         (*vertexShaderData)[size] = 0;
308                 }
309
310                 size = fsFile->getSize();
311                 if (size)
312                 {
313                         // if both handles are the same we must reset the file
314                         if (fsFile == vsFile)
315                                 fsFile->seek(0);
316
317                         *fragmentShaderData = new c8[size+1];
318                         fsFile->read(*fragmentShaderData, size);
319                         (*fragmentShaderData)[size] = 0;
320                 }
321
322                 vsFile->drop();
323                 fsFile->drop();
324         }
325
326         void COpenGL3DriverBase::addDummyMaterial(E_MATERIAL_TYPE type) {
327                 auto index = addMaterialRenderer(getMaterialRenderer(EMT_SOLID), "DUMMY");
328                 assert(index == type);
329         }
330
331         void COpenGL3DriverBase::createMaterialRenderers()
332         {
333                 // Create callbacks.
334
335                 COpenGL3MaterialSolidCB* SolidCB = new COpenGL3MaterialSolidCB();
336                 COpenGL3MaterialSolidCB* TransparentAlphaChannelCB = new COpenGL3MaterialSolidCB();
337                 COpenGL3MaterialSolidCB* TransparentAlphaChannelRefCB = new COpenGL3MaterialSolidCB();
338                 COpenGL3MaterialSolidCB* TransparentVertexAlphaCB = new COpenGL3MaterialSolidCB();
339                 COpenGL3MaterialOneTextureBlendCB* OneTextureBlendCB = new COpenGL3MaterialOneTextureBlendCB();
340
341                 // Create built-in materials.
342                 // The addition order must be the same as in the E_MATERIAL_TYPE enumeration. Thus the
343                 // addDummyMaterial calls for materials no longer supported.
344
345                 const core::stringc VertexShader = OGLES2ShaderPath + "Solid.vsh";
346
347                 // EMT_SOLID
348                 core::stringc FragmentShader = OGLES2ShaderPath + "Solid.fsh";
349                 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
350                         EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, SolidCB, EMT_SOLID, 0);
351
352                 addDummyMaterial(EMT_SOLID_2_LAYER);
353                 addDummyMaterial(EMT_LIGHTMAP);
354                 addDummyMaterial(EMT_LIGHTMAP_ADD);
355                 addDummyMaterial(EMT_LIGHTMAP_M2);
356                 addDummyMaterial(EMT_LIGHTMAP_M4);
357                 addDummyMaterial(EMT_LIGHTMAP_LIGHTING);
358                 addDummyMaterial(EMT_LIGHTMAP_LIGHTING_M2);
359                 addDummyMaterial(EMT_LIGHTMAP_LIGHTING_M4);
360                 addDummyMaterial(EMT_DETAIL_MAP);
361                 addDummyMaterial(EMT_SPHERE_MAP);
362                 addDummyMaterial(EMT_REFLECTION_2_LAYER);
363                 addDummyMaterial(EMT_TRANSPARENT_ADD_COLOR);
364
365                 // EMT_TRANSPARENT_ALPHA_CHANNEL
366                 FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannel.fsh";
367                 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
368                         EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0);
369
370                 // EMT_TRANSPARENT_ALPHA_CHANNEL_REF
371                 FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannelRef.fsh";
372                 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
373                         EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelRefCB, EMT_SOLID, 0);
374
375                 // EMT_TRANSPARENT_VERTEX_ALPHA
376                 FragmentShader = OGLES2ShaderPath + "TransparentVertexAlpha.fsh";
377                 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
378                         EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentVertexAlphaCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0);
379
380                 addDummyMaterial(EMT_TRANSPARENT_REFLECTION_2_LAYER);
381
382                 // EMT_ONETEXTURE_BLEND
383                 FragmentShader = OGLES2ShaderPath + "OneTextureBlend.fsh";
384                 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
385                         EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, OneTextureBlendCB, EMT_ONETEXTURE_BLEND, 0);
386
387                 // Drop callbacks.
388
389                 SolidCB->drop();
390                 TransparentAlphaChannelCB->drop();
391                 TransparentAlphaChannelRefCB->drop();
392                 TransparentVertexAlphaCB->drop();
393                 OneTextureBlendCB->drop();
394
395                 // Create 2D material renderers
396
397                 c8* vs2DData = 0;
398                 c8* fs2DData = 0;
399                 loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D.fsh"), &vs2DData, &fs2DData);
400                 MaterialRenderer2DTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, true);
401                 delete[] vs2DData;
402                 delete[] fs2DData;
403                 vs2DData = 0;
404                 fs2DData = 0;
405
406                 loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D_noTex.fsh"), &vs2DData, &fs2DData);
407                 MaterialRenderer2DNoTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, false);
408                 delete[] vs2DData;
409                 delete[] fs2DData;
410         }
411
412         bool COpenGL3DriverBase::setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture* texture)
413         {
414                 Material.TextureLayer[layerIdx].Texture = const_cast<ITexture*>(texture); // function uses const-pointer for texture because all draw functions use const-pointers already
415                 return CacheHandler->getTextureCache().set(0, texture);
416         }
417
418         bool COpenGL3DriverBase::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData& videoData, core::rect<s32>* sourceRect)
419         {
420                 CNullDriver::beginScene(clearFlag, clearColor, clearDepth, clearStencil, videoData, sourceRect);
421
422                 if (ContextManager)
423                         ContextManager->activateContext(videoData, true);
424
425                 clearBuffers(clearFlag, clearColor, clearDepth, clearStencil);
426
427                 return true;
428         }
429
430         bool COpenGL3DriverBase::endScene()
431         {
432                 CNullDriver::endScene();
433
434                 glFlush();
435
436                 if (ContextManager)
437                         return ContextManager->swapBuffers();
438
439                 return false;
440         }
441
442
443         //! Returns the transformation set by setTransform
444         const core::matrix4& COpenGL3DriverBase::getTransform(E_TRANSFORMATION_STATE state) const
445         {
446                 return Matrices[state];
447         }
448
449
450         //! sets transformation
451         void COpenGL3DriverBase::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat)
452         {
453                 Matrices[state] = mat;
454                 Transformation3DChanged = true;
455         }
456
457
458         bool COpenGL3DriverBase::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer)
459         {
460                 if (!HWBuffer)
461                         return false;
462
463                 const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer;
464                 const void* vertices = mb->getVertices();
465                 const u32 vertexCount = mb->getVertexCount();
466                 const E_VERTEX_TYPE vType = mb->getVertexType();
467                 const u32 vertexSize = getVertexPitchFromType(vType);
468
469                 const void *buffer = vertices;
470                 size_t bufferSize = vertexSize * vertexCount;
471
472                 //get or create buffer
473                 bool newBuffer = false;
474                 if (!HWBuffer->vbo_verticesID)
475                 {
476                         glGenBuffers(1, &HWBuffer->vbo_verticesID);
477                         if (!HWBuffer->vbo_verticesID) return false;
478                         newBuffer = true;
479                 }
480                 else if (HWBuffer->vbo_verticesSize < bufferSize)
481                 {
482                         newBuffer = true;
483                 }
484
485                 glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID);
486
487                 // copy data to graphics card
488                 if (!newBuffer)
489                         glBufferSubData(GL_ARRAY_BUFFER, 0, bufferSize, buffer);
490                 else
491                 {
492                         HWBuffer->vbo_verticesSize = bufferSize;
493
494                         if (HWBuffer->Mapped_Vertex == scene::EHM_STATIC)
495                                 glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_STATIC_DRAW);
496                         else
497                                 glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_DYNAMIC_DRAW);
498                 }
499
500                 glBindBuffer(GL_ARRAY_BUFFER, 0);
501
502                 return (!testGLError(__LINE__));
503         }
504
505
506         bool COpenGL3DriverBase::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer)
507         {
508                 if (!HWBuffer)
509                         return false;
510
511                 const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer;
512
513                 const void* indices = mb->getIndices();
514                 u32 indexCount = mb->getIndexCount();
515
516                 GLenum indexSize;
517                 switch (mb->getIndexType())
518                 {
519                         case(EIT_16BIT):
520                         {
521                                 indexSize = sizeof(u16);
522                                 break;
523                         }
524                         case(EIT_32BIT):
525                         {
526                                 indexSize = sizeof(u32);
527                                 break;
528                         }
529                         default:
530                         {
531                                 return false;
532                         }
533                 }
534
535                 //get or create buffer
536                 bool newBuffer = false;
537                 if (!HWBuffer->vbo_indicesID)
538                 {
539                         glGenBuffers(1, &HWBuffer->vbo_indicesID);
540                         if (!HWBuffer->vbo_indicesID) return false;
541                         newBuffer = true;
542                 }
543                 else if (HWBuffer->vbo_indicesSize < indexCount*indexSize)
544                 {
545                         newBuffer = true;
546                 }
547
548                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID);
549
550                 // copy data to graphics card
551                 if (!newBuffer)
552                         glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indexCount * indexSize, indices);
553                 else
554                 {
555                         HWBuffer->vbo_indicesSize = indexCount * indexSize;
556
557                         if (HWBuffer->Mapped_Index == scene::EHM_STATIC)
558                                 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_STATIC_DRAW);
559                         else
560                                 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_DYNAMIC_DRAW);
561                 }
562
563                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
564
565                 return (!testGLError(__LINE__));
566         }
567
568
569         //! updates hardware buffer if needed
570         bool COpenGL3DriverBase::updateHardwareBuffer(SHWBufferLink *HWBuffer)
571         {
572                 if (!HWBuffer)
573                         return false;
574
575                 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
576                 {
577                         if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex()
578                                 || !static_cast<SHWBufferLink_opengl*>(HWBuffer)->vbo_verticesID)
579                         {
580
581                                 HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex();
582
583                                 if (!updateVertexHardwareBuffer(static_cast<SHWBufferLink_opengl*>(HWBuffer)))
584                                         return false;
585                         }
586                 }
587
588                 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
589                 {
590                         if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index()
591                                 || !static_cast<SHWBufferLink_opengl*>(HWBuffer)->vbo_indicesID)
592                         {
593
594                                 HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index();
595
596                                 if (!updateIndexHardwareBuffer((SHWBufferLink_opengl*)HWBuffer))
597                                         return false;
598                         }
599                 }
600
601                 return true;
602         }
603
604
605         //! Create hardware buffer from meshbuffer
606         COpenGL3DriverBase::SHWBufferLink *COpenGL3DriverBase::createHardwareBuffer(const scene::IMeshBuffer* mb)
607         {
608                 if (!mb || (mb->getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER))
609                         return 0;
610
611                 SHWBufferLink_opengl *HWBuffer = new SHWBufferLink_opengl(mb);
612
613                 //add to map
614                 HWBuffer->listPosition = HWBufferList.insert(HWBufferList.end(), HWBuffer);
615
616                 HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex();
617                 HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index();
618                 HWBuffer->Mapped_Vertex = mb->getHardwareMappingHint_Vertex();
619                 HWBuffer->Mapped_Index = mb->getHardwareMappingHint_Index();
620                 HWBuffer->vbo_verticesID = 0;
621                 HWBuffer->vbo_indicesID = 0;
622                 HWBuffer->vbo_verticesSize = 0;
623                 HWBuffer->vbo_indicesSize = 0;
624
625                 if (!updateHardwareBuffer(HWBuffer))
626                 {
627                         deleteHardwareBuffer(HWBuffer);
628                         return 0;
629                 }
630
631                 return HWBuffer;
632         }
633
634
635         void COpenGL3DriverBase::deleteHardwareBuffer(SHWBufferLink *_HWBuffer)
636         {
637                 if (!_HWBuffer)
638                         return;
639
640                 SHWBufferLink_opengl *HWBuffer = static_cast<SHWBufferLink_opengl*>(_HWBuffer);
641                 if (HWBuffer->vbo_verticesID)
642                 {
643                         glDeleteBuffers(1, &HWBuffer->vbo_verticesID);
644                         HWBuffer->vbo_verticesID = 0;
645                 }
646                 if (HWBuffer->vbo_indicesID)
647                 {
648                         glDeleteBuffers(1, &HWBuffer->vbo_indicesID);
649                         HWBuffer->vbo_indicesID = 0;
650                 }
651
652                 CNullDriver::deleteHardwareBuffer(_HWBuffer);
653         }
654
655
656         //! Draw hardware buffer
657         void COpenGL3DriverBase::drawHardwareBuffer(SHWBufferLink *_HWBuffer)
658         {
659                 if (!_HWBuffer)
660                         return;
661
662                 SHWBufferLink_opengl *HWBuffer = static_cast<SHWBufferLink_opengl*>(_HWBuffer);
663
664                 updateHardwareBuffer(HWBuffer); //check if update is needed
665
666                 const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer;
667                 const void *vertices = mb->getVertices();
668                 const void *indexList = mb->getIndices();
669
670                 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
671                 {
672                         glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID);
673                         vertices = 0;
674                 }
675
676                 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
677                 {
678                         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID);
679                         indexList = 0;
680                 }
681
682
683                 drawVertexPrimitiveList(vertices, mb->getVertexCount(),
684                                 indexList, mb->getPrimitiveCount(),
685                                 mb->getVertexType(), mb->getPrimitiveType(),
686                                 mb->getIndexType());
687
688                 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
689                         glBindBuffer(GL_ARRAY_BUFFER, 0);
690
691                 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
692                         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
693         }
694
695
696         IRenderTarget* COpenGL3DriverBase::addRenderTarget()
697         {
698                 COpenGL3RenderTarget* renderTarget = new COpenGL3RenderTarget(this);
699                 RenderTargets.push_back(renderTarget);
700
701                 return renderTarget;
702         }
703
704
705         // small helper function to create vertex buffer object adress offsets
706         static inline u8* buffer_offset(const long offset)
707         {
708                 return ((u8*)0 + offset);
709         }
710
711
712         //! draws a vertex primitive list
713         void COpenGL3DriverBase::drawVertexPrimitiveList(const void* vertices, u32 vertexCount,
714                         const void* indexList, u32 primitiveCount,
715                         E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType)
716         {
717                 if (!primitiveCount || !vertexCount)
718                         return;
719
720                 if (!checkPrimitiveCount(primitiveCount))
721                         return;
722
723                 CNullDriver::drawVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount, vType, pType, iType);
724
725                 setRenderStates3DMode();
726
727                 auto &vTypeDesc = getVertexTypeDescription(vType);
728                 beginDraw(vTypeDesc, reinterpret_cast<uintptr_t>(vertices));
729                 GLenum indexSize = 0;
730
731                 switch (iType)
732                 {
733                         case(EIT_16BIT):
734                         {
735                                 indexSize = GL_UNSIGNED_SHORT;
736                                 break;
737                         }
738                         case(EIT_32BIT):
739                         {
740 #ifdef GL_OES_element_index_uint
741 #ifndef GL_UNSIGNED_INT
742 #define GL_UNSIGNED_INT 0x1405
743 #endif
744                                 if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_element_index_uint])
745                                         indexSize = GL_UNSIGNED_INT;
746                                 else
747 #endif
748                                         indexSize = GL_UNSIGNED_SHORT;
749                                 break;
750                         }
751                 }
752
753                 switch (pType)
754                 {
755                         case scene::EPT_POINTS:
756                         case scene::EPT_POINT_SPRITES:
757                                 glDrawArrays(GL_POINTS, 0, primitiveCount);
758                                 break;
759                         case scene::EPT_LINE_STRIP:
760                                 glDrawElements(GL_LINE_STRIP, primitiveCount + 1, indexSize, indexList);
761                                 break;
762                         case scene::EPT_LINE_LOOP:
763                                 glDrawElements(GL_LINE_LOOP, primitiveCount, indexSize, indexList);
764                                 break;
765                         case scene::EPT_LINES:
766                                 glDrawElements(GL_LINES, primitiveCount*2, indexSize, indexList);
767                                 break;
768                         case scene::EPT_TRIANGLE_STRIP:
769                                 glDrawElements(GL_TRIANGLE_STRIP, primitiveCount + 2, indexSize, indexList);
770                                 break;
771                         case scene::EPT_TRIANGLE_FAN:
772                                 glDrawElements(GL_TRIANGLE_FAN, primitiveCount + 2, indexSize, indexList);
773                                 break;
774                         case scene::EPT_TRIANGLES:
775                                 glDrawElements((LastMaterial.Wireframe) ? GL_LINES : (LastMaterial.PointCloud) ? GL_POINTS : GL_TRIANGLES, primitiveCount*3, indexSize, indexList);
776                                 break;
777                         default:
778                                 break;
779                 }
780
781                 endDraw(vTypeDesc);
782         }
783
784
785         void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos,
786                 const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect, SColor color,
787                 bool useAlphaChannelOfTexture)
788         {
789                 if (!texture)
790                         return;
791
792                 if (!sourceRect.isValid())
793                         return;
794
795                 SColor colors[4] = {color, color, color, color};
796                 draw2DImage(texture, {destPos, sourceRect.getSize()}, sourceRect, clipRect, colors, useAlphaChannelOfTexture);
797         }
798
799
800         void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect,
801                 const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect,
802                 const video::SColor* const colors, bool useAlphaChannelOfTexture)
803         {
804                 if (!texture)
805                         return;
806
807                 // texcoords need to be flipped horizontally for RTTs
808                 const bool isRTT = texture->isRenderTarget();
809                 const core::dimension2du& ss = texture->getOriginalSize();
810                 const f32 invW = 1.f / static_cast<f32>(ss.Width);
811                 const f32 invH = 1.f / static_cast<f32>(ss.Height);
812                 const core::rect<f32> tcoords(
813                         sourceRect.UpperLeftCorner.X * invW,
814                         (isRTT ? sourceRect.LowerRightCorner.Y : sourceRect.UpperLeftCorner.Y) * invH,
815                         sourceRect.LowerRightCorner.X * invW,
816                         (isRTT ? sourceRect.UpperLeftCorner.Y : sourceRect.LowerRightCorner.Y) *invH);
817
818                 const video::SColor temp[4] =
819                 {
820                         0xFFFFFFFF,
821                         0xFFFFFFFF,
822                         0xFFFFFFFF,
823                         0xFFFFFFFF
824                 };
825
826                 const video::SColor* const useColor = colors ? colors : temp;
827
828                 chooseMaterial2D();
829                 if (!setMaterialTexture(0, texture ))
830                         return;
831
832                 setRenderStates2DMode(useColor[0].getAlpha() < 255 || useColor[1].getAlpha() < 255 ||
833                         useColor[2].getAlpha() < 255 || useColor[3].getAlpha() < 255,
834                         true, useAlphaChannelOfTexture);
835
836                 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
837
838                 if (clipRect)
839                 {
840                         if (!clipRect->isValid())
841                                 return;
842
843                         glEnable(GL_SCISSOR_TEST);
844                         glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y,
845                                 clipRect->getWidth(), clipRect->getHeight());
846                 }
847
848                 f32 left = (f32)destRect.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
849                 f32 right = (f32)destRect.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
850                 f32 down = 2.f - (f32)destRect.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
851                 f32 top = 2.f - (f32)destRect.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
852
853                 S3DVertex vertices[4];
854                 vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, useColor[0], tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y);
855                 vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, useColor[3], tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y);
856                 vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, useColor[2], tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y);
857                 vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, useColor[1], tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y);
858
859                 drawQuad(vt2DImage, vertices);
860
861                 if (clipRect)
862                         glDisable(GL_SCISSOR_TEST);
863
864                 testGLError(__LINE__);
865         }
866
867         void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, u32 layer, bool flip)
868         {
869                 if (!texture)
870                         return;
871
872                 chooseMaterial2D();
873                 if (!setMaterialTexture(0, texture ))
874                         return;
875
876                 setRenderStates2DMode(false, true, true);
877
878                 S3DVertex quad2DVertices[4];
879
880                 quad2DVertices[0].Pos = core::vector3df(-1.f, 1.f, 0.f);
881                 quad2DVertices[1].Pos = core::vector3df(1.f, 1.f, 0.f);
882                 quad2DVertices[2].Pos = core::vector3df(1.f, -1.f, 0.f);
883                 quad2DVertices[3].Pos = core::vector3df(-1.f, -1.f, 0.f);
884
885                 f32 modificator = (flip) ? 1.f : 0.f;
886
887                 quad2DVertices[0].TCoords = core::vector2df(0.f, 0.f + modificator);
888                 quad2DVertices[1].TCoords = core::vector2df(1.f, 0.f + modificator);
889                 quad2DVertices[2].TCoords = core::vector2df(1.f, 1.f - modificator);
890                 quad2DVertices[3].TCoords = core::vector2df(0.f, 1.f - modificator);
891
892                 quad2DVertices[0].Color = SColor(0xFFFFFFFF);
893                 quad2DVertices[1].Color = SColor(0xFFFFFFFF);
894                 quad2DVertices[2].Color = SColor(0xFFFFFFFF);
895                 quad2DVertices[3].Color = SColor(0xFFFFFFFF);
896
897                 drawQuad(vt2DImage, quad2DVertices);
898         }
899
900         void COpenGL3DriverBase::draw2DImageBatch(const video::ITexture* texture,
901                         const core::array<core::position2d<s32> >& positions,
902                         const core::array<core::rect<s32> >& sourceRects,
903                         const core::rect<s32>* clipRect,
904                         SColor color, bool useAlphaChannelOfTexture)
905         {
906                 if (!texture)
907                         return;
908
909                 chooseMaterial2D();
910                 if (!setMaterialTexture(0, texture))
911                         return;
912
913                 setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture);
914
915                 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
916
917                 if (clipRect)
918                 {
919                         if (!clipRect->isValid())
920                                 return;
921
922                         glEnable(GL_SCISSOR_TEST);
923                         glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y,
924                                         clipRect->getWidth(), clipRect->getHeight());
925                 }
926
927                 const irr::u32 drawCount = core::min_<u32>(positions.size(), sourceRects.size());
928                 assert(6 * drawCount <= QuadIndexCount); // FIXME split the batch? or let it crash?
929
930                 core::array<S3DVertex> vtx(drawCount * 4);
931
932                 for (u32 i = 0; i < drawCount; i++)
933                 {
934                         core::position2d<s32> targetPos = positions[i];
935                         core::position2d<s32> sourcePos = sourceRects[i].UpperLeftCorner;
936                         // This needs to be signed as it may go negative.
937                         core::dimension2d<s32> sourceSize(sourceRects[i].getSize());
938
939                         // now draw it.
940
941                         core::rect<f32> tcoords;
942                         tcoords.UpperLeftCorner.X = (((f32)sourcePos.X)) / texture->getOriginalSize().Width ;
943                         tcoords.UpperLeftCorner.Y = (((f32)sourcePos.Y)) / texture->getOriginalSize().Height;
944                         tcoords.LowerRightCorner.X = tcoords.UpperLeftCorner.X + ((f32)(sourceSize.Width) / texture->getOriginalSize().Width);
945                         tcoords.LowerRightCorner.Y = tcoords.UpperLeftCorner.Y + ((f32)(sourceSize.Height) / texture->getOriginalSize().Height);
946
947                         const core::rect<s32> poss(targetPos, sourceSize);
948
949                         f32 left = (f32)poss.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
950                         f32 right = (f32)poss.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
951                         f32 down = 2.f - (f32)poss.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
952                         f32 top = 2.f - (f32)poss.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
953
954                         vtx.push_back(S3DVertex(left, top, 0.0f,
955                                         0.0f, 0.0f, 0.0f, color,
956                                         tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y));
957                         vtx.push_back(S3DVertex(right, top, 0.0f,
958                                         0.0f, 0.0f, 0.0f, color,
959                                         tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y));
960                         vtx.push_back(S3DVertex(right, down, 0.0f,
961                                         0.0f, 0.0f, 0.0f, color,
962                                         tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y));
963                         vtx.push_back(S3DVertex(left, down, 0.0f,
964                                         0.0f, 0.0f, 0.0f, color,
965                                         tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y));
966                 }
967
968                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, QuadIndexBuffer);
969                 drawElements(GL_TRIANGLES, vt2DImage, vtx.const_pointer(), vtx.size(), 0, 6 * drawCount);
970                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
971
972                 if (clipRect)
973                         glDisable(GL_SCISSOR_TEST);
974         }
975
976
977         //! draw a 2d rectangle
978         void COpenGL3DriverBase::draw2DRectangle(SColor color,
979                         const core::rect<s32>& position,
980                         const core::rect<s32>* clip)
981         {
982                 chooseMaterial2D();
983                 setMaterialTexture(0, 0);
984
985                 setRenderStates2DMode(color.getAlpha() < 255, false, false);
986
987                 core::rect<s32> pos = position;
988
989                 if (clip)
990                         pos.clipAgainst(*clip);
991
992                 if (!pos.isValid())
993                         return;
994
995                 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
996
997                 f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
998                 f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
999                 f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1000                 f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1001
1002                 S3DVertex vertices[4];
1003                 vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, color, 0, 0);
1004                 vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, color, 0, 0);
1005                 vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, color, 0, 0);
1006                 vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, color, 0, 0);
1007
1008                 drawQuad(vtPrimitive, vertices);
1009         }
1010
1011
1012         //! draw an 2d rectangle
1013         void COpenGL3DriverBase::draw2DRectangle(const core::rect<s32>& position,
1014                         SColor colorLeftUp, SColor colorRightUp,
1015                         SColor colorLeftDown, SColor colorRightDown,
1016                         const core::rect<s32>* clip)
1017         {
1018                 core::rect<s32> pos = position;
1019
1020                 if (clip)
1021                         pos.clipAgainst(*clip);
1022
1023                 if (!pos.isValid())
1024                         return;
1025
1026                 chooseMaterial2D();
1027                 setMaterialTexture(0, 0);
1028
1029                 setRenderStates2DMode(colorLeftUp.getAlpha() < 255 ||
1030                                 colorRightUp.getAlpha() < 255 ||
1031                                 colorLeftDown.getAlpha() < 255 ||
1032                                 colorRightDown.getAlpha() < 255, false, false);
1033
1034                 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1035
1036                 f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1037                 f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1038                 f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1039                 f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1040
1041                 S3DVertex vertices[4];
1042                 vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, colorLeftUp, 0, 0);
1043                 vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, colorRightUp, 0, 0);
1044                 vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, colorRightDown, 0, 0);
1045                 vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, colorLeftDown, 0, 0);
1046
1047                 drawQuad(vtPrimitive, vertices);
1048         }
1049
1050
1051         //! Draws a 2d line.
1052         void COpenGL3DriverBase::draw2DLine(const core::position2d<s32>& start,
1053                         const core::position2d<s32>& end, SColor color)
1054         {
1055                 if (start==end)
1056                         drawPixel(start.X, start.Y, color);
1057                 else
1058                 {
1059                         chooseMaterial2D();
1060                         setMaterialTexture(0, 0);
1061
1062                         setRenderStates2DMode(color.getAlpha() < 255, false, false);
1063
1064                         const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1065
1066                         f32 startX = (f32)start.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1067                         f32 endX = (f32)end.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1068                         f32 startY = 2.f - (f32)start.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1069                         f32 endY = 2.f - (f32)end.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1070
1071                         S3DVertex vertices[2];
1072                         vertices[0] = S3DVertex(startX, startY, 0, 0, 0, 1, color, 0, 0);
1073                         vertices[1] = S3DVertex(endX, endY, 0, 0, 0, 1, color, 1, 1);
1074
1075                         drawArrays(GL_LINES, vtPrimitive, vertices, 2);
1076                 }
1077         }
1078
1079
1080         //! Draws a pixel
1081         void COpenGL3DriverBase::drawPixel(u32 x, u32 y, const SColor &color)
1082         {
1083                 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1084                 if (x > (u32)renderTargetSize.Width || y > (u32)renderTargetSize.Height)
1085                         return;
1086
1087                 chooseMaterial2D();
1088                 setMaterialTexture(0, 0);
1089
1090                 setRenderStates2DMode(color.getAlpha() < 255, false, false);
1091
1092                 f32 X = (f32)x / (f32)renderTargetSize.Width * 2.f - 1.f;
1093                 f32 Y = 2.f - (f32)y / (f32)renderTargetSize.Height * 2.f - 1.f;
1094
1095                 S3DVertex vertices[1];
1096                 vertices[0] = S3DVertex(X, Y, 0, 0, 0, 1, color, 0, 0);
1097
1098                 drawArrays(GL_POINTS, vtPrimitive, vertices, 1);
1099         }
1100
1101         void COpenGL3DriverBase::drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4])
1102         {
1103                 drawArrays(GL_TRIANGLE_FAN, vertexType, vertices, 4);
1104         }
1105
1106         void COpenGL3DriverBase::drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount)
1107         {
1108                 beginDraw(vertexType, reinterpret_cast<uintptr_t>(vertices));
1109                 glDrawArrays(primitiveType, 0, vertexCount);
1110                 endDraw(vertexType);
1111         }
1112
1113         void COpenGL3DriverBase::drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount, const u16 *indices, int indexCount)
1114         {
1115                 beginDraw(vertexType, reinterpret_cast<uintptr_t>(vertices));
1116                 glDrawRangeElements(primitiveType, 0, vertexCount - 1, indexCount, GL_UNSIGNED_SHORT, indices);
1117                 endDraw(vertexType);
1118         }
1119
1120         void COpenGL3DriverBase::beginDraw(const VertexType &vertexType, uintptr_t verticesBase)
1121         {
1122                 for (auto attr: vertexType) {
1123                         glEnableVertexAttribArray(attr.Index);
1124                         switch (attr.mode) {
1125                         case VertexAttribute::Mode::Regular: glVertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_FALSE, vertexType.VertexSize, reinterpret_cast<void *>(verticesBase + attr.Offset)); break;
1126                         case VertexAttribute::Mode::Normalized: glVertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_TRUE, vertexType.VertexSize, reinterpret_cast<void *>(verticesBase + attr.Offset)); break;
1127                         case VertexAttribute::Mode::Integral: glVertexAttribIPointer(attr.Index, attr.ComponentCount, attr.ComponentType, vertexType.VertexSize, reinterpret_cast<void *>(verticesBase + attr.Offset)); break;
1128                         }
1129                 }
1130         }
1131
1132         void COpenGL3DriverBase::endDraw(const VertexType &vertexType)
1133         {
1134                 for (auto attr: vertexType)
1135                         glDisableVertexAttribArray(attr.Index);
1136         }
1137
1138         ITexture* COpenGL3DriverBase::createDeviceDependentTexture(const io::path& name, IImage* image)
1139         {
1140                 core::array<IImage*> imageArray(1);
1141                 imageArray.push_back(image);
1142
1143                 COpenGL3Texture* texture = new COpenGL3Texture(name, imageArray, ETT_2D, this);
1144
1145                 return texture;
1146         }
1147
1148         ITexture* COpenGL3DriverBase::createDeviceDependentTextureCubemap(const io::path& name, const core::array<IImage*>& image)
1149         {
1150                 COpenGL3Texture* texture = new COpenGL3Texture(name, image, ETT_CUBEMAP, this);
1151
1152                 return texture;
1153         }
1154
1155         //! Sets a material.
1156         void COpenGL3DriverBase::setMaterial(const SMaterial& material)
1157         {
1158                 Material = material;
1159                 OverrideMaterial.apply(Material);
1160
1161                 for (u32 i = 0; i < Feature.MaxTextureUnits; ++i)
1162                 {
1163                         CacheHandler->getTextureCache().set(i, material.getTexture(i));
1164                         setTransform((E_TRANSFORMATION_STATE)(ETS_TEXTURE_0 + i), material.getTextureMatrix(i));
1165                 }
1166         }
1167
1168         //! prints error if an error happened.
1169         bool COpenGL3DriverBase::testGLError(int code)
1170         {
1171 #ifdef _DEBUG
1172                 GLenum g = glGetError();
1173                 switch (g)
1174                 {
1175                         case GL_NO_ERROR:
1176                                 return false;
1177                         case GL_INVALID_ENUM:
1178                                 os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR);
1179                                 break;
1180                         case GL_INVALID_VALUE:
1181                                 os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR);
1182                                 break;
1183                         case GL_INVALID_OPERATION:
1184                                 os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR);
1185                                 break;
1186                         case GL_OUT_OF_MEMORY:
1187                                 os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR);
1188                                 break;
1189                 };
1190                 return true;
1191 #else
1192                 return false;
1193 #endif
1194         }
1195
1196         //! prints error if an error happened.
1197         bool COpenGL3DriverBase::testEGLError()
1198         {
1199 #if defined(EGL_VERSION_1_0) && defined(_DEBUG)
1200                 EGLint g = eglGetError();
1201                 switch (g)
1202                 {
1203                         case EGL_SUCCESS:
1204                                 return false;
1205                         case EGL_NOT_INITIALIZED :
1206                                 os::Printer::log("Not Initialized", ELL_ERROR);
1207                                 break;
1208                         case EGL_BAD_ACCESS:
1209                                 os::Printer::log("Bad Access", ELL_ERROR);
1210                                 break;
1211                         case EGL_BAD_ALLOC:
1212                                 os::Printer::log("Bad Alloc", ELL_ERROR);
1213                                 break;
1214                         case EGL_BAD_ATTRIBUTE:
1215                                 os::Printer::log("Bad Attribute", ELL_ERROR);
1216                                 break;
1217                         case EGL_BAD_CONTEXT:
1218                                 os::Printer::log("Bad Context", ELL_ERROR);
1219                                 break;
1220                         case EGL_BAD_CONFIG:
1221                                 os::Printer::log("Bad Config", ELL_ERROR);
1222                                 break;
1223                         case EGL_BAD_CURRENT_SURFACE:
1224                                 os::Printer::log("Bad Current Surface", ELL_ERROR);
1225                                 break;
1226                         case EGL_BAD_DISPLAY:
1227                                 os::Printer::log("Bad Display", ELL_ERROR);
1228                                 break;
1229                         case EGL_BAD_SURFACE:
1230                                 os::Printer::log("Bad Surface", ELL_ERROR);
1231                                 break;
1232                         case EGL_BAD_MATCH:
1233                                 os::Printer::log("Bad Match", ELL_ERROR);
1234                                 break;
1235                         case EGL_BAD_PARAMETER:
1236                                 os::Printer::log("Bad Parameter", ELL_ERROR);
1237                                 break;
1238                         case EGL_BAD_NATIVE_PIXMAP:
1239                                 os::Printer::log("Bad Native Pixmap", ELL_ERROR);
1240                                 break;
1241                         case EGL_BAD_NATIVE_WINDOW:
1242                                 os::Printer::log("Bad Native Window", ELL_ERROR);
1243                                 break;
1244                         case EGL_CONTEXT_LOST:
1245                                 os::Printer::log("Context Lost", ELL_ERROR);
1246                                 break;
1247                 };
1248                 return true;
1249 #else
1250                 return false;
1251 #endif
1252         }
1253
1254
1255         void COpenGL3DriverBase::setRenderStates3DMode()
1256         {
1257                 if ( LockRenderStateMode )
1258                         return;
1259
1260                 if (CurrentRenderMode != ERM_3D)
1261                 {
1262                         // Reset Texture Stages
1263                         CacheHandler->setBlend(false);
1264                         CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1265
1266                         ResetRenderStates = true;
1267                 }
1268
1269                 if (ResetRenderStates || LastMaterial != Material)
1270                 {
1271                         // unset old material
1272
1273                         // unset last 3d material
1274                         if (CurrentRenderMode == ERM_2D && MaterialRenderer2DActive)
1275                         {
1276                                 MaterialRenderer2DActive->OnUnsetMaterial();
1277                                 MaterialRenderer2DActive = 0;
1278                         }
1279                         else if (LastMaterial.MaterialType != Material.MaterialType &&
1280                                         static_cast<u32>(LastMaterial.MaterialType) < MaterialRenderers.size())
1281                                 MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial();
1282
1283                         // set new material.
1284                         if (static_cast<u32>(Material.MaterialType) < MaterialRenderers.size())
1285                                 MaterialRenderers[Material.MaterialType].Renderer->OnSetMaterial(
1286                                         Material, LastMaterial, ResetRenderStates, this);
1287
1288                         LastMaterial = Material;
1289                         CacheHandler->correctCacheMaterial(LastMaterial);
1290                         ResetRenderStates = false;
1291                 }
1292
1293                 if (static_cast<u32>(Material.MaterialType) < MaterialRenderers.size())
1294                         MaterialRenderers[Material.MaterialType].Renderer->OnRender(this, video::EVT_STANDARD);
1295
1296                 CurrentRenderMode = ERM_3D;
1297         }
1298
1299         //! Can be called by an IMaterialRenderer to make its work easier.
1300         void COpenGL3DriverBase::setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, bool resetAllRenderStates)
1301         {
1302                 // ZBuffer
1303                 switch (material.ZBuffer)
1304                 {
1305                         case ECFN_DISABLED:
1306                                 CacheHandler->setDepthTest(false);
1307                                 break;
1308                         case ECFN_LESSEQUAL:
1309                                 CacheHandler->setDepthTest(true);
1310                                 CacheHandler->setDepthFunc(GL_LEQUAL);
1311                                 break;
1312                         case ECFN_EQUAL:
1313                                 CacheHandler->setDepthTest(true);
1314                                 CacheHandler->setDepthFunc(GL_EQUAL);
1315                                 break;
1316                         case ECFN_LESS:
1317                                 CacheHandler->setDepthTest(true);
1318                                 CacheHandler->setDepthFunc(GL_LESS);
1319                                 break;
1320                         case ECFN_NOTEQUAL:
1321                                 CacheHandler->setDepthTest(true);
1322                                 CacheHandler->setDepthFunc(GL_NOTEQUAL);
1323                                 break;
1324                         case ECFN_GREATEREQUAL:
1325                                 CacheHandler->setDepthTest(true);
1326                                 CacheHandler->setDepthFunc(GL_GEQUAL);
1327                                 break;
1328                         case ECFN_GREATER:
1329                                 CacheHandler->setDepthTest(true);
1330                                 CacheHandler->setDepthFunc(GL_GREATER);
1331                                 break;
1332                         case ECFN_ALWAYS:
1333                                 CacheHandler->setDepthTest(true);
1334                                 CacheHandler->setDepthFunc(GL_ALWAYS);
1335                                 break;
1336                         case ECFN_NEVER:
1337                                 CacheHandler->setDepthTest(true);
1338                                 CacheHandler->setDepthFunc(GL_NEVER);
1339                                 break;
1340                         default:
1341                                 break;
1342                 }
1343
1344                 // ZWrite
1345                 if (getWriteZBuffer(material))
1346                 {
1347                         CacheHandler->setDepthMask(true);
1348                 }
1349                 else
1350                 {
1351                         CacheHandler->setDepthMask(false);
1352                 }
1353
1354                 // Back face culling
1355                 if ((material.FrontfaceCulling) && (material.BackfaceCulling))
1356                 {
1357                         CacheHandler->setCullFaceFunc(GL_FRONT_AND_BACK);
1358                         CacheHandler->setCullFace(true);
1359                 }
1360                 else if (material.BackfaceCulling)
1361                 {
1362                         CacheHandler->setCullFaceFunc(GL_BACK);
1363                         CacheHandler->setCullFace(true);
1364                 }
1365                 else if (material.FrontfaceCulling)
1366                 {
1367                         CacheHandler->setCullFaceFunc(GL_FRONT);
1368                         CacheHandler->setCullFace(true);
1369                 }
1370                 else
1371                 {
1372                         CacheHandler->setCullFace(false);
1373                 }
1374
1375                 // Color Mask
1376                 CacheHandler->setColorMask(material.ColorMask);
1377
1378                 // Blend Equation
1379                 if (material.BlendOperation == EBO_NONE)
1380                         CacheHandler->setBlend(false);
1381                 else
1382                 {
1383                         CacheHandler->setBlend(true);
1384
1385                         switch (material.BlendOperation)
1386                         {
1387                         case EBO_ADD:
1388                                 CacheHandler->setBlendEquation(GL_FUNC_ADD);
1389                                 break;
1390                         case EBO_SUBTRACT:
1391                                 CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT);
1392                                 break;
1393                         case EBO_REVSUBTRACT:
1394                                 CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
1395                                 break;
1396                         default:
1397                                 break;
1398                         }
1399                 }
1400
1401                 // Blend Factor
1402                 if (IR(material.BlendFactor) & 0xFFFFFFFF       // TODO: why the & 0xFFFFFFFF?
1403                         && material.MaterialType != EMT_ONETEXTURE_BLEND
1404                 )
1405                 {
1406                     E_BLEND_FACTOR srcRGBFact = EBF_ZERO;
1407                     E_BLEND_FACTOR dstRGBFact = EBF_ZERO;
1408                     E_BLEND_FACTOR srcAlphaFact = EBF_ZERO;
1409                     E_BLEND_FACTOR dstAlphaFact = EBF_ZERO;
1410                     E_MODULATE_FUNC modulo = EMFN_MODULATE_1X;
1411                     u32 alphaSource = 0;
1412
1413                     unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor);
1414
1415                         CacheHandler->setBlendFuncSeparate(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact),
1416                                 getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact));
1417                 }
1418
1419                 // TODO: Polygon Offset. Not sure if it was left out deliberately or if it won't work with this driver.
1420
1421                 if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness)
1422                         glLineWidth(core::clamp(static_cast<GLfloat>(material.Thickness), DimAliasedLine[0], DimAliasedLine[1]));
1423
1424                 // Anti aliasing
1425                 if (resetAllRenderStates || lastmaterial.AntiAliasing != material.AntiAliasing)
1426                 {
1427                         if (material.AntiAliasing & EAAM_ALPHA_TO_COVERAGE)
1428                                 glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
1429                         else if (lastmaterial.AntiAliasing & EAAM_ALPHA_TO_COVERAGE)
1430                                 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
1431                 }
1432
1433                 // Texture parameters
1434                 setTextureRenderStates(material, resetAllRenderStates);
1435         }
1436
1437         //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call.
1438         void COpenGL3DriverBase::setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates)
1439         {
1440                 // Set textures to TU/TIU and apply filters to them
1441
1442                 for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i)
1443                 {
1444                         const COpenGL3Texture* tmpTexture = CacheHandler->getTextureCache()[i];
1445
1446                         if (!tmpTexture)
1447                                 continue;
1448
1449                         GLenum tmpTextureType = tmpTexture->getOpenGLTextureType();
1450
1451                         CacheHandler->setActiveTexture(GL_TEXTURE0 + i);
1452
1453                         if (resetAllRenderstates)
1454                                 tmpTexture->getStatesCache().IsCached = false;
1455
1456                         if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1457                                 material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter)
1458                         {
1459                                 glTexParameteri(tmpTextureType, GL_TEXTURE_MAG_FILTER,
1460                                         (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST);
1461
1462                                 tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1463                                 tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1464                         }
1465
1466                         if (material.UseMipMaps && tmpTexture->hasMipMaps())
1467                         {
1468                                 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1469                                         material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || !tmpTexture->getStatesCache().MipMapStatus)
1470                                 {
1471                                         glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER,
1472                                                 material.TextureLayer[i].TrilinearFilter ? GL_LINEAR_MIPMAP_LINEAR :
1473                                                 material.TextureLayer[i].BilinearFilter ? GL_LINEAR_MIPMAP_NEAREST :
1474                                                 GL_NEAREST_MIPMAP_NEAREST);
1475
1476                                         tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1477                                         tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1478                                         tmpTexture->getStatesCache().MipMapStatus = true;
1479                                 }
1480                         }
1481                         else
1482                         {
1483                                 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1484                                         material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || tmpTexture->getStatesCache().MipMapStatus)
1485                                 {
1486                                         glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER,
1487                                                 (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST);
1488
1489                                         tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1490                                         tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1491                                         tmpTexture->getStatesCache().MipMapStatus = false;
1492                                 }
1493                         }
1494
1495         #ifdef GL_EXT_texture_filter_anisotropic
1496                         if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_EXT_texture_filter_anisotropic] &&
1497                                 (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].AnisotropicFilter != tmpTexture->getStatesCache().AnisotropicFilter))
1498                         {
1499                                 glTexParameteri(tmpTextureType, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1500                                         material.TextureLayer[i].AnisotropicFilter>1 ? core::min_(MaxAnisotropy, material.TextureLayer[i].AnisotropicFilter) : 1);
1501
1502                                 tmpTexture->getStatesCache().AnisotropicFilter = material.TextureLayer[i].AnisotropicFilter;
1503                         }
1504         #endif
1505
1506                         if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapU != tmpTexture->getStatesCache().WrapU)
1507                         {
1508                                 glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_S, getTextureWrapMode(material.TextureLayer[i].TextureWrapU));
1509                                 tmpTexture->getStatesCache().WrapU = material.TextureLayer[i].TextureWrapU;
1510                         }
1511
1512                         if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapV != tmpTexture->getStatesCache().WrapV)
1513                         {
1514                                 glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_T, getTextureWrapMode(material.TextureLayer[i].TextureWrapV));
1515                                 tmpTexture->getStatesCache().WrapV = material.TextureLayer[i].TextureWrapV;
1516                         }
1517
1518                         tmpTexture->getStatesCache().IsCached = true;
1519                 }
1520         }
1521
1522
1523         // Get OpenGL ES2.0 texture wrap mode from Irrlicht wrap mode.
1524         GLint COpenGL3DriverBase::getTextureWrapMode(u8 clamp) const
1525         {
1526                 switch (clamp)
1527                 {
1528                         case ETC_CLAMP:
1529                         case ETC_CLAMP_TO_EDGE:
1530                         case ETC_CLAMP_TO_BORDER:
1531                                 return GL_CLAMP_TO_EDGE;
1532                         case ETC_MIRROR:
1533                                 return GL_REPEAT;
1534                         default:
1535                                 return GL_REPEAT;
1536                 }
1537         }
1538
1539
1540         //! sets the needed renderstates
1541         void COpenGL3DriverBase::setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel)
1542         {
1543                 if ( LockRenderStateMode )
1544                         return;
1545
1546                 COpenGL3Renderer2D* nextActiveRenderer = texture ? MaterialRenderer2DTexture : MaterialRenderer2DNoTexture;
1547
1548                 if (CurrentRenderMode != ERM_2D)
1549                 {
1550                         // unset last 3d material
1551                         if (CurrentRenderMode == ERM_3D)
1552                         {
1553                                 if (static_cast<u32>(LastMaterial.MaterialType) < MaterialRenderers.size())
1554                                         MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial();
1555                         }
1556
1557                         CurrentRenderMode = ERM_2D;
1558                 }
1559                 else if ( MaterialRenderer2DActive && MaterialRenderer2DActive != nextActiveRenderer)
1560                 {
1561                         MaterialRenderer2DActive->OnUnsetMaterial();
1562                 }
1563
1564                 MaterialRenderer2DActive = nextActiveRenderer;
1565
1566                 MaterialRenderer2DActive->OnSetMaterial(Material, LastMaterial, true, 0);
1567                 LastMaterial = Material;
1568                 CacheHandler->correctCacheMaterial(LastMaterial);
1569
1570                 // no alphaChannel without texture
1571                 alphaChannel &= texture;
1572
1573                 if (alphaChannel || alpha)
1574                 {
1575                         CacheHandler->setBlend(true);
1576                         CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1577                         CacheHandler->setBlendEquation(GL_FUNC_ADD);
1578                 }
1579                 else
1580                         CacheHandler->setBlend(false);
1581
1582                 Material.setTexture(0, const_cast<COpenGL3Texture*>(CacheHandler->getTextureCache().get(0)));
1583                 setTransform(ETS_TEXTURE_0, core::IdentityMatrix);
1584
1585                 if (texture)
1586                 {
1587                         if (OverrideMaterial2DEnabled)
1588                                 setTextureRenderStates(OverrideMaterial2D, false);
1589                         else
1590                                 setTextureRenderStates(InitMaterial2D, false);
1591                 }
1592
1593                 MaterialRenderer2DActive->OnRender(this, video::EVT_STANDARD);
1594         }
1595
1596
1597         void COpenGL3DriverBase::chooseMaterial2D()
1598         {
1599                 if (!OverrideMaterial2DEnabled)
1600                         Material = InitMaterial2D;
1601
1602                 if (OverrideMaterial2DEnabled)
1603                 {
1604                         OverrideMaterial2D.Lighting=false;
1605                         OverrideMaterial2D.ZWriteEnable=EZW_OFF;
1606                         OverrideMaterial2D.ZBuffer=ECFN_DISABLED; // it will be ECFN_DISABLED after merge
1607                         OverrideMaterial2D.Lighting=false;
1608
1609                         Material = OverrideMaterial2D;
1610                 }
1611         }
1612
1613
1614         //! \return Returns the name of the video driver.
1615         const wchar_t* COpenGL3DriverBase::getName() const
1616         {
1617                 return Name.c_str();
1618         }
1619
1620         void COpenGL3DriverBase::setViewPort(const core::rect<s32>& area)
1621         {
1622                 core::rect<s32> vp = area;
1623                 core::rect<s32> rendert(0, 0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height);
1624                 vp.clipAgainst(rendert);
1625
1626                 if (vp.getHeight() > 0 && vp.getWidth() > 0)
1627                         CacheHandler->setViewport(vp.UpperLeftCorner.X, getCurrentRenderTargetSize().Height - vp.UpperLeftCorner.Y - vp.getHeight(), vp.getWidth(), vp.getHeight());
1628
1629                 ViewPort = vp;
1630         }
1631
1632
1633         void COpenGL3DriverBase::setViewPortRaw(u32 width, u32 height)
1634         {
1635                 CacheHandler->setViewport(0, 0, width, height);
1636                 ViewPort = core::recti(0, 0, width, height);
1637         }
1638
1639
1640         //! Draws a 3d line.
1641         void COpenGL3DriverBase::draw3DLine(const core::vector3df& start,
1642                         const core::vector3df& end, SColor color)
1643         {
1644                 setRenderStates3DMode();
1645
1646                 S3DVertex vertices[2];
1647                 vertices[0] = S3DVertex(start.X, start.Y, start.Z, 0, 0, 1, color, 0, 0);
1648                 vertices[1] = S3DVertex(end.X, end.Y, end.Z, 0, 0, 1, color, 0, 0);
1649
1650                 drawArrays(GL_LINES, vtPrimitive, vertices, 2);
1651         }
1652
1653
1654         //! Only used by the internal engine. Used to notify the driver that
1655         //! the window was resized.
1656         void COpenGL3DriverBase::OnResize(const core::dimension2d<u32>& size)
1657         {
1658                 CNullDriver::OnResize(size);
1659                 CacheHandler->setViewport(0, 0, size.Width, size.Height);
1660                 Transformation3DChanged = true;
1661         }
1662
1663
1664         //! Returns type of video driver
1665         E_DRIVER_TYPE COpenGL3DriverBase::getDriverType() const
1666         {
1667                 return EDT_OPENGL3;
1668         }
1669
1670
1671         //! returns color format
1672         ECOLOR_FORMAT COpenGL3DriverBase::getColorFormat() const
1673         {
1674                 return ColorFormat;
1675         }
1676
1677
1678         //! Get a vertex shader constant index.
1679         s32 COpenGL3DriverBase::getVertexShaderConstantID(const c8* name)
1680         {
1681                 return getPixelShaderConstantID(name);
1682         }
1683
1684         //! Get a pixel shader constant index.
1685         s32 COpenGL3DriverBase::getPixelShaderConstantID(const c8* name)
1686         {
1687                 os::Printer::log("Error: Please call services->getPixelShaderConstantID(), not VideoDriver->getPixelShaderConstantID().");
1688                 return -1;
1689         }
1690
1691         //! Sets a vertex shader constant.
1692         void COpenGL3DriverBase::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
1693         {
1694                 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1695         }
1696
1697         //! Sets a pixel shader constant.
1698         void COpenGL3DriverBase::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
1699         {
1700                 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1701         }
1702
1703         //! Sets a constant for the vertex shader based on an index.
1704         bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const f32* floats, int count)
1705         {
1706                 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1707                 return false;
1708         }
1709
1710         //! Int interface for the above.
1711         bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const s32* ints, int count)
1712         {
1713                 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1714                 return false;
1715         }
1716
1717         bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const u32* ints, int count)
1718         {
1719                 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1720                 return false;
1721         }
1722
1723         //! Sets a constant for the pixel shader based on an index.
1724         bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const f32* floats, int count)
1725         {
1726                 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1727                 return false;
1728         }
1729
1730         //! Int interface for the above.
1731         bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const s32* ints, int count)
1732         {
1733                 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1734                 return false;
1735         }
1736
1737         bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const u32* ints, int count)
1738         {
1739                 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1740                 return false;
1741         }
1742
1743         //! Adds a new material renderer to the VideoDriver, using pixel and/or
1744         //! vertex shaders to render geometry.
1745         s32 COpenGL3DriverBase::addShaderMaterial(const c8* vertexShaderProgram,
1746                         const c8* pixelShaderProgram,
1747                         IShaderConstantSetCallBack* callback,
1748                         E_MATERIAL_TYPE baseMaterial, s32 userData)
1749         {
1750                 os::Printer::log("No shader support.");
1751                 return -1;
1752         }
1753
1754
1755         //! Adds a new material renderer to the VideoDriver, using GLSL to render geometry.
1756         s32 COpenGL3DriverBase::addHighLevelShaderMaterial(
1757                         const c8* vertexShaderProgram,
1758                         const c8* vertexShaderEntryPointName,
1759                         E_VERTEX_SHADER_TYPE vsCompileTarget,
1760                         const c8* pixelShaderProgram,
1761                         const c8* pixelShaderEntryPointName,
1762                         E_PIXEL_SHADER_TYPE psCompileTarget,
1763                         const c8* geometryShaderProgram,
1764                         const c8* geometryShaderEntryPointName,
1765                         E_GEOMETRY_SHADER_TYPE gsCompileTarget,
1766                         scene::E_PRIMITIVE_TYPE inType,
1767                         scene::E_PRIMITIVE_TYPE outType,
1768                         u32 verticesOut,
1769                         IShaderConstantSetCallBack* callback,
1770                         E_MATERIAL_TYPE baseMaterial,
1771                         s32 userData)
1772         {
1773                 s32 nr = -1;
1774                 COpenGL3MaterialRenderer* r = new COpenGL3MaterialRenderer(
1775                         this, nr, vertexShaderProgram,
1776                         pixelShaderProgram,
1777                         callback, baseMaterial, userData);
1778
1779                 r->drop();
1780                 return nr;
1781         }
1782
1783         //! Returns a pointer to the IVideoDriver interface. (Implementation for
1784         //! IMaterialRendererServices)
1785         IVideoDriver* COpenGL3DriverBase::getVideoDriver()
1786         {
1787                 return this;
1788         }
1789
1790
1791         //! Returns pointer to the IGPUProgrammingServices interface.
1792         IGPUProgrammingServices* COpenGL3DriverBase::getGPUProgrammingServices()
1793         {
1794                 return this;
1795         }
1796
1797         ITexture* COpenGL3DriverBase::addRenderTargetTexture(const core::dimension2d<u32>& size,
1798                 const io::path& name, const ECOLOR_FORMAT format)
1799         {
1800                 //disable mip-mapping
1801                 bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS);
1802                 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false);
1803
1804                 COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, size, ETT_2D, format, this);
1805                 addTexture(renderTargetTexture);
1806                 renderTargetTexture->drop();
1807
1808                 //restore mip-mapping
1809                 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels);
1810
1811                 return renderTargetTexture;
1812         }
1813
1814         ITexture* COpenGL3DriverBase::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path& name, const ECOLOR_FORMAT format)
1815         {
1816                 //disable mip-mapping
1817                 bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS);
1818                 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false);
1819
1820                 bool supportForFBO = (Feature.ColorAttachment > 0);
1821
1822                 const core::dimension2d<u32> size(sideLen, sideLen);
1823                 core::dimension2du destSize(size);
1824
1825                 if (!supportForFBO)
1826                 {
1827                         destSize = core::dimension2d<u32>(core::min_(size.Width, ScreenSize.Width), core::min_(size.Height, ScreenSize.Height));
1828                         destSize = destSize.getOptimalSize((size == size.getOptimalSize()), false, false);
1829                 }
1830
1831                 COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, destSize, ETT_CUBEMAP, format, this);
1832                 addTexture(renderTargetTexture);
1833                 renderTargetTexture->drop();
1834
1835                 //restore mip-mapping
1836                 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels);
1837
1838                 return renderTargetTexture;
1839         }
1840
1841
1842         //! Returns the maximum amount of primitives
1843         u32 COpenGL3DriverBase::getMaximalPrimitiveCount() const
1844         {
1845                 return 65535;
1846         }
1847
1848         bool COpenGL3DriverBase::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil)
1849         {
1850                 if (target && target->getDriverType() != getDriverType())
1851                 {
1852                         os::Printer::log("Fatal Error: Tried to set a render target not owned by OpenGL 3 driver.", ELL_ERROR);
1853                         return false;
1854                 }
1855
1856                 core::dimension2d<u32> destRenderTargetSize(0, 0);
1857
1858                 if (target)
1859                 {
1860                         COpenGL3RenderTarget* renderTarget = static_cast<COpenGL3RenderTarget*>(target);
1861
1862                         CacheHandler->setFBO(renderTarget->getBufferID());
1863                         renderTarget->update();
1864
1865                         destRenderTargetSize = renderTarget->getSize();
1866
1867                         setViewPortRaw(destRenderTargetSize.Width, destRenderTargetSize.Height);
1868                 }
1869                 else
1870                 {
1871                         CacheHandler->setFBO(0);
1872
1873                         destRenderTargetSize = core::dimension2d<u32>(0, 0);
1874
1875                         setViewPortRaw(ScreenSize.Width, ScreenSize.Height);
1876                 }
1877
1878                 if (CurrentRenderTargetSize != destRenderTargetSize)
1879                 {
1880                         CurrentRenderTargetSize = destRenderTargetSize;
1881
1882                         Transformation3DChanged = true;
1883                 }
1884
1885                 CurrentRenderTarget = target;
1886
1887                 clearBuffers(clearFlag, clearColor, clearDepth, clearStencil);
1888
1889                 return true;
1890         }
1891
1892         void COpenGL3DriverBase::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil)
1893         {
1894                 GLbitfield mask = 0;
1895                 u8 colorMask = 0;
1896                 bool depthMask = false;
1897
1898                 CacheHandler->getColorMask(colorMask);
1899                 CacheHandler->getDepthMask(depthMask);
1900
1901                 if (flag & ECBF_COLOR)
1902                 {
1903                         CacheHandler->setColorMask(ECP_ALL);
1904
1905                         const f32 inv = 1.0f / 255.0f;
1906                         glClearColor(color.getRed() * inv, color.getGreen() * inv,
1907                                 color.getBlue() * inv, color.getAlpha() * inv);
1908
1909                         mask |= GL_COLOR_BUFFER_BIT;
1910                 }
1911
1912                 if (flag & ECBF_DEPTH)
1913                 {
1914                         CacheHandler->setDepthMask(true);
1915                         glClearDepthf(depth);
1916                         mask |= GL_DEPTH_BUFFER_BIT;
1917                 }
1918
1919                 if (flag & ECBF_STENCIL)
1920                 {
1921                         glClearStencil(stencil);
1922                         mask |= GL_STENCIL_BUFFER_BIT;
1923                 }
1924
1925                 if (mask)
1926                         glClear(mask);
1927
1928                 CacheHandler->setColorMask(colorMask);
1929                 CacheHandler->setDepthMask(depthMask);
1930         }
1931
1932
1933         //! Returns an image created from the last rendered frame.
1934         // We want to read the front buffer to get the latest render finished.
1935         // This is not possible under ogl-es, though, so one has to call this method
1936         // outside of the render loop only.
1937         IImage* COpenGL3DriverBase::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target)
1938         {
1939                 if (target==video::ERT_MULTI_RENDER_TEXTURES || target==video::ERT_RENDER_TEXTURE || target==video::ERT_STEREO_BOTH_BUFFERS)
1940                         return 0;
1941
1942                 GLint internalformat = GL_RGBA;
1943                 GLint type = GL_UNSIGNED_BYTE;
1944                 {
1945 //                      glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &internalformat);
1946 //                      glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &type);
1947                         // there's a format we don't support ATM
1948                         if (GL_UNSIGNED_SHORT_4_4_4_4 == type)
1949                         {
1950                                 internalformat = GL_RGBA;
1951                                 type = GL_UNSIGNED_BYTE;
1952                         }
1953                 }
1954
1955                 IImage* newImage = 0;
1956                 if (GL_RGBA == internalformat)
1957                 {
1958                         if (GL_UNSIGNED_BYTE == type)
1959                                 newImage = new CImage(ECF_A8R8G8B8, ScreenSize);
1960                         else
1961                                 newImage = new CImage(ECF_A1R5G5B5, ScreenSize);
1962                 }
1963                 else
1964                 {
1965                         if (GL_UNSIGNED_BYTE == type)
1966                                 newImage = new CImage(ECF_R8G8B8, ScreenSize);
1967                         else
1968                                 newImage = new CImage(ECF_R5G6B5, ScreenSize);
1969                 }
1970
1971                 if (!newImage)
1972                         return 0;
1973
1974                 u8* pixels = static_cast<u8*>(newImage->getData());
1975                 if (!pixels)
1976                 {
1977                         newImage->drop();
1978                         return 0;
1979                 }
1980
1981                 glReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, internalformat, type, pixels);
1982                 testGLError(__LINE__);
1983
1984                 // opengl images are horizontally flipped, so we have to fix that here.
1985                 const s32 pitch = newImage->getPitch();
1986                 u8* p2 = pixels + (ScreenSize.Height - 1) * pitch;
1987                 u8* tmpBuffer = new u8[pitch];
1988                 for (u32 i = 0; i < ScreenSize.Height; i += 2)
1989                 {
1990                         memcpy(tmpBuffer, pixels, pitch);
1991                         memcpy(pixels, p2, pitch);
1992                         memcpy(p2, tmpBuffer, pitch);
1993                         pixels += pitch;
1994                         p2 -= pitch;
1995                 }
1996                 delete [] tmpBuffer;
1997
1998                 // also GL_RGBA doesn't match the internal encoding of the image (which is BGRA)
1999                 if (GL_RGBA == internalformat && GL_UNSIGNED_BYTE == type)
2000                 {
2001                         pixels = static_cast<u8*>(newImage->getData());
2002                         for (u32 i = 0; i < ScreenSize.Height; i++)
2003                         {
2004                                 for (u32 j = 0; j < ScreenSize.Width; j++)
2005                                 {
2006                                         u32 c = *(u32*) (pixels + 4 * j);
2007                                         *(u32*) (pixels + 4 * j) = (c & 0xFF00FF00) |
2008                                                 ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16);
2009                                 }
2010                                 pixels += pitch;
2011                         }
2012                 }
2013
2014                 if (testGLError(__LINE__))
2015                 {
2016                         newImage->drop();
2017                         return 0;
2018                 }
2019                 testGLError(__LINE__);
2020                 return newImage;
2021         }
2022
2023         void COpenGL3DriverBase::removeTexture(ITexture* texture)
2024         {
2025                 CacheHandler->getTextureCache().remove(texture);
2026                 CNullDriver::removeTexture(texture);
2027         }
2028
2029         //! Set/unset a clipping plane.
2030         bool COpenGL3DriverBase::setClipPlane(u32 index, const core::plane3df& plane, bool enable)
2031         {
2032                 if (index >= UserClipPlane.size())
2033                         UserClipPlane.push_back(SUserClipPlane());
2034
2035                 UserClipPlane[index].Plane = plane;
2036                 UserClipPlane[index].Enabled = enable;
2037                 return true;
2038         }
2039
2040         //! Enable/disable a clipping plane.
2041         void COpenGL3DriverBase::enableClipPlane(u32 index, bool enable)
2042         {
2043                 UserClipPlane[index].Enabled = enable;
2044         }
2045
2046         //! Get the ClipPlane Count
2047         u32 COpenGL3DriverBase::getClipPlaneCount() const
2048         {
2049                 return UserClipPlane.size();
2050         }
2051
2052         const core::plane3df& COpenGL3DriverBase::getClipPlane(irr::u32 index) const
2053         {
2054                 if (index < UserClipPlane.size())
2055                         return UserClipPlane[index].Plane;
2056                 else
2057                 {
2058                         _IRR_DEBUG_BREAK_IF(true)       // invalid index
2059                         static const core::plane3df dummy;
2060                         return dummy;
2061                 }
2062         }
2063
2064         core::dimension2du COpenGL3DriverBase::getMaxTextureSize() const
2065         {
2066                 return core::dimension2du(MaxTextureSize, MaxTextureSize);
2067         }
2068
2069         GLenum COpenGL3DriverBase::getGLBlend(E_BLEND_FACTOR factor) const
2070         {
2071                 static GLenum const blendTable[] =
2072                 {
2073                         GL_ZERO,
2074                         GL_ONE,
2075                         GL_DST_COLOR,
2076                         GL_ONE_MINUS_DST_COLOR,
2077                         GL_SRC_COLOR,
2078                         GL_ONE_MINUS_SRC_COLOR,
2079                         GL_SRC_ALPHA,
2080                         GL_ONE_MINUS_SRC_ALPHA,
2081                         GL_DST_ALPHA,
2082                         GL_ONE_MINUS_DST_ALPHA,
2083                         GL_SRC_ALPHA_SATURATE
2084                 };
2085
2086                 return blendTable[factor];
2087         }
2088
2089         bool COpenGL3DriverBase::getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat,
2090                 GLenum& pixelType, void(**converter)(const void*, s32, void*)) const
2091         {
2092                 bool supported = false;
2093                 pixelFormat = GL_RGBA;
2094                 pixelType = GL_UNSIGNED_BYTE;
2095                 *converter = 0;
2096
2097                 switch (format)
2098                 {
2099                 case ECF_A1R5G5B5:
2100                         supported = true;
2101                         pixelFormat = GL_RGBA;
2102                         pixelType = GL_UNSIGNED_SHORT_5_5_5_1;
2103                         *converter = CColorConverter::convert_A1R5G5B5toR5G5B5A1;
2104                         break;
2105                 case ECF_R5G6B5:
2106                         supported = true;
2107                         pixelFormat = GL_RGB;
2108                         pixelType = GL_UNSIGNED_SHORT_5_6_5;
2109                         break;
2110                 case ECF_R8G8B8:
2111                         supported = true;
2112                         pixelFormat = GL_RGB;
2113                         pixelType = GL_UNSIGNED_BYTE;
2114                         break;
2115                 case ECF_A8R8G8B8:
2116                         supported = true;
2117                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_IMG_texture_format_BGRA8888) ||
2118                                 queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_format_BGRA8888) ||
2119                                 queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_APPLE_texture_format_BGRA8888))
2120                         {
2121                                 pixelFormat = GL_BGRA;
2122                         }
2123                         else
2124                         {
2125                                 pixelFormat = GL_RGBA;
2126                                 *converter = CColorConverter::convert_A8R8G8B8toA8B8G8R8;
2127                         }
2128                         pixelType = GL_UNSIGNED_BYTE;
2129                         break;
2130 #ifdef GL_EXT_texture_compression_s3tc
2131                 case ECF_DXT1:
2132                         supported = true;
2133                         pixelFormat = GL_RGBA;
2134                         pixelType = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
2135                         break;
2136                 case ECF_DXT2:
2137                 case ECF_DXT3:
2138                         supported = true;
2139                         pixelFormat = GL_RGBA;
2140                         pixelType = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
2141                         break;
2142                 case ECF_DXT4:
2143                 case ECF_DXT5:
2144                         supported = true;
2145                         pixelFormat = GL_RGBA;
2146                         pixelType = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
2147                         break;
2148 #endif
2149 #ifdef GL_OES_compressed_ETC1_RGB8_texture
2150                 case ECF_ETC1:
2151                         supported = true;
2152                         pixelFormat = GL_RGB;
2153                         pixelType = GL_ETC1_RGB8_OES;
2154                         break;
2155 #endif
2156 #ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available
2157                 case ECF_ETC2_RGB:
2158                         supported = true;
2159                         pixelFormat = GL_RGB;
2160                         pixelType = GL_COMPRESSED_RGB8_ETC2;
2161                         break;
2162 #endif
2163 #ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available
2164                 case ECF_ETC2_ARGB:
2165                         supported = true;
2166                         pixelFormat = GL_RGBA;
2167                         pixelType = GL_COMPRESSED_RGBA8_ETC2_EAC;
2168                         break;
2169 #endif
2170                 case ECF_D16:
2171                         supported = true;
2172                         pixelFormat = GL_DEPTH_COMPONENT;
2173                         pixelType = GL_UNSIGNED_SHORT;
2174                         break;
2175                 case ECF_D32:
2176 #if defined(GL_OES_depth32)
2177                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_depth32))
2178                         {
2179                                 supported = true;
2180                                 pixelFormat = GL_DEPTH_COMPONENT;
2181                                 pixelType = GL_UNSIGNED_INT;
2182                         }
2183 #endif
2184                         break;
2185                 case ECF_D24S8:
2186 #ifdef GL_OES_packed_depth_stencil
2187                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_packed_depth_stencil))
2188                         {
2189                                 supported = true;
2190                                 pixelFormat = GL_DEPTH_STENCIL_OES;
2191                                 pixelType = GL_UNSIGNED_INT_24_8_OES;
2192                         }
2193 #endif
2194                         break;
2195                 case ECF_R8:
2196 #if defined(GL_EXT_texture_rg)
2197                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg))
2198                         {
2199                                 supported = true;
2200                                 pixelFormat = GL_RED_EXT;
2201                                 pixelType = GL_UNSIGNED_BYTE;
2202                         }
2203 #endif
2204                         break;
2205                 case ECF_R8G8:
2206 #if defined(GL_EXT_texture_rg)
2207                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg))
2208                         {
2209                                 supported = true;
2210                                 pixelFormat = GL_RG_EXT;
2211                                 pixelType = GL_UNSIGNED_BYTE;
2212                         }
2213 #endif
2214                         break;
2215                 case ECF_R16:
2216                         break;
2217                 case ECF_R16G16:
2218                         break;
2219                 case ECF_R16F:
2220 #if defined(GL_OES_texture_half_float) && defined(GL_EXT_texture_rg)
2221                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2222                                 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float)
2223                                 )
2224                         {
2225                                 supported = true;
2226                                 pixelFormat = GL_RED_EXT;
2227                                 pixelType = GL_HALF_FLOAT_OES ;
2228                         }
2229 #endif
2230                         break;
2231                 case ECF_G16R16F:
2232 #if defined(GL_OES_texture_half_float) && defined(GL_EXT_texture_rg)
2233                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2234                                 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float)
2235                                 )
2236                         {
2237                                 supported = true;
2238                                 pixelFormat = GL_RG_EXT;
2239                                 pixelType = GL_HALF_FLOAT_OES ;
2240                         }
2241 #endif
2242                         break;
2243                 case ECF_A16B16G16R16F:
2244 #if defined(GL_OES_texture_half_float)
2245                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float))
2246                         {
2247                                 supported = true;
2248                                 pixelFormat = GL_RGBA;
2249                                 pixelType = GL_HALF_FLOAT_OES ;
2250                         }
2251 #endif
2252                         break;
2253                 case ECF_R32F:
2254 #if defined(GL_OES_texture_float) && defined(GL_EXT_texture_rg)
2255                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2256                                 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_float)
2257                                 )
2258                         {
2259                                 supported = true;
2260                                 pixelFormat = GL_RED_EXT;
2261                                 pixelType = GL_FLOAT;
2262                         }
2263 #endif
2264                         break;
2265                 case ECF_G32R32F:
2266 #if defined(GL_OES_texture_float) && defined(GL_EXT_texture_rg)
2267                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2268                                 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_float)
2269                                 )
2270                         {
2271                                 supported = true;
2272                                 pixelFormat = GL_RG_EXT;
2273                                 pixelType = GL_FLOAT;
2274                         }
2275 #endif
2276                         break;
2277                 case ECF_A32B32G32R32F:
2278 #if defined(GL_OES_texture_float)
2279                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float))
2280                         {
2281                                 supported = true;
2282                                 pixelFormat = GL_RGBA;
2283                                 pixelType = GL_FLOAT ;
2284                         }
2285 #endif
2286                         break;
2287                 default:
2288                         break;
2289                 }
2290
2291                 // ES 2.0 says internalFormat must match pixelFormat (chapter 3.7.1 in Spec).
2292                 // Doesn't mention if "match" means "equal" or some other way of matching, but
2293                 // some bug on Emscripten and browsing discussions by others lead me to believe
2294                 // it means they have to be equal. Note that this was different in OpenGL.
2295                 internalFormat = pixelFormat;
2296
2297 #ifdef _IRR_IOS_PLATFORM_
2298                 if (internalFormat == GL_BGRA)
2299                         internalFormat = GL_RGBA;
2300 #endif
2301
2302                 return supported;
2303         }
2304
2305         bool COpenGL3DriverBase::queryTextureFormat(ECOLOR_FORMAT format) const
2306         {
2307                 GLint dummyInternalFormat;
2308                 GLenum dummyPixelFormat;
2309                 GLenum dummyPixelType;
2310                 void (*dummyConverter)(const void*, s32, void*);
2311                 return getColorFormatParameters(format, dummyInternalFormat, dummyPixelFormat, dummyPixelType, &dummyConverter);
2312         }
2313
2314         bool COpenGL3DriverBase::needsTransparentRenderPass(const irr::video::SMaterial& material) const
2315         {
2316                 return CNullDriver::needsTransparentRenderPass(material) || material.isAlphaBlendOperation();
2317         }
2318
2319         const SMaterial& COpenGL3DriverBase::getCurrentMaterial() const
2320         {
2321                 return Material;
2322         }
2323
2324         COpenGL3CacheHandler* COpenGL3DriverBase::getCacheHandler() const
2325         {
2326                 return CacheHandler;
2327         }
2328
2329 } // end namespace
2330 } // end namespace