ecere/gfx/drivers/OpenGL (Android): Fixed blank textures
[sdk] / ecere / src / gfx / drivers / OpenGLDisplayDriver.ec
index 6715480..cd5524b 100644 (file)
-// We were using PBUFFER for alpha compositing on Linux before, but it does not seem to work, nor be required anymore.
-// #define USEPBUFFER
+// #define DIAGNOSTICS
 
 namespace gfx::drivers;
 
-// OpenGL Extensions
-#if defined(__unix__) || defined(__APPLE__)
+#if !defined(_GLES)  // OpenGL ES 1
+   #define SHADERS
+#endif
 
-#if !defined(__MINGW32__)
-#define GL_GLEXT_PROTOTYPES
+#if !defined(__ANDROID__) && !defined(__EMSCRIPTEN__) && !defined(__ODROID__)
+#  if defined(SHADERS)
+#     include "gl_core_3_3.h"
+#  else
+#     include "gl_compat_4_4.h"
+#  endif
 #endif
 
-#ifdef ECERE_MINIGLX
+#if defined(__ANDROID__) || defined(__ODROID__)
+import "egl"
+#endif
 
-//#include <GL/miniglx.h>
+import "glab"
+import "immediate"
+import "matrixStack"
+import "shading"
 
-#else
+#define GL_BGRA_EXT  0x80E1
 
-#if defined(__ANDROID__)
+#ifdef SHADERS
 
-#else
+#undef glEnableClientState
+#undef glDisableClientState
+#undef GL_VERTEX_ARRAY
+#undef GL_NORMAL_ARRAY
+#undef GL_TEXTURE_COORD_ARRAY
+#undef GL_COLOR_ARRAY
 
-#define property _property
-#define new _new
-#define class _class
+#define glEnableClientState      glEnableVertexAttribArray
+#define glDisableClientState     glDisableVertexAttribArray
+#define GL_VERTEX_ARRAY          GLBufferContents::vertex
+#define GL_NORMAL_ARRAY          GLBufferContents::normal
+#define GL_TEXTURE_COORD_ARRAY   GLBufferContents::texCoord
+#define GL_COLOR_ARRAY           GLBufferContents::color
 
-#define Window    X11Window
-#define Cursor    X11Cursor
-#define Font      X11Font
-#define Display   X11Display
-#define Time      X11Time
-#define KeyCode   X11KeyCode
-#define Picture   X11Picture
-#define uint _uint
+#endif
 
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-#include <GL/glx.h>
-#include <X11/extensions/XShm.h>
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#include <X11/extensions/Xrender.h>
-#include <X11/extensions/shape.h>
+// We were using PBUFFER for alpha compositing on Linux before, but it does not seem to work, nor be required anymore.
+// #define USEPBUFFER
+#if defined(__unix__) || defined(__APPLE__)
 
-#undef Window
-#undef Cursor
-#undef Font
-#undef Display
-#undef Time
-#undef KeyCode
-#undef Picture
-#undef uint
-#undef new
-#undef property
-#undef class
+   #if !defined(__MINGW32__)
+      #define GL_GLEXT_PROTOTYPES
+   #endif
 
-#endif
+   #define pointer _pointer
+
+
+   #if !defined(__ANDROID__) && !defined(__ODROID__) && !defined(__EMSCRIPTEN__)
+
+      #define property _property
+      #define new _new
+      #define class _class
+
+      #define Window    X11Window
+      #define Cursor    X11Cursor
+      #define Font      X11Font
+      #define Display   X11Display
+      #define Time      X11Time
+      #define KeyCode   X11KeyCode
+      #define Picture   X11Picture
+      #define uint _uint
+
+      #include <X11/Xlib.h>
+      #include <X11/Xutil.h>
+      #include <GL/glx.h>
+      #include <X11/extensions/XShm.h>
+      #include <sys/ipc.h>
+      #include <sys/shm.h>
+      #include <X11/extensions/Xrender.h>
+      #include <X11/extensions/shape.h>
+
+      #undef Window
+      #undef Cursor
+      #undef Font
+      #undef Display
+      #undef Time
+      #undef KeyCode
+      #undef Picture
+      #undef uint
+      #undef new
+      #undef property
+      #undef class
 
-#endif
+   #endif
 
 #endif
 
 #if defined(__APPLE__)
-#include <OpenGl/gl.h>
+   #include <OpenGl/gl.h>
 #endif
 
 #if defined(__WIN32__) || defined(__unix__) || defined(__APPLE__)
 
-#if defined(__WIN32__)
-#define WIN32_LEAN_AND_MEAN
-#undef _WIN32_WINNT
-#define _WIN32_WINNT 0x0500
-#define String Sting_
-#include <windows.h>
-#undef String
+   #if defined(__WIN32__)
+      //#define WIN32_LEAN_AND_MEAN
+      #undef _WIN32_WINNT
+      #define _WIN32_WINNT 0x0502
+      #define String Sting_
+      #include <windows.h>
+      #undef String
+   #endif
+
+   #if defined(__ANDROID__) || defined(__ODROID__)
+      #if defined(__ODROID__) && !defined(_GLES)
+         #define _GLES
+      #endif
+
+      #define uint _uint
+      #define property _property
+      #define new _new
+      #define class _class
+      #define Window    X11Window
+      #define Cursor    X11Cursor
+      #define Font      X11Font
+      #define Display   X11Display
+      #define Time      X11Time
+      #define KeyCode   X11KeyCode
+      #define Picture   X11Picture
+      #define Bool      X11Bool
+
+      #include <GLES/gl.h>
+
+      #undef Bool
+      #undef Picture
+      #undef Window
+      #undef Cursor
+      #undef Font
+      #undef Display
+      #undef Time
+      #undef KeyCode
+      #undef uint
+      #undef new
+      #undef property
+      #undef class
+
+   #elif defined(__EMSCRIPTEN__)
+#if !defined(_GLES2)
+      #define _GLES2
 #endif
+      // #define _GLES
 
-#if defined(__ANDROID__)
+      #define property _property
+      #define uint _uint
 
-#include <GLES/gl.h>
-#include <EGL/egl.h>
+      //#include <GL/gl.h>
+      //#include <GLES/gl.h>
+      #include <GLES2/gl2.h>
 
-#else
+      #include <emscripten/emscripten.h>
+      #include <emscripten/html5.h>
 
-#include <GL/gl.h>
-#include <GL/glext.h>
+      #undef property
+      #undef uint
 
-#endif
+   #else
+      #include <GL/gl.h>
+   #endif
 
-import "Display"
+   #undef pointer
 
-#if defined(__unix__) || defined(__APPLE__)
+   import "Display"
 
-#ifndef __ANDROID__
-import "XInterface"
-#endif
+   #if defined(__unix__) || defined(__APPLE__)
 
-#endif
+   #if !defined(__ANDROID__) && !defined(__ODROID__) && !defined(__EMSCRIPTEN__)
+   import "XInterface"
+   #endif
 
-static double nearPlane = 1;
+   #endif
 
-#define glLoadMatrix glLoadMatrixd
-#define glMultMatrix glMultMatrixd
-#define glGetMatrix  glGetDoublev
-#define glTranslate glTranslated
-#define glScale glScaled
+   #define glLoadMatrix glLoadMatrixd
+   #define glMultMatrix glMultMatrixd
+   #define glGetMatrix  glGetDoublev
+   #define glTranslate glTranslated
+   #define glScale glScaled
 
 /*
 #define glVertex3v glVertex3dv
@@ -145,904 +223,181 @@ static double nearPlane = 1;
 #define GL_MULTISAMPLE_ARB             0x809D
 
 #if defined(__WIN32__)
-
-#define WGL_SAMPLE_BUFFERS_ARB              0x2041
-#define WGL_SAMPLES_ARB                     0x2042
-
-#define  WGL_WGLEXT_VERSION   1
-#define  WGL_FRONT_COLOR_BUFFER_BIT_ARB   0x00000001
-#define  WGL_BACK_COLOR_BUFFER_BIT_ARB   0x00000002
-#define  WGL_DEPTH_BUFFER_BIT_ARB   0x00000004
-#define  WGL_STENCIL_BUFFER_BIT_ARB   0x00000008
-#define  WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
-#define  WGL_DRAW_TO_WINDOW_ARB   0x2001
-#define  WGL_DRAW_TO_BITMAP_ARB   0x2002
-#define  WGL_ACCELERATION_ARB   0x2003
-#define  WGL_NEED_PALETTE_ARB   0x2004
-#define  WGL_NEED_SYSTEM_PALETTE_ARB   0x2005
-#define  WGL_SWAP_LAYER_BUFFERS_ARB   0x2006
-#define  WGL_SWAP_METHOD_ARB   0x2007
-#define  WGL_NUMBER_OVERLAYS_ARB   0x2008
-#define  WGL_NUMBER_UNDERLAYS_ARB   0x2009
-#define  WGL_TRANSPARENT_ARB   0x200A
-#define  WGL_TRANSPARENT_RED_VALUE_ARB   0x2037
-#define  WGL_TRANSPARENT_GREEN_VALUE_ARB   0x2038
-#define  WGL_TRANSPARENT_BLUE_VALUE_ARB   0x2039
-#define  WGL_TRANSPARENT_ALPHA_VALUE_ARB   0x203A
-#define  WGL_TRANSPARENT_INDEX_VALUE_ARB   0x203B
-#define  WGL_SHARE_DEPTH_ARB   0x200C
-#define  WGL_SHARE_STENCIL_ARB   0x200D
-#define  WGL_SHARE_ACCUM_ARB   0x200E
-#define  WGL_SUPPORT_GDI_ARB   0x200F
-#define  WGL_SUPPORT_OPENGL_ARB   0x2010
-#define  WGL_DOUBLE_BUFFER_ARB   0x2011
-#define  WGL_STEREO_ARB   0x2012
-#define  WGL_PIXEL_TYPE_ARB   0x2013
-#define  WGL_COLOR_BITS_ARB   0x2014
-#define  WGL_RED_BITS_ARB   0x2015
-#define  WGL_RED_SHIFT_ARB   0x2016
-#define  WGL_GREEN_BITS_ARB   0x2017
-#define  WGL_GREEN_SHIFT_ARB   0x2018
-#define  WGL_BLUE_BITS_ARB   0x2019
-#define  WGL_BLUE_SHIFT_ARB   0x201A
-#define  WGL_ALPHA_BITS_ARB   0x201B
-#define  WGL_ALPHA_SHIFT_ARB   0x201C
-#define  WGL_ACCUM_BITS_ARB   0x201D
-#define  WGL_ACCUM_RED_BITS_ARB   0x201E
-#define  WGL_ACCUM_GREEN_BITS_ARB   0x201F
-#define  WGL_ACCUM_BLUE_BITS_ARB   0x2020
-#define  WGL_ACCUM_ALPHA_BITS_ARB   0x2021
-#define  WGL_DEPTH_BITS_ARB   0x2022
-#define  WGL_STENCIL_BITS_ARB   0x2023
-#define  WGL_AUX_BUFFERS_ARB   0x2024
-#define  WGL_NO_ACCELERATION_ARB   0x2025
-#define  WGL_GENERIC_ACCELERATION_ARB   0x2026
-#define  WGL_FULL_ACCELERATION_ARB   0x2027
-#define  WGL_SWAP_EXCHANGE_ARB   0x2028
-#define  WGL_SWAP_COPY_ARB   0x2029
-#define  WGL_SWAP_UNDEFINED_ARB   0x202A
-#define  WGL_TYPE_RGBA_ARB   0x202B
-#define  WGL_TYPE_COLORINDEX_ARB   0x202C
-#define  ERROR_INVALID_PIXEL_TYPE_ARB   0x2043
-#define  ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB   0x2054
-#define  WGL_DRAW_TO_PBUFFER_ARB   0x202D
-#define  WGL_MAX_PBUFFER_PIXELS_ARB   0x202E
-#define  WGL_MAX_PBUFFER_WIDTH_ARB   0x202F
-#define  WGL_MAX_PBUFFER_HEIGHT_ARB   0x2030
-#define  WGL_PBUFFER_LARGEST_ARB   0x2033
-#define  WGL_PBUFFER_WIDTH_ARB   0x2034
-#define  WGL_PBUFFER_HEIGHT_ARB   0x2035
-#define  WGL_PBUFFER_LOST_ARB   0x2036
-#define  ERROR_INVALID_PIXEL_TYPE_EXT   0x2043
-#define  WGL_NUMBER_PIXEL_FORMATS_EXT   0x2000
-#define  WGL_DRAW_TO_WINDOW_EXT   0x2001
-#define  WGL_DRAW_TO_BITMAP_EXT   0x2002
-#define  WGL_ACCELERATION_EXT   0x2003
-#define  WGL_NEED_PALETTE_EXT   0x2004
-#define  WGL_NEED_SYSTEM_PALETTE_EXT   0x2005
-#define  WGL_SWAP_LAYER_BUFFERS_EXT   0x2006
-#define  WGL_SWAP_METHOD_EXT   0x2007
-#define  WGL_NUMBER_OVERLAYS_EXT   0x2008
-#define  WGL_NUMBER_UNDERLAYS_EXT   0x2009
-#define  WGL_TRANSPARENT_EXT   0x200A
-#define  WGL_TRANSPARENT_VALUE_EXT   0x200B
-#define  WGL_SHARE_DEPTH_EXT   0x200C
-#define  WGL_SHARE_STENCIL_EXT   0x200D
-#define  WGL_SHARE_ACCUM_EXT   0x200E
-#define  WGL_SUPPORT_GDI_EXT   0x200F
-#define  WGL_SUPPORT_OPENGL_EXT   0x2010
-#define  WGL_DOUBLE_BUFFER_EXT   0x2011
-#define  WGL_STEREO_EXT   0x2012
-#define  WGL_PIXEL_TYPE_EXT   0x2013
-#define  WGL_COLOR_BITS_EXT   0x2014
-#define  WGL_RED_BITS_EXT   0x2015
-#define  WGL_RED_SHIFT_EXT   0x2016
-#define  WGL_GREEN_BITS_EXT   0x2017
-#define  WGL_GREEN_SHIFT_EXT   0x2018
-#define  WGL_BLUE_BITS_EXT   0x2019
-#define  WGL_BLUE_SHIFT_EXT   0x201A
-#define  WGL_ALPHA_BITS_EXT   0x201B
-#define  WGL_ALPHA_SHIFT_EXT   0x201C
-#define  WGL_ACCUM_BITS_EXT   0x201D
-#define  WGL_ACCUM_RED_BITS_EXT   0x201E
-#define  WGL_ACCUM_GREEN_BITS_EXT   0x201F
-#define  WGL_ACCUM_BLUE_BITS_EXT   0x2020
-#define  WGL_ACCUM_ALPHA_BITS_EXT   0x2021
-#define  WGL_DEPTH_BITS_EXT   0x2022
-#define  WGL_STENCIL_BITS_EXT   0x2023
-#define  WGL_AUX_BUFFERS_EXT   0x2024
-#define  WGL_NO_ACCELERATION_EXT   0x2025
-#define  WGL_GENERIC_ACCELERATION_EXT   0x2026
-#define  WGL_FULL_ACCELERATION_EXT   0x2027
-#define  WGL_SWAP_EXCHANGE_EXT   0x2028
-#define  WGL_SWAP_COPY_EXT   0x2029
-#define  WGL_SWAP_UNDEFINED_EXT   0x202A
-#define  WGL_TYPE_RGBA_EXT   0x202B
-#define  WGL_TYPE_COLORINDEX_EXT   0x202C
-#define  WGL_DRAW_TO_PBUFFER_EXT   0x202D
-#define  WGL_MAX_PBUFFER_PIXELS_EXT   0x202E
-#define  WGL_MAX_PBUFFER_WIDTH_EXT   0x202F
-#define  WGL_MAX_PBUFFER_HEIGHT_EXT   0x2030
-#define  WGL_OPTIMAL_PBUFFER_WIDTH_EXT   0x2031
-#define  WGL_OPTIMAL_PBUFFER_HEIGHT_EXT   0x2032
-#define  WGL_PBUFFER_LARGEST_EXT   0x2033
-#define  WGL_PBUFFER_WIDTH_EXT   0x2034
-#define  WGL_PBUFFER_HEIGHT_EXT   0x2035
-#define  WGL_DEPTH_FLOAT_EXT   0x2040
-#define  WGL_SAMPLE_BUFFERS_3DFX   0x2060
-#define  WGL_SAMPLES_3DFX   0x2061
-#define  WGL_SAMPLE_BUFFERS_EXT   0x2041
-#define  WGL_SAMPLES_EXT   0x2042
-#define  WGL_GENLOCK_SOURCE_MULTIVIEW_I3D   0x2044
-#define  WGL_GENLOCK_SOURCE_EXTENAL_SYNC_I3D   0x2045
-#define  WGL_GENLOCK_SOURCE_EXTENAL_FIELD_I3D   0x2046
-#define  WGL_GENLOCK_SOURCE_EXTENAL_TTL_I3D   0x2047
-#define  WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D   0x2048
-#define  WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D   0x2049
-#define  WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D   0x204A
-#define  WGL_GENLOCK_SOURCE_EDGE_RISING_I3D   0x204B
-#define  WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D   0x204C
-#define  WGL_GAMMA_TABLE_SIZE_I3D   0x204E
-#define  WGL_GAMMA_EXCLUDE_DESKTOP_I3D   0x204F
-#define  WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D   0x2050
-#define  WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D   0x2051
-#define  WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D   0x2052
-#define  WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D   0x2053
-#define  WGL_ARB_buffer_region   1
-#define  WGL_ARB_extensions_string   1
-#define  WGL_ARB_pixel_format   1
-#define  WGL_ARB_make_current_read   1
-#define  WGL_ARB_pbuffer   1
-#define  WGL_EXT_display_color_table   1
-#define  WGL_EXT_extensions_string   1
-#define  WGL_EXT_make_current_read   1
-#define  WGL_EXT_pbuffer   1
-#define  WGL_EXT_pixel_format   1
-#define  WGL_EXT_swap_control   1
-#define  WGL_WGL_EXT_depth_float   1
-#define  WGL_WGL_3DFX_multisample   1
-#define  WGL_WGL_EXT_multisample   1
-#define  WGL_NV_allocate_memory   1
-
-/*
-typedef void (APIENTRY * PFNGLACTIVETEXTUREARBPROC) (GLenum target);
-typedef void (APIENTRY * PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t);
-typedef void (APIENTRY * PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum target);
-typedef void (APIENTRY * PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count);
-typedef void (APIENTRY * PFNGLUNLOCKARRAYSEXTPROC) (void);
-*/
-
-/*
-typedef int (APIENTRY * PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
-typedef int (APIENTRY * PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
-typedef int (APIENTRY * PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
-typedef int (APIENTRY * PFNGLBUFFERDATAARBPROC) (GLenum target, int size, const GLvoid *data, GLenum usage);
-*/
-typedef int (APIENTRY * PFNWGLCHOOSEPIXELFORMATARBPROC) ();
-typedef void * (APIENTRY * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
-typedef HDC (APIENTRY * PFNWGLGETPBUFFERDCARBPROC) (void * hPbuffer);
-typedef int (APIENTRY * PFNWGLRELEASEPBUFFERDCARBPROC) (void * hPbuffer, HDC hDC);
-typedef BOOL (APIENTRY * PFNWGLDESTROYPBUFFERARBPROC) (void * hPbuffer);
-typedef BOOL (APIENTRY * PFNWGLQUERYPBUFFERARBPROC) (void * hPbuffer, int iAttribute, int *piValue);
-
-static PFNGLMAPBUFFERARBPROC glMapBufferARB = null;
-static PFNGLUNMAPBUFFERARBPROC glUnmapBufferARB = null;
-static PFNGLACTIVETEXTUREARBPROC glActiveTextureARB = null;
-static PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB = null;
-static PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTextureARB = null;
-static PFNGLLOCKARRAYSEXTPROC glLockArraysEXT = null;
-static PFNGLUNLOCKARRAYSEXTPROC glUnlockArraysEXT = null;
-static PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate = null;
-
-static PFNGLGENBUFFERSARBPROC glGenBuffersARB = null;
-static PFNGLBINDBUFFERARBPROC glBindBufferARB = null;
-static PFNGLBUFFERDATAARBPROC glBufferDataARB = null;
-static PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB = null;
-static PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = null;
-static PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = null;
-static PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB = null;
-static PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB = null;
-static PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB = null;
-static PFNWGLDESTROYPBUFFERARBPROC wglDestroyPbufferARB = null;
-static PFNWGLRELEASEPBUFFERDCARBPROC wglReleasePbufferDCARB = null;
-static PFNWGLBINDTEXIMAGEARBPROC wglBindTexImageARB = null;
-static PFNWGLRELEASETEXIMAGEARBPROC wglReleaseTexImageARB = null;
-
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglSwapIntervalEXT (int);
-extern int WINAPI wglGetSwapIntervalEXT (void);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
-typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
-
-static PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL;
+   #include "wglDefs.h"
+
+   typedef void (APIENTRY * PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count);
+   typedef void (APIENTRY * PFNGLUNLOCKARRAYSEXTPROC) (void);
+
+   static PFNGLLOCKARRAYSEXTPROC glLockArraysEXT = null;
+   static PFNGLUNLOCKARRAYSEXTPROC glUnlockArraysEXT = null;
+
+   static PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = null;
+   static PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = null;
+   static PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB = null;
+   static PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB = null;
+   static PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB = null;
+   static PFNWGLDESTROYPBUFFERARBPROC wglDestroyPbufferARB = null;
+   static PFNWGLRELEASEPBUFFERDCARBPROC wglReleasePbufferDCARB = null;
+   static PFNWGLBINDTEXIMAGEARBPROC wglBindTexImageARB = null;
+   static PFNWGLRELEASETEXIMAGEARBPROC wglReleaseTexImageARB = null;
+   static PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = null;
+   static PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = null;
 
 #else
 
-#if defined(__ANDROID__)
-
-// Our own matrix stack
-static Matrix matrixStack[3][32];
-static int matrixIndex[3];
-static int curStack = 0;
-
-// OpenGL ES Porting Kit
-
-#define glBindFramebuffer        glBindFramebufferOES
-#define glBindRenderbuffer       glBindRenderbufferOES
-#define GL_FRAMEBUFFER           GL_FRAMEBUFFER_OES
-#define GL_RENDERBUFFER          GL_RENDERBUFFER_OES
-#define glFramebufferTexture2D   glFramebufferTexture2DOES
-#define GL_COLOR_ATTACHMENT0     GL_COLOR_ATTACHMENT0_OES
-#define glGenFramebuffers        glGenFramebuffersOES
-#define glGenRenderbuffers       glGenRenderbuffersOES
-#define glDeleteFramebuffers     glDeleteFramebuffersOES
-#define glDeleteRenderbuffers    glDeleteRenderbuffersOES
-
-#define GL_POLYGON_STIPPLE 0xFFFF
-#define GL_LINE_STIPPLE 0xFFFF
-#define GL_LINE 0xFFFF
-#define GL_FILL 0xFFFF
-#define GL_ALL_ATTRIB_BITS 0xFFFF
-#define GL_LIGHT_MODEL_LOCAL_VIEWER 0xFFFF
-#define glDrawElementsi(type, count, start)  glDrawElements(type, count, GL_UNSIGNED_SHORT, start)
-
-#define GL_UNSIGNED_INT                         0x1405
-#define GL_DOUBLE                               0x140A
-
-#define GL_POLYGON      9
-#define GL_QUADS        7
-
-#define glBufferDatai         glesBufferDatai
-#define glBufferDatad         glesBufferDatad
-#define glVertexPointeri      glesVertexPointeri
-#define glVertexPointerd      glesVertexPointerd
-
-#define glRecti               glesRecti
-#define glBegin               glesBegin
-#define glTexCoord2i          glesTexCoord2i
-#define glVertex2i            glesVertex2i
-#define glTexCoord2d          glesTexCoord2d
-#define glVertex2d            glesVertex2d
-#define glTexCoord2f          glesTexCoord2f
-#define glVertex2f            glesVertex2f
-#define glEnd                 glesEnd
-#define glColor3f             glesColor3f
-#define glColor4ub            glesColor4ub
-#define glColor4fv            glesColor4fv
-#define glLineStipple         glesLineStipple
-#define glNormal3fv           glesNormal3fv
-#define glTexCoord2fv         glesTexCoord2fv
-#define glColorMaterial       glesColorMaterial
-
-#define glLoadMatrixd         glesLoadMatrixd
-#define glMultMatrixd         glesMultMatrixd
-#define glFrustum             glesFrustum
-#define glOrtho               glesOrtho
-#define glScaled              glesScaled
-#define glTranslated          glesTranslated
-#define glRotated             glesRotated
-#define glVertex3d            glesVertex3d
-#define glVertex3f            glesVertex3f
-#define glVertex3fv           glesVertex3fv
-#define glLightModeli         glesLightModeli
-
-#define APIENTRY
-//#define GL_QUADS              0
-#define GL_QUAD_STRIP         0
-//#define GL_DOUBLE             0
-//#define GL_UNSIGNED_INT       0
-//#define GL_FILL               0
-//#define GL_LINE               0
-//#define GL_LINE_STIPPLE       0
-#define GL_BGRA_EXT           0
-#define GL_UNPACK_ROW_LENGTH  0
-#define GL_UNPACK_SKIP_PIXELS 0
-#define GL_UNPACK_SKIP_ROWS   0
-#define GL_RGBA8              0
-#define GL_PACK_ROW_LENGTH    0
-#define GL_PACK_SKIP_ROWS     0
-#define GL_PACK_SKIP_PIXELS   0
-
-static EGLDisplay eglDisplay;
-static EGLSurface eglSurface;
-static EGLContext eglContext;
-static int eglWidth, eglHeight;
-
-static bool egl_init_display(ANativeWindow* window)
-{
-   const EGLint attribs[] =
-   {
-      EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
-      EGL_BLUE_SIZE, 8,
-      EGL_GREEN_SIZE, 8,
-      EGL_RED_SIZE, 8,
-      EGL_DEPTH_SIZE, 24,
-      /*EGL_SAMPLE_BUFFERS, 1,
-      EGL_SAMPLES, 0, //2,*/
-      EGL_NONE
-   };
-   EGLint w, h, dummy, format;
-   EGLint numConfigs;
-   EGLConfig config;
-   EGLSurface surface;
-   EGLContext context;
-
-   EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
-   eglInitialize(display, 0, 0);
-   eglChooseConfig(display, attribs, &config, 1, &numConfigs);
-   eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
-
-   surface = eglCreateWindowSurface(display, config, window, null);
-   context = eglCreateContext(display, config, null, null);
-
-   if(!eglMakeCurrent(display, surface, surface, context))
-      return false;
-
-   eglQuerySurface(display, surface, EGL_WIDTH, &w);
-   eglQuerySurface(display, surface, EGL_HEIGHT, &h);
-
-   eglDisplay = display;
-   eglContext = context;
-   eglSurface = surface;
-   eglWidth = w;
-   eglHeight = h;
-
-   glEnableClientState(GL_VERTEX_ARRAY);
-   /*
-   // Initialize GL state.
-   glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
-   glEnable(GL_CULL_FACE);
-   glShadeModel(GL_SMOOTH);
-   glDisable(GL_DEPTH_TEST);
-   */
-   glDisable(GL_CULL_FACE);
-   glDisable(GL_DEPTH_TEST);
-
-   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-   glEnable(GL_BLEND);
-
-   matrixStack[0][0].Identity();
-   matrixStack[1][0].Identity();
-   matrixStack[2][0].Identity();
-
-   glesMatrixMode(GL_MODELVIEW);
-   glScaled(1.0, 1.0, -1.0);
-   glesMatrixMode(GL_PROJECTION);
-   glShadeModel(GL_FLAT);
-
-   glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
-   glFogi(GL_FOG_MODE, GL_EXP);
-   glFogf(GL_FOG_DENSITY, 0);
-   glEnable(GL_NORMALIZE);
-   glDepthFunc(GL_LESS);
-   glClearDepth(1.0);
-   glDisable(GL_MULTISAMPLE_ARB);
-
-   glViewport(0,0,w,h);
-   glesLoadIdentity();
-   glOrtho(0,w,h,0,0.0,1.0);
-
-   currentVertexBuffer = 0;
-   return true;
-}
-
-static void egl_term_display()
-{
-   if(stippleTexture)
-   {
-      glDeleteTextures(1, (int *)&stippleTexture);
-      stippleTexture = 0;
-   }
-   if(eglDisplay != EGL_NO_DISPLAY)
-   {
-      eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
-      if(eglContext != EGL_NO_CONTEXT)
-         eglDestroyContext(eglDisplay, eglContext);
-      if(eglSurface != EGL_NO_SURFACE)
-         eglDestroySurface(eglDisplay, eglSurface);
-      eglTerminate(eglDisplay);
-   }
-   eglDisplay = EGL_NO_DISPLAY;
-   eglContext = EGL_NO_CONTEXT;
-   eglSurface = EGL_NO_SURFACE;
-}
-
-// OpenGL Immediate Mode Porting Kit
-static int beginCount;
-static int vertexCount;
-static int normalCount;
-static float *vertexPointer;
-static float *normalPointer;
-static GLenum beginMode;
-static unsigned int beginBufferSize, normalBufferSize;
-static int numVertexCoords = 2;
-
-void glesRecti(int a, int b, int c, int d)
-{
-   glBegin(GL_QUADS);
-   glVertex2i(a, b);
-   glVertex2i(a, d);
-   glVertex2i(c, d);
-   glVertex2i(c, b);
-   glEnd();
-}
-
-void glesBegin(GLenum mode)
-{
-   beginMode = mode;
-   beginCount = 0;
-   vertexCount = 0;
-   if(!vertexPointer)
-   {
-      normalBufferSize = beginBufferSize = 1024;  // default number of vertices
-      vertexPointer = new float[beginBufferSize * 5];
-      normalPointer = new float[normalBufferSize * 3];
-   }
-}
-
-void glesTexCoord2f(float x, float y)
-{
-   int count = vertexCount;
-
-   if(vertexCount + numVertexCoords > beginBufferSize)
-   {
-      beginBufferSize = beginBufferSize + beginBufferSize/2;
-      vertexPointer = renew vertexPointer float[beginBufferSize * 5];
-   }
-
-   vertexPointer[count*(2+numVertexCoords)  ] = x;
-   vertexPointer[count*(2+numVertexCoords)+1] = y;
-   count++;
-
-   if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
-   {
-      vertexPointer[count*(2+numVertexCoords)  ] = vertexPointer[(count-4)*(2+numVertexCoords)];
-      vertexPointer[count*(2+numVertexCoords)+1] = vertexPointer[(count-4)*(2+numVertexCoords)+1];
-      count++;
-      vertexPointer[count*(2+numVertexCoords)  ] = vertexPointer[(count-3)*(2+numVertexCoords)];
-      vertexPointer[count*(2+numVertexCoords)+1] = vertexPointer[(count-3)*(2+numVertexCoords)+1];
-      count++;
-   }
-}
-void glesTexCoord2i(int x, int y)       { glesTexCoord2f((float)x, (float)y); }
-void glesTexCoord2d(double x, double y) { glesTexCoord2f((float)x, (float)y); }
-void glesTexCoord2fv(float * a)         { glesTexCoord2f(a[0], a[1]); }
-
-void glesVertex2f(float x, float y)
-{
-   numVertexCoords = 2;
-   if(vertexCount + 4 > beginBufferSize)
-   {
-      beginBufferSize = beginBufferSize + beginBufferSize/2;
-      vertexPointer = renew vertexPointer float[beginBufferSize * 5];
-   }
-
-   vertexPointer[vertexCount*4+2] = x;
-   vertexPointer[vertexCount*4+3] = y;
-   vertexCount++;
-
-   if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
-   {
-      vertexPointer[vertexCount*4+2] = vertexPointer[(vertexCount-4)*4+2];
-      vertexPointer[vertexCount*4+3] = vertexPointer[(vertexCount-4)*4+3];
-      vertexCount++;
-      vertexPointer[vertexCount*4+2] = vertexPointer[(vertexCount-3)*4+2];
-      vertexPointer[vertexCount*4+3] = vertexPointer[(vertexCount-3)*4+3];
-      vertexCount++;
-   }
-   beginCount++;
-}
-void glesVertex2i(int x, int y)         { glesVertex2f((float)x, (float)y); }
-void glesVertex2d(double x, double y)   { glesVertex2f((float)x, (float)y); }
-
-void glesEnd(void)
-{
-   int mode = beginMode;
-   if(mode == GL_QUADS)        mode = GL_TRIANGLES;
-   else if(mode == GL_POLYGON) mode = GL_TRIANGLE_FAN;
-   GLSelectVBO(0);
-   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-   glTexCoordPointer(numVertexCoords, GL_FLOAT, (numVertexCoords+2)*sizeof(float),vertexPointer);
-   glVertexPointer  (numVertexCoords, GL_FLOAT, (numVertexCoords+2)*sizeof(float),vertexPointer+2);
-   if(normalCount && normalCount == vertexCount)
-   {
-      glEnableClientState(GL_NORMAL_ARRAY);
-      glNormalPointer  (GL_FLOAT, 3*sizeof(float),normalPointer);
-   }
-
-   glDrawArrays(mode, 0, vertexCount);
-   if(normalCount)
-      glDisableClientState(GL_NORMAL_ARRAY);
-   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-   normalCount = 0;
-}
-
-// Vertex Pointer
-static float *floatVPBuffer = null;
-static short *shortVPBuffer = null;
-static unsigned int shortVPSize = 0, floatVPSize = 0;
-
-// Buffer Data
-//static float *floatVPBuffer = null;  // For floats we reuse floatVPBuffer
-static unsigned short *shortBDBuffer = null;
-static unsigned int shortBDSize = 0/*, floatVPSize = 0*/;
-
-void glesVertexPointeri(int numCoords, int stride, int *pointer, int numVertices)
-{
-   if(pointer)
-   {
-      int i;
-      if(numVertices*numCoords > shortVPSize)
-      {
-         shortVPSize = numVertices*numCoords;
-         shortVPBuffer = renew shortVPBuffer short[shortVPSize];
-      }
-      for(i = 0; i < numVertices*numCoords; i++)
-         shortVPBuffer[i] = (short)pointer[i];
-      glVertexPointer(numCoords, GL_SHORT, stride, shortVPBuffer);
-   }
-   else
-      glVertexPointer(numCoords, GL_SHORT, stride, 0);
-}
-
-void glesVertexPointerd(int numCoords, int stride, double *pointer, int numVertices)
-{
-   if(pointer)
-   {
-      int i;
-      if(numVertices*numCoords > floatVPSize)
-      {
-         floatVPSize = numVertices*numCoords;
-         floatVPBuffer = renew floatVPBuffer float[floatVPSize];
-      }
-      for(i = 0; i < numVertices*numCoords; i++)
-         floatVPBuffer[i] = (float)pointer[i];
-      glVertexPointer(numCoords, GL_FLOAT, stride, floatVPBuffer);
-   }
-   else
-      glVertexPointer(numCoords, GL_FLOAT, stride, 0);
-}
-
-void glesTexReuseIntVP(int numCoords)
-{
-   glTexCoordPointer(numCoords, GL_SHORT, 0, floatVPBuffer);
-}
-
-void glesTexReuseDoubleVP(int numCoords)
-{
-   glTexCoordPointer(numCoords, GL_FLOAT, 0, floatVPBuffer);
-}
-
-void glesColor3f( float r, float g, float b )
-{
-   glColor4f(r, g, b, 1.0f);
-}
-
-void glesColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
-{
-   glColor4f(r/255.0f, g/255.0f, b/255.0f, a/255.0f);
-}
-
-void glesColor4fv(float * a)
-{
-   glColor4f(a[0], a[1], a[2], a[3]);
-}
-
-void glesBufferDatad(int target, int size, void * data, int usage)
-{
-   int numElems = size/sizeof(double);
-   double * dblPtr = (double *)data;
-   int i;
-   if (numElems > floatVPSize)
-   {
-      floatVPSize = numElems;
-      floatVPBuffer = renew floatVPBuffer float[floatVPSize];
-   }
-   for (i=0; i< numElems; i++)
-      floatVPBuffer[i] = (float)dblPtr[i];
-
-   glBufferData(target, numElems*sizeof(float), floatVPBuffer, usage);
-}
-
-void glesBufferDatai(int target, int size, void * data, int usage)
-{
-   int numElems = size/sizeof(unsigned int);
-   unsigned int * pointer = (unsigned int *)data;
-   int i;
-   if (numElems > shortBDSize)
-   {
-      shortBDSize = numElems;
-      shortBDBuffer = renew shortBDBuffer uint16[shortBDSize];
-   }
-   for (i=0; i< numElems; i++)
-      shortBDBuffer[i] = (unsigned short)pointer[i];
-
-   glBufferData(target, numElems*sizeof(unsigned short), shortBDBuffer, usage);
-}
-
-// *** Our Custom Matrix Stack ***
-
-static void LoadCurMatrix()
-{
-   double * i = matrixStack[curStack][matrixIndex[curStack]].array;
-   float m[16] =
-   {
-      (float)i[0],(float)i[1],(float)i[2],(float)i[3],
-      (float)i[4],(float)i[5],(float)i[6],(float)i[7],
-      (float)i[8],(float)i[9],(float)i[10],(float)i[11],
-      (float)i[12],(float)i[13],(float)i[14],(float)i[15]
-   };
-   glLoadMatrixf(m);
-}
-
-void glesLoadIdentity()
-{
-   matrixStack[curStack][matrixIndex[curStack]].Identity();
-   LoadCurMatrix();
-}
-
-void glesPushMatrix()
-{
-   if(matrixIndex[curStack] + 1 < sizeof(matrixStack[0]) / sizeof(Matrix))
-   {
-      matrixIndex[curStack]++;
-      memcpy(matrixStack[curStack][matrixIndex[curStack]].array, matrixStack[curStack][matrixIndex[curStack]-1].array, sizeof(Matrix));
-   }
-}
-
-void glesPopMatrix()
-{
-   if(matrixIndex[curStack] > 0)
-   {
-      matrixIndex[curStack]--;
-      LoadCurMatrix();
-   }
-}
-
-void glesLoadMatrixd(double * i)
-{
-   memcpy(matrixStack[curStack][matrixIndex[curStack]].array, i, sizeof(Matrix));
-   LoadCurMatrix();
-}
-
-void glesOrtho( double l, double r, double b, double t, double n, double f )
-{
-   Matrix m =
-   { {
-      (2 / (r - l)), 0, 0, 0,
-      0, (2 / (t - b)), 0, 0,
-      0, 0, (-2 / (f - n)), 0,
-      (-(r + l) / (r - l)), (-(t + b) / (t - b)), (-(f + n) / (f - n)), 1
-   } }, res;
-   res.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
-   matrixStack[curStack][matrixIndex[curStack]] = res;
-   LoadCurMatrix();
-}
-
-void glesFrustum( double l, double r, double b, double t, double n, double f )
-{
-   nearPlane = n;
-   n = 1;
-   l /= nearPlane;
-   r /= nearPlane;
-   b /= nearPlane;
-   t /= nearPlane;
-   f /= nearPlane;
-   {
-      double A = ((r + l) / (r - l));
-      double B = ((t + b) / (t - b));
-      double C = (-(f + n) / (f - n));
-      double D = (-2*f*n/(f-n));
-      Matrix m =
-      { {
-         (2.0*n / (r - l)), 0, 0, 0,
-         0, (2.0*n / (t - b)), 0, 0,
-         A, B,             C,-1,
-         0, 0,             D, 0
-      } }, res;
-      res.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
-      matrixStack[curStack][matrixIndex[curStack]] = res;
-      LoadCurMatrix();
-   }
-}
-
-void glesRotated( double a, double b, double c, double d )
-{
-   Matrix m;
-   Quaternion q;
-   q.RotationAxis({(float)b,(float)-c,(float)d}, a );
-   m.RotationQuaternion(q);
-   matrixStack[curStack][matrixIndex[curStack]].Rotate(q);
-   LoadCurMatrix();
-}
-void glesScaled( double a, double b, double c )
-{
-   Matrix m, r;
-
-   m.Identity();
-   m.Scale(a,b,c);
-   r.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
-   matrixStack[curStack][matrixIndex[curStack]] = r;
-   LoadCurMatrix();
-}
-
-void glesTranslated( double a, double b, double c )
-{
-   Matrix m, r;
-
-   m.Identity();
-   m.Translate(a,b,c);
-   r.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
-   matrixStack[curStack][matrixIndex[curStack]] = r;
-   LoadCurMatrix();
-}
-
-void glesMultMatrixd( double * i )
-{
-   Matrix r;
-   r.Multiply((Matrix *)i, matrixStack[curStack][matrixIndex[curStack]]);
-   matrixStack[curStack][matrixIndex[curStack]] = r;
-   LoadCurMatrix();
-}
-
-void glesMatrixMode(int mode)
-{
-   curStack = mode == GL_MODELVIEW ? 0 : mode == GL_PROJECTION ? 1 : 2;
-   glMatrixMode(mode);
-}
-
-#define glPushMatrix          glesPushMatrix
-#define glPopMatrix           glesPopMatrix
-#define glLoadIdentity        glesLoadIdentity
-#define glMatrixMode          glesMatrixMode
-
-/* Using the built-in matrix stack
-void glesLoadMatrixd( double * i )
-{
-   float m[16] =
-   {
-      (float)i[0],(float)i[1],(float)i[2],(float)i[3],
-      (float)i[4],(float)i[5],(float)i[6],(float)i[7],
-      (float)i[8],(float)i[9],(float)i[10],(float)i[11],
-      (float)i[12],(float)i[13],(float)i[14],(float)i[15]
-   };
-   glLoadMatrixf(m);
-}
-
-void glesOrtho( double l, double r, double b, double t, double n, double f )
-{
-   float matrix[4][4] =
-   {
-      { (float)(2 / (r - l)), 0, 0, 0 },
-      { 0, (float)(2 / (t - b)), 0, 0 },
-      { 0, 0, (float)(-2 / (f - n)), 0 },
-      { (float)(-(r + l) / (r - l)), (float)(-(t + b) / (t - b)), (float)(-(f + n) / (f - n)), 1 }
-   };
-   glMultMatrixf((float *)matrix);
-}
-
-void glesFrustum( double l, double r, double b, double t, double n, double f )
-{
-   float A = (float)((r + l) / (r - l));
-   float B = (float)((t + b) / (t - b));
-   float C = (float)(-(f + n) / (f - n));
-   float D = (float)(-2*f*n/(f-n));
-   float matrix[4][4] =
-   {
-      { (float)(2*n / (r - l)), 0, 0, 0 },
-      { 0, (float)(2*n / (t - b)), 0, 0 },
-      { A, B,             C,-1 },
-      { 0, 0,             D, 0 }
-   };
-   glMultMatrixf((float *)matrix);
-}
-
-void glesRotated( double a, double b, double c, double d ) { glRotatef((float)a, (float)b, (float)c, (float)d); }
-void glesScaled( double a, double b, double c ) { glScalef((float)a, (float)b, (float)c); }
-void glesTranslated( double a, double b, double c ) { glTranslatef((float)a, (float)b, (float)c); }
+#if !defined(__ANDROID__) && !defined(__APPLE__) && !defined(__ODROID__) && !defined(__EMSCRIPTEN__)
+default:
+   GLAPI void APIENTRY glLockArraysEXT (GLint first, GLsizei count);
+   GLAPI void APIENTRY glUnlockArraysEXT (void);
+private:
+#endif
 
-void glesMultMatrixd( double * i )
-{
-   float m[16] =
-   {
-      (float)i[0], (float)i[1], (float)i[2], (float)i[3],
-      (float)i[4], (float)i[5], (float)i[6], (float)i[7],
-      (float)i[8], (float)i[9], (float)i[10], (float)i[11],
-      (float)i[12], (float)i[13], (float)i[14], (float)i[15]
-   };
-   glMultMatrixf(m);
-}
-*/
+#if defined(__ANDROID__) || defined(__ODROID__)
+   #define GL_FRAMEBUFFER           GL_FRAMEBUFFER_OES
+   #define GL_RENDERBUFFER          GL_RENDERBUFFER_OES
+   #define GL_COLOR_ATTACHMENT0     GL_COLOR_ATTACHMENT0_OES
+   #define GL_BGRA_EXT           0
+#endif
 
-// Need to do these...
-void glesVertex3f( float x, float y, float z )
-{
-   numVertexCoords = 3;
-   if(vertexCount + 4 > beginBufferSize)
-   {
-      beginBufferSize = beginBufferSize + beginBufferSize/2;
-      vertexPointer = renew vertexPointer float[beginBufferSize * 5];
-   }
+#if defined(__ANDROID__) || defined(__ODROID__) || defined(__EMSCRIPTEN__)
+
+   #define GL_POLYGON_STIPPLE 0xFFFF
+   #define GL_LINE_STIPPLE 0xFFFF
+   #define GL_LINE 0xFFFF
+   #define GL_FILL 0xFFFF
+   #define GL_ALL_ATTRIB_BITS 0xFFFF
+   #define GL_LIGHT_MODEL_LOCAL_VIEWER 0xFFFF
+
+   #define GL_POLYGON      9
+   #define GL_QUADS        7
+
+   //#define GL_QUADS              0
+   #define GL_QUAD_STRIP         0
+   //#define GL_DOUBLE             0
+   //#define GL_UNSIGNED_INT       0
+   //#define GL_FILL               0
+   //#define GL_LINE               0
+   //#define GL_LINE_STIPPLE       0
+   #define GL_UNPACK_ROW_LENGTH  0
+   #define GL_UNPACK_SKIP_PIXELS 0
+   #define GL_UNPACK_SKIP_ROWS   0
+   #define GL_RGBA8              0
+   #define GL_PACK_ROW_LENGTH    0
+   #define GL_PACK_SKIP_ROWS     0
+   #define GL_PACK_SKIP_PIXELS   0
+#endif
 
-   vertexPointer[vertexCount*5+2] = x;
-   vertexPointer[vertexCount*5+3] = y;
-   vertexPointer[vertexCount*5+4] = z;
-   vertexCount++;
+#endif
 
-   if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
-   {
-      vertexPointer[vertexCount*5+2] = vertexPointer[(vertexCount-4)*5+2];
-      vertexPointer[vertexCount*5+3] = vertexPointer[(vertexCount-4)*5+3];
-      vertexPointer[vertexCount*5+4] = vertexPointer[(vertexCount-4)*5+4];
-      vertexCount++;
-      vertexPointer[vertexCount*5+2] = vertexPointer[(vertexCount-3)*5+2];
-      vertexPointer[vertexCount*5+3] = vertexPointer[(vertexCount-3)*5+3];
-      vertexPointer[vertexCount*5+4] = vertexPointer[(vertexCount-3)*5+4];
-      vertexCount++;
-   }
-   beginCount++;
-}
 
-void glesVertex3d( double x, double y, double z )  { glesVertex3f((float)x, (float)y, (float)z); }
-void glesVertex3fv( float* coords )                { glesVertex3f(coords[0], coords[1], coords[2]); }
+#if defined(__ANDROID__) || defined(__ODROID__)
+   #define glBindFramebuffer        glBindFramebufferOES
+   #define glBindRenderbuffer       glBindRenderbufferOES
+   #define glFramebufferTexture2D   glFramebufferTexture2DOES
+   #define glGenFramebuffers        glGenFramebuffersOES
+   #define glGenRenderbuffers       glGenRenderbuffersOES
+   #define glDeleteFramebuffers     glDeleteFramebuffersOES
+   #define glDeleteRenderbuffers    glDeleteRenderbuffersOES
+#endif
 
-void glesNormal3f(float x, float y, float z)
-{
-   normalCount = vertexCount;
-   if(vertexCount + 4 > normalBufferSize)
-   {
-      normalBufferSize = normalBufferSize + normalBufferSize/2;
-      normalPointer = renew normalPointer float[normalBufferSize * 2];
-   }
+#if defined(__ANDROID__) || defined(__ODROID__) || defined(__EMSCRIPTEN__)
+   #define GL_INT                                  0x1404
+   #define GL_UNSIGNED_INT                         0x1405
+   #define GL_DOUBLE                               0x140A
+   #define APIENTRY
+#endif
 
-   normalPointer[normalCount*3+0] = x;
-   normalPointer[normalCount*3+1] = y;
-   normalPointer[normalCount*3+2] = z;
-   normalCount++;
+#if defined(_GLES) || defined(_GLES2) || defined(SHADERS)
+
+   #undef glRecti
+   #undef glBegin
+   #undef glTexCoord2i
+   #undef glVertex2i
+   #undef glTexCoord2d
+   #undef glVertex2d
+   #undef glTexCoord2f
+   #undef glVertex2f
+   #undef glEnd
+   #undef glColor3f
+   #undef glColor4ub
+   #undef glColor4fv
+   #undef glNormal3fv
+   #undef glNormal3f
+   #undef glTexCoord2fv
+   #undef glVertex3d
+   #undef glVertex3dv
+   #undef glVertex3f
+   #undef glVertex3fv
+
+   #undef glLoadMatrixd
+   #undef glMultMatrixd
+   #undef glFrustum
+   #undef glOrtho
+   #undef glScaled
+   #undef glScalef
+   #undef glTranslated
+   #undef glRotated
+   #undef glMatrixMode
+   #undef glLoadIdentity
+   #undef glPushMatrix
+   #undef glPopMatrix
+
+   #undef glLineStipple
+   #undef glColorMaterial
+   #undef glLightModeli
+
+   #define glRecti               glimtkRecti
+   #define glBegin               glimtkBegin
+   #define glTexCoord2i          glimtkTexCoord2i
+   #define glVertex2i            glimtkVertex2i
+   #define glTexCoord2d          glimtkTexCoord2d
+   #define glVertex2d            glimtkVertex2d
+   #define glTexCoord2f          glimtkTexCoord2f
+   #define glVertex2f            glimtkVertex2f
+   #define glEnd                 glimtkEnd
+   #define glColor3f             glimtkColor3f
+   #define glColor4ub            glimtkColor4ub
+   #define glColor4fv            glimtkColor4fv
+   #define glNormal3fv           glimtkNormal3fv
+   #define glNormal3f            glimtkNormal3f
+   #define glTexCoord2fv         glimtkTexCoord2fv
+   #define glVertex3d            glimtkVertex3d
+   #define glVertex3dv           glimtkVertex3dv
+   #define glVertex3f            glimtkVertex3f
+   #define glVertex3fv           glimtkVertex3fv
+
+   #define glLoadMatrixd         glmsLoadMatrixd
+   #define glMultMatrixd         glmsMultMatrixd
+   #define glFrustum             glmsFrustum
+   #define glOrtho               glmsOrtho
+   #define glScaled              glmsScaled
+   #define glScalef              glmsScaled
+   #define glTranslated          glmsTranslated
+   #define glRotated             glmsRotated
+   #define glMatrixMode          glmsMatrixMode
+   #define glLoadIdentity        glmsLoadIdentity
+   #define glPushMatrix          glmsPushMatrix
+   #define glPopMatrix           glmsPopMatrix
+
+   #define glLineStipple         glesLineStipple
+   #define glColorMaterial       glesColorMaterial
+   #define glLightModeli         glesLightModeli
 
-   if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
-   {
-      normalPointer[normalCount*3+0] = normalPointer[(normalCount-4)*3+0];
-      normalPointer[normalCount*3+1] = normalPointer[(normalCount-4)*3+1];
-      normalPointer[normalCount*3+2] = normalPointer[(normalCount-4)*3+2];
-      normalCount++;
-      normalPointer[normalCount*3+0] = normalPointer[(normalCount-3)*3+0];
-      normalPointer[normalCount*3+1] = normalPointer[(normalCount-3)*3+1];
-      normalPointer[normalCount*3+2] = normalPointer[(normalCount-3)*3+2];
-      normalCount++;
-   }
-}
-void glesNormal3fd(double x, double y, double z)         { glesNormal3f((float)x, (float)y, (float)z); }
-void glesNormal3fv(float * coords)                       { glesNormal3f(coords[0], coords[1], coords[2]); }
+#endif
 
-void glesColorMaterial(int a, int b)
+public void glesColorMaterial(int a, int b)
 {
    PrintLn("glColorMaterial stub");
 }
 
-void glesTerminate()
-{
-   delete vertexPointer;
-   beginBufferSize = 0;
-
-   delete floatVPBuffer;
-   shortVPSize = 0;
-
-   delete shortVPBuffer;
-   floatVPSize = 0;
-
-   delete shortBDBuffer;
-   shortBDSize = 0;
-}
-
-static int stippleTexture;
+static GLuint stippleTexture;
+#if defined(_GLES) || defined(_GLES2) || defined(SHADERS)
 static bool stippleEnabled;
+#endif
 
-void glesLineStipple( int i, unsigned short j )
+public void glesLineStipple( int i, unsigned short j )
 {
    uint texture[1*16];
-   int c;
    int x;
    for(x = 0; x < 16; x++)
    {
@@ -1053,7 +408,9 @@ void glesLineStipple( int i, unsigned short j )
       glGenTextures(1, &stippleTexture);
    glBindTexture(GL_TEXTURE_2D, stippleTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 16, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture);
-   glEnable(GL_TEXTURE_2D);
+
+   // TOOD: Special shading code for stippling?
+   GLSetupTexturing(true);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
@@ -1063,16 +420,22 @@ void glesLineStipple( int i, unsigned short j )
    //glTranslated(1.0/backAttrib->texW/2.0f, 1.0/backAttrib->texH/2.0f, 0.0f);
    glScaled(i/16.0, 1, 1.0f);
    glTranslated(0.5, 0.5, 0);
-   glMatrixMode(GL_PROJECTION);
+   glMatrixMode(MatrixMode::projection);
 }
 
-void glesLightModeli( unsigned int pname, int param )
+public void glesLightModeli( unsigned int pname, int param )
 {
+#if !defined(SHADERS)
    if(pname == GL_LIGHT_MODEL_TWO_SIDE)
       glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, param);
+#endif
 }
 
+#if defined(__ANDROID__) || defined(__ODROID__) || defined(__EMSCRIPTEN__)
 void glClearDepth( double depth ) { glClearDepthf((float)depth); }
+#endif
+
+#if defined(__ANDROID__) || defined(__ODROID__)
 void glFogi( unsigned int pname, int param ) { }
 void glPolygonMode( unsigned int i, unsigned int j ) { }
 
@@ -1093,98 +456,76 @@ void glRasterPos2d(double a, double b) { }
 void glPixelZoom(float a, float b) { }
 void glDrawPixels(int a, int b, int c, int d, void * e) { }
 
-#else
-
-/* Non OpenGL ES friendly stuff
-#undef GL_UNSIGNED_INT
-#undef GL_DOUBLE
-#undef GL_INT
-//#undef GL_POLYGON
-//#undef GL_QUADS
-#undef GL_QUAD_STRIP
-#undef GL_POLYGON_STIPPLE
-#undef GL_LINE_STIPPLE
-#undef GL_LINE
-#undef GL_FILL
-#undef GL_ALL_ATTRIB_BITS
-#undef GL_LIGHT_MODEL_LOCAL_VIEWER
-*/
-
 #endif
 
-#if !defined(__APPLE__)
-void (APIENTRY * glBindBufferARB) (GLenum target, GLuint buffer);
-void (APIENTRY * glGenBuffersARB) (GLsizei n, GLuint *buffers);
-void (APIENTRY * glDeleteBuffersARB) (GLsizei n, const GLuint *buffers);
-void (APIENTRY * glBufferDataARB) (GLenum target, int size, const GLvoid *data, GLenum usage);
+#if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
+static int primitiveTypes[RenderPrimitiveType] =
+{
+   GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN,
+#if defined(SHADERS) || defined(_GLES) || defined(_GLES2)
+   GL_TRIANGLE_FAN,     // NOTE: This will only work for single quads
+#else
+   GLIMTKMode::quads,
 #endif
-
+   GLIMTKMode::quadStrip,
+   GL_LINE_STRIP
+};
 #endif
 
-static int currentVertexBuffer;
-
-bool GLSelectVBO(uint vbo)
+public void GLSetupTexturing(bool enable)
 {
-   if(currentVertexBuffer != vbo)
-   {
-      GLBindBuffer(GL_ARRAY_BUFFER, vbo);
-      currentVertexBuffer = vbo;
-      return true;
-   }
-   return false;
-}
-
-void GLGenBuffers(int count, uint * buffer)
-{
-#ifdef __ANDROID__
-   glGenBuffers(count, buffer);
+#ifdef SHADERS
+   shader_texturing(enable);
 #else
-   if(glGenBuffersARB)
-      glGenBuffersARB(count, buffer);
+   (enable ? glEnable : glDisable)(GL_TEXTURE_2D);
 #endif
 }
 
-void GLDeleteBuffers(int count, uint * buffer)
+public void GLSetupFog(bool enable)
 {
-#ifdef __ANDROID__
-   glDeleteBuffers(count, buffer);
+#ifdef SHADERS
+   shader_fog(enable);
 #else
-   if(glDeleteBuffersARB)
-      glDeleteBuffersARB(count, buffer);
+   (enable ? glEnable : glDisable)(GL_FOG);
 #endif
 }
 
-void GLBindBuffer(int target, uint buffer)
+bool lightingEnabled;
+
+public void GLSetupLighting(bool enable)
 {
-#ifdef __ANDROID__
-   glBindBuffer(target, buffer);
+   lightingEnabled = enable;
+#if defined(SHADERS)
+   shader_lighting(enable);
 #else
-   if(glBindBufferARB)
-      glBindBufferARB(target, buffer);
+   (enable ? glEnable : glDisable)(GL_LIGHTING);
 #endif
 }
 
-void GLBufferData(int type, GLenum target, int size, const GLvoid *data, GLenum usage)
-{
-#ifdef __ANDROID__
-   if(type == GL_DOUBLE)
-      glesBufferDatad(target, size, data, usage);
-   else if(type == GL_UNSIGNED_INT)
-      glesBufferDatai(target, size, data, usage);
-   else
-      glBufferData(target, size, data, usage);
-#else
-   if(glBufferDataARB)
-      glBufferDataARB(target, size, data, usage);
+// Non OpenGL ES friendly stuff
+
+#if defined(_GLES) || defined(_GLES2)
+
+//#undef GL_UNSIGNED_INT
+//#undef GL_DOUBLE
+#undef GL_INT
+//#undef GL_POLYGON
+//#undef GL_QUADS
+#undef GL_QUAD_STRIP
+#undef GL_POLYGON_STIPPLE
+#undef GL_LINE_STIPPLE
+#undef GL_LINE
+#undef GL_FILL
+#undef GL_ALL_ATTRIB_BITS
+#undef GL_LIGHT_MODEL_LOCAL_VIEWER
 
 #endif
-}
 
 static int displayWidth, displayHeight;
 
 #define GL_CLAMP_TO_EDGE 0x812F
 
-static bool vboAvailable;
+/*static */bool vboAvailable;
 
 static bool useSingleGLContext = false;
 class OGLDisplay : struct
@@ -1202,7 +543,7 @@ class OGLDisplay : struct
    int imageBuffers[2];
    byte * pboMemory1, * pboMemory2;
    */
-#else
+#elif !defined(__ANDROID__) && !defined(__ODROID__) && !defined(__EMSCRIPTEN__)
    GLXContext glContext;
 
    Pixmap pixmap;
@@ -1225,6 +566,47 @@ class OGLDisplay : struct
    int x, y;
 };
 
+#if defined(_DEBUG) && !defined(__ANDROID__) && !defined(__EMSCRIPTEN__) && !defined(__ODROID__)
+// #define GL_DEBUGGING
+#endif
+
+#ifdef GL_DEBUGGING
+static void APIENTRY openglCallbackFunction(GLenum source,
+                                           GLenum type,
+                                           GLuint id,
+                                           GLenum severity,
+                                           GLsizei length,
+                                           const GLchar* message,
+                                           const void* userParam)
+{
+   if(severity == GL_DEBUG_SEVERITY_NOTIFICATION)
+      return;
+   PrintLn("---------------------opengl-callback-start------------");
+   PrintLn("message: ", message);
+   PrintLn("type: ");
+   switch (type)
+   {
+      case GL_DEBUG_TYPE_ERROR: PrintLn("ERROR"); break;
+      case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: PrintLn("DEPRECATED_BEHAVIOR"); break;
+      case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: PrintLn("UNDEFINED_BEHAVIOR"); break;
+      case GL_DEBUG_TYPE_PORTABILITY: PrintLn("PORTABILITY"); break;
+      case GL_DEBUG_TYPE_PERFORMANCE: PrintLn("PERFORMANCE"); break;
+      case GL_DEBUG_TYPE_OTHER: PrintLn("OTHER"); break;
+   }
+
+   PrintLn("id: ", id);
+   Print("severity: ");
+   switch (severity)
+   {
+      case GL_DEBUG_SEVERITY_LOW: PrintLn("LOW"); break;
+      case GL_DEBUG_SEVERITY_MEDIUM: PrintLn("MEDIUM"); break;
+      case GL_DEBUG_SEVERITY_HIGH: PrintLn("HIGH"); break;
+      default: PrintLn("(other)");
+   }
+   PrintLn("---------------------opengl-callback-end--------------");
+}
+#endif
+
 class OGLSystem : struct
 {
    int maxTextureSize;
@@ -1236,7 +618,9 @@ class OGLSystem : struct
    HDC hdc;
    HGLRC glrc;
    HWND hwnd;
-#else
+#elif defined(__EMSCRIPTEN__)
+   EMSCRIPTEN_WEBGL_CONTEXT_HANDLE glc;
+#elif !defined(__ANDROID__) && !defined(__ODROID__)
    XVisualInfo * visualInfo;
    GLXContext glContext;
    GLXDrawable glxDrawable;
@@ -1249,35 +633,80 @@ class OGLSurface : struct
    bool opaqueText;
    int xOffset;
    bool writingText;
+   bool writingOutline;
 
    float foreground[4], background[4], bitmapMult[4];
 } OGLSurface;
 
 class OGLMesh : struct
 {
-   int vertices;
-   int normals;
-   int texCoords;
-   int texCoords2;
-   int colors;
+   GLAB vertices;
+   GLAB normals;
+   GLAB texCoords;
+   GLAB texCoords2;
+   GLAB colors;
 };
 
 class OGLIndices : struct
 {
    uint16 * indices;
-   int buffer;
-   int nIndices;
+   GLEAB buffer;
+   uint nIndices;
 };
 
-#if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
-static int primitiveTypes[RenderPrimitiveType] =
+int current;
+void * previous;
+
+#ifdef GL_DEBUGGING
+static void setupDebugging()
 {
-   GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUADS, GL_QUAD_STRIP, GL_LINE_STRIP
-};
+   if(glDebugMessageCallback)
+   {
+      GLuint unusedIds = 0;
+
+      glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
+
+      glDebugMessageCallback(openglCallbackFunction, null);
+      glDebugMessageControl(GL_DONT_CARE,
+          GL_DONT_CARE,
+          GL_DONT_CARE,
+          0,
+          &unusedIds,
+          GL_TRUE);
+   }
+}
 #endif
 
-int current;
-void * previous;
+#if defined(__WIN32__)
+static HGLRC winCreateContext(HDC hdc)
+{
+   HGLRC result = 0;
+#ifdef SHADERS
+   if(wglCreateContextAttribsARB)
+   {
+      int attribs[] =
+      {
+         WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
+         WGL_CONTEXT_MINOR_VERSION_ARB, 4,
+         WGL_CONTEXT_FLAGS_ARB, /*WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | */WGL_CONTEXT_DEBUG_BIT_ARB,
+         WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB /*WGL_CONTEXT_CORE_PROFILE_BIT_ARB*/,
+         0,0
+      };
+      result = wglCreateContextAttribsARB(hdc, null, attribs);
+      if(!result)
+      {
+         attribs[1] = 2;
+         attribs[3] = 0;
+         attribs[7] = 0;
+         result = wglCreateContextAttribsARB(hdc, null, attribs);
+      }
+   }
+#endif
+   if(!result)
+      result = wglCreateContext(hdc);
+   return result;
+}
+#endif
 
 class OpenGLDisplayDriver : DisplayDriver
 {
@@ -1285,6 +714,10 @@ class OpenGLDisplayDriver : DisplayDriver
 
    bool LockSystem(DisplaySystem displaySystem)
    {
+#if defined(__EMSCRIPTEN__)
+      OGLSystem oglSystem = displaySystem.driverData;
+      emscripten_webgl_make_context_current(oglSystem.glc);
+#elif !defined(__ANDROID__) && !defined(__ODROID__)
       OGLSystem oglSystem = displaySystem.driverData;
       if(useSingleGLContext) return true;
    #if defined(__WIN32__)
@@ -1292,11 +725,12 @@ class OpenGLDisplayDriver : DisplayDriver
    #elif defined(__unix__) || defined(__APPLE__)
       //if(previous) return true;
       // printf("Making SYSTEM current\n");
-#if !defined(__ANDROID__)
       glXMakeCurrent(xGlobalDisplay, (GLXDrawable)oglSystem.glxDrawable, oglSystem.glContext);
-#endif
       //previous = oglSystem.glContext;
    #endif
+#endif
+      GLABBindBuffer(GL_ARRAY_BUFFER, 0);
+      GLABBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
       return true;
    }
 
@@ -1307,7 +741,7 @@ class OpenGLDisplayDriver : DisplayDriver
       wglMakeCurrent(null, null);
    #elif defined(__unix__) || defined(__APPLE__)
       // printf("Making NULL current\n");
-      #if defined(__ANDROID__)
+      #if defined(__ANDROID__) || defined(__ODROID__) || defined(__EMSCRIPTEN__)
       #else
       glXMakeCurrent(xGlobalDisplay, None, null);
       #endif
@@ -1317,20 +751,19 @@ class OpenGLDisplayDriver : DisplayDriver
 
    bool Lock(Display display)
    {
+#if !defined(__ANDROID__) && !defined(__ODROID__) && !defined(__EMSCRIPTEN__)
       OGLDisplay oglDisplay = display.driverData;
-      OGLSystem oglSystem = display.displaySystem.driverData;
-
       if(useSingleGLContext) return true;
    #if defined(__WIN32__)
       wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
    #elif defined(__unix__) || defined(__APPLE__)
       // if(previous) glXMakeCurrent(xGlobalDisplay, None, null);
       // printf("   Making DISPLAY current\n");
-      #if defined(__ANDROID__)
-      #else
-      glXMakeCurrent(xGlobalDisplay, (int)display.window, oglDisplay.glContext);
-      #endif
+      glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
    #endif
+#endif
+      GLABBindBuffer(GL_ARRAY_BUFFER, 0);
+      GLABBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
       return true;
    }
 
@@ -1368,7 +801,7 @@ class OpenGLDisplayDriver : DisplayDriver
          if(oglDisplay.memBitmap) DeleteObject(oglDisplay.memBitmap);
 
    #elif defined(__unix__) || defined(__APPLE__)
-      #if defined(__ANDROID__)
+      #if defined(__ANDROID__) || defined(__ODROID__) || defined(__EMSCRIPTEN__)
       #else
          if(oglDisplay.shapePixmap)
             XFreePixmap(xGlobalDisplay, oglDisplay.shapePixmap);
@@ -1411,10 +844,16 @@ class OpenGLDisplayDriver : DisplayDriver
 
    void ::CheckExtensions(OGLSystem oglSystem)
    {
-      char * extensions = glGetString(GL_EXTENSIONS);
-      if(extensions)
-         oglSystem.pow2textures = strstr(extensions, "GL_ARB_texture_non_power_of_two") ? false : true;
+      const char * extensions = (const char *)glGetString(GL_EXTENSIONS);
+#ifdef DIAGNOSTICS
+      printf("extensions: %s\n", extensions);
+#endif
+
+      oglSystem.pow2textures = (extensions && strstr(extensions, "GL_ARB_texture_non_power_of_two")) ? false : true;
       glGetIntegerv(GL_MAX_TEXTURE_SIZE, &oglSystem.maxTextureSize);
+#ifdef DIAGNOSTICS
+      PrintLn("max texture size: ", oglSystem.maxTextureSize);
+#endif
    }
 
    bool CreateDisplaySystem(DisplaySystem displaySystem)
@@ -1422,6 +861,10 @@ class OpenGLDisplayDriver : DisplayDriver
       bool result = false;
       OGLSystem oglSystem = displaySystem.driverData = OGLSystem { };
 
+#ifdef DIAGNOSTICS
+      PrintLn("OpenGL driver's CreateDisplaySystem()");
+#endif
+
    #ifdef __WIN32__
       oglSystem.hwnd = CreateWindow("static", null, 0,0,0,0,0,null,null,null,null);
 
@@ -1449,20 +892,6 @@ class OpenGLDisplayDriver : DisplayDriver
             {
                wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
 
-                // Get Pointers To The GL Functions
-               glActiveTextureARB = (void *) wglGetProcAddress("glActiveTextureARB");
-               glMultiTexCoord2fARB = (void *) wglGetProcAddress("glMultiTexCoord2fARB");
-               glClientActiveTextureARB = (void *) wglGetProcAddress("glClientActiveTextureARB");
-               glLockArraysEXT = (void *) wglGetProcAddress("glLockArraysEXT" );
-               glUnlockArraysEXT = (void *) wglGetProcAddress("glUnlockArraysEXT");
-                glGenBuffersARB = (void *) wglGetProcAddress("glGenBuffersARB");
-                glBindBufferARB = (void *) wglGetProcAddress("glBindBufferARB");
-                glBufferDataARB = (void *) wglGetProcAddress("glBufferDataARB");
-               glMapBufferARB  = (void *) wglGetProcAddress("glMapBufferARB");
-               glUnmapBufferARB  = (void *) wglGetProcAddress("glUnmapBufferARB");
-                glDeleteBuffersARB = (void *) wglGetProcAddress("glDeleteBuffersARB");
-               glBlendFuncSeparate = (void *) wglGetProcAddress("glBlendFuncSeparate");
-
                wglChoosePixelFormatARB = (void *) wglGetProcAddress("wglChoosePixelFormatARB");
                wglGetExtensionsStringARB = (void *)wglGetProcAddress("wglGetExtensionsStringARB");
                wglCreatePbufferARB = (void *)wglGetProcAddress("wglCreatePbufferARB");
@@ -1472,42 +901,43 @@ class OpenGLDisplayDriver : DisplayDriver
                wglReleasePbufferDCARB = (void *)wglGetProcAddress("wglReleasePbufferDCARB");
                wglBindTexImageARB = (void *)wglGetProcAddress("wglBindTexImageARB");
                wglReleaseTexImageARB = (void *)wglGetProcAddress("wglReleaseTexImageARB");
-
                wglSwapIntervalEXT = (void *)wglGetProcAddress("wglSwapIntervalEXT");
+               wglCreateContextAttribsARB = (void *)wglGetProcAddress("wglCreateContextAttribsARB");
 
-               vboAvailable = glBindBufferARB != null;
+               glLockArraysEXT = (void *) wglGetProcAddress("glLockArraysEXT" );
+               glUnlockArraysEXT = (void *) wglGetProcAddress("glUnlockArraysEXT");
 
                // eSystem_LoggingMode(LOG_MSGBOX, null);
 
                if(wglChoosePixelFormatARB)
                {
-                   int pixelFormat;
-                   int valid;
-                   int numFormats;
-                   float fAttributes[] = {0,0};
-                   int iAttributes[] =
+                  int pixelFormat;
+                  int valid;
+                  int numFormats;
+                  float fAttributes[] = {0,0};
+                  int iAttributes[] =
                   {
                      WGL_DRAW_TO_WINDOW_ARB,GL_TRUE,
-                           WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
-                           WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
-                           WGL_COLOR_BITS_ARB,24,
-                           WGL_ALPHA_BITS_ARB,8,
-                           WGL_DEPTH_BITS_ARB,16,
-                           WGL_STENCIL_BITS_ARB,0,
-                           WGL_DOUBLE_BUFFER_ARB,GL_TRUE,
-                           WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
-                           WGL_SAMPLES_ARB, 4,                                         // Check For 4x Multisampling
-                           0,0
+                     WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
+                     WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
+                     WGL_COLOR_BITS_ARB,24,
+                     WGL_ALPHA_BITS_ARB,8,
+                     WGL_DEPTH_BITS_ARB,16,
+                     WGL_STENCIL_BITS_ARB,0,
+                     WGL_DOUBLE_BUFFER_ARB,GL_TRUE,
+                     WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
+                     WGL_SAMPLES_ARB, 4,                  // Check For 4x Multisampling
+                     0,0
                   };
 
                   //Log("Found wglChoosePixelFormatARB\n");
 
-                   valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
-                   if(!valid || !numFormats)
-                   {
+                  valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
+                  if(!valid || !numFormats)
+                  {
                      //Log("Can't find 4x multi sampling\n");
-                      iAttributes[19] = 2;
-                      valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
+                     iAttributes[19] = 2;
+                     valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
                      if(!valid || !numFormats)
                      {
                         // Log("Can't find 2x multi sampling\n");
@@ -1515,41 +945,119 @@ class OpenGLDisplayDriver : DisplayDriver
                         iAttributes[17] = 0;
                         valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
                      }
-                   }
+                  }
                   if(valid && numFormats)
                   {
                      oglSystem.format = pixelFormat;
                      wglMakeCurrent(null, null);
                      wglDeleteContext(oglSystem.glrc);
 
-                     // *** DescribePixelFormat does not support WGL pixel formats! ***
-                     //DescribePixelFormat(oglSystem.hdc, oglSystem.format, sizeof(oglSystem.pfd), &oglSystem.pfd);
-                     SetPixelFormat(oglSystem.hdc, oglSystem.format, &oglSystem.pfd);
-                     //Log("Successfully set pixel format\n");
+                     // *** DescribePixelFormat does not support WGL pixel formats! ***
+                     //DescribePixelFormat(oglSystem.hdc, oglSystem.format, sizeof(oglSystem.pfd), &oglSystem.pfd);
+                     SetPixelFormat(oglSystem.hdc, oglSystem.format, &oglSystem.pfd);
+                     //Log("Successfully set pixel format\n");
+
+#ifdef DIAGNOSTICS
+                     PrintLn("winCreateContext()");
+#endif
+                     oglSystem.glrc = winCreateContext(oglSystem.hdc);
+#ifdef DIAGNOSTICS
+                     PrintLn("wglMakeCurrent()");
+#endif
+                     wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
+                  }
+               }
+               /*else
+                  eSystem_Logf("Can't find wglChoosePixelFormatARB\n");*/
+
+               result = true;
+
+               wglMakeCurrent(null, null);
+
+               //eSystem_DumpErrors(true);
+            }
+         }
+      }
+   #elif defined(__unix__) || defined(__APPLE__)
+      vboAvailable = true;
+      #if defined(__ANDROID__) || defined(__ODROID__)
+         #if defined(__ANDROID__)
+         egl_init_display(guiApp.desktop.windowHandle);
+         #elif defined(__ODROID__)
+         egl_init_display((uint)displaySystem.window);
+         #endif
+         CheckExtensions(oglSystem);
+
+         // TODO: Clean this up? Needed here?
+         glEnableClientState(GL_VERTEX_ARRAY);
+         /*
+         // Initialize GL state.
+         glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
+         glEnable(GL_CULL_FACE);
+         glShadeModel(GL_SMOOTH);
+         glDisable(GL_DEPTH_TEST);
+         */
+         glDisable(GL_CULL_FACE);
+         glDisable(GL_DEPTH_TEST);
+
+         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+         glEnable(GL_BLEND);
+
+         matrixStack[0][0].Identity();
+         matrixStack[1][0].Identity();
+         matrixStack[2][0].Identity();
+
+         glmsMatrixMode(GL_MODELVIEW);
+         glScaled(1.0, 1.0, -1.0);
+         glmsMatrixMode(GL_PROJECTION);
+         glShadeModel(GL_FLAT);
+
+         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
+         glFogi(GL_FOG_MODE, GL_EXP);
+         glFogf(GL_FOG_DENSITY, 0);
+         glEnable(GL_NORMALIZE);
+         glDepthFunc(GL_LESS);
+         glClearDepth(1.0);
+         glDisable(GL_MULTISAMPLE_ARB);
 
-                     oglSystem.glrc = wglCreateContext(oglSystem.hdc);
-                     wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
-                  }
-               }
-               /*else
-                  eSystem_Logf("Can't find wglChoosePixelFormatARB\n");*/
+         glViewport(0,0,eglWidth,eglHeight);
+         glmsLoadIdentity();
+         glOrtho(0,eglWidth,eglHeight,0,0.0,1.0);
 
-               result = true;
+         glabCurArrayBuffer = 0;
+         glabCurElementBuffer = 0;
 
-               CheckExtensions(oglSystem);
+         result = true;
+      #elif defined(__EMSCRIPTEN__)
+         {
+            EmscriptenWebGLContextAttributes attribs = { 0 };
+            attribs.depth = 1;
+            attribs.antialias = 1;
 
-               wglMakeCurrent(null, null);
+            /*
+              EM_BOOL alpha;
+              EM_BOOL depth;
+              EM_BOOL stencil;
+              EM_BOOL antialias;
+              EM_BOOL premultipliedAlpha;
+              EM_BOOL preserveDrawingBuffer;
+              EM_BOOL preferLowPowerToHighPerformance;
+              EM_BOOL failIfMajorPerformanceCaveat;
+              int majorVersion;
+              int minorVersion;
+              EM_BOOL enableExtensionsByDefault;
+              */
+
+            emscripten_webgl_init_context_attributes(&attribs);
+            oglSystem.pow2textures = true;
+            oglSystem.maxTextureSize = 16384;
+            oglSystem.glc = emscripten_webgl_create_context("canvas", &attribs);
+            if(emscripten_webgl_make_context_current(oglSystem.glc) == EMSCRIPTEN_RESULT_SUCCESS)
+               result = true;
 
-               //eSystem_DumpErrors(true);
-            }
+            /*glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+            glEnable(GL_BLEND);*/
          }
-      }
-   #elif defined(__unix__) || defined(__APPLE__)
-      vboAvailable = true;
-      #if defined(__ANDROID__)
-         egl_init_display(guiApp.desktop.windowHandle);
-         CheckExtensions(oglSystem);
-         result = true;
       #else
       {
          X11Window root = RootWindow( xGlobalDisplay, DefaultScreen( xGlobalDisplay ) );
@@ -1583,7 +1091,7 @@ class OpenGLDisplayDriver : DisplayDriver
          {
             glXMakeCurrent(xGlobalDisplay, oglSystem.glxDrawable, oglSystem.glContext);
             // Setup Extensions
-            CheckExtensions(oglSystem);
+            // CheckExtensions(oglSystem);
             glXMakeCurrent(xGlobalDisplay, None, null);
             result = true;
          }
@@ -1600,6 +1108,13 @@ class OpenGLDisplayDriver : DisplayDriver
    void DestroyDisplaySystem(DisplaySystem displaySystem)
    {
       OGLSystem oglSystem = displaySystem.driverData;
+      if(stippleTexture)
+      {
+         glDeleteTextures(1, &stippleTexture);
+         stippleTexture = 0;
+      }
+
+      glimtkTerminate();
 
    #if defined(__WIN32__)
       wglMakeCurrent( null, null );
@@ -1612,8 +1127,10 @@ class OpenGLDisplayDriver : DisplayDriver
       DestroyWindow(oglSystem.hwnd);
 
    #elif defined(__unix__) || defined(__APPLE__)
-      #if defined(__ANDROID__)
+      #if defined(__ANDROID__) || defined(__ODROID__)
          egl_term_display();
+      #elif defined(__EMSCRIPTEN__)
+         emscripten_webgl_destroy_context(oglSystem.glc);
       #else
       if(oglSystem.visualInfo)
       {
@@ -1634,11 +1151,62 @@ class OpenGLDisplayDriver : DisplayDriver
       delete oglSystem;
    }
 
+   static bool ::initialDisplaySetup(Display display)
+   {
+      bool result = true;
+      #ifdef SHADERS
+      loadShaders("<:ecere>shaders/fixed.vertex", "<:ecere>shaders/fixed.frag");
+      #endif
+      glEnableClientState(GL_VERTEX_ARRAY);
+
+      GLABBindBuffer(GL_ARRAY_BUFFER, 0);
+      GLABBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+
+#if defined(__WIN32__)
+      if(glBlendFuncSeparate)
+         glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+      else
+         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+#else
+      glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+#endif
+      glEnable(GL_BLEND);
+
+      glMatrixMode(MatrixMode::modelView);
+      glLoadIdentity(); // For setting up GLES stack
+      glScaled(1.0, 1.0, -1.0);
+      // glTranslatef(0.375f, 0.375f, 0.0f);
+      // glTranslatef(-0.625f, -0.625f, 0.0f);
+      glMatrixMode(MatrixMode::projection);
+#if !defined(EM_MODE) && !defined(SHADERS)
+      glShadeModel(GL_FLAT);
+
+      // #define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51
+
+      // glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
+
+      glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
+      glFogi(GL_FOG_MODE, GL_EXP);
+      glFogf(GL_FOG_DENSITY, 0);
+      glEnable(GL_NORMALIZE);
+#endif
+      glDepthFunc(GL_LESS);
+      glClearDepth(1.0);
+      glDisable(GL_MULTISAMPLE_ARB);
+#if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
+      display.ambient = Color { 50,50,50 };
+#endif
+      return result;
+   }
+
    bool CreateDisplay(Display display)
    {
       bool result = false;
       OGLDisplay oglDisplay = display.driverData;
+#if !defined(__ANDROID__) && !defined(__ODROID__)
       OGLSystem oglSystem = display.displaySystem.driverData;
+#endif
+
       if(!oglDisplay)
          oglDisplay = display.driverData = OGLDisplay { };
       //printf("Inside CreateDisplay\n");
@@ -1647,10 +1215,10 @@ class OpenGLDisplayDriver : DisplayDriver
       if(!display.alphaBlend)
 #endif
       {
-   #if defined(__WIN32__)
+#if defined(__WIN32__)
          oglDisplay.hdc = GetDC(display.window);
          SetPixelFormat(oglDisplay.hdc, oglSystem.format, &oglSystem.pfd);
-         if((oglDisplay.glrc = wglCreateContext(oglDisplay.hdc)))
+         if((oglDisplay.glrc = winCreateContext(oglDisplay.hdc)))
          {
             wglShareLists(oglSystem.glrc, oglDisplay.glrc);
             wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
@@ -1658,9 +1226,10 @@ class OpenGLDisplayDriver : DisplayDriver
          }
          else
             ReleaseDC(display.window, oglDisplay.hdc);
-   #elif defined(__unix__) || defined(__APPLE__)
-      #if defined(__ANDROID__)
-      #else
+#elif defined(__unix__) || defined(__APPLE__)
+#  if defined(__ANDROID__) || defined(__EMSCRIPTEN__) || defined(__ODROID__)
+         result = true;
+#  else
          XVisualInfo * visualInfo = ((XWindowData)display.windowDriverData).visual;
          /*
 #if defined(__APPLE__)
@@ -1691,58 +1260,70 @@ class OpenGLDisplayDriver : DisplayDriver
          if(oglDisplay.glContext)
          {
             //printf("CreateDisplay Got a Context\n");
-            glXMakeCurrent(xGlobalDisplay, (int)display.window, oglDisplay.glContext);
+            glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
             result = true;
          }
-      #endif
-   #endif
+#  endif
+#endif
       }
 #if defined(__WIN32__) || defined(USEPBUFFER)
       else
+      {
          result = true;
+         wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
+      }
 #endif
       if(result)
       {
-#if !defined(__OLDX__)
-         if(glBlendFuncSeparate)
-            glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
-         else
+#if !defined(__ANDROID__) && !defined(__EMSCRIPTEN__) && !defined(__ODROID__)
+
+#ifdef DIAGNOSTICS
+         PrintLn("Calling ogl_LoadFunctions() in CreateDisplay()");
 #endif
-            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-         glEnable(GL_BLEND);
+         if(ogl_LoadFunctions() == ogl_LOAD_FAILED)
+            PrintLn("ogl_LoadFunctions() failed!");
 
-         glMatrixMode(GL_MODELVIEW);
-         glScaled(1.0, 1.0, -1.0);
-         // glTranslatef(0.375f, 0.375f, 0.0f);
-         // glTranslatef(-0.625f, -0.625f, 0.0f);
-         glMatrixMode(GL_PROJECTION);
-         glShadeModel(GL_FLAT);
+#ifdef DIAGNOSTICS
+         PrintLn("CheckExtensions()");
+#endif
+         CheckExtensions(oglSystem);
+         vboAvailable = glBindBuffer != null;
 
-         // glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, true);
-         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
-         glFogi(GL_FOG_MODE, GL_EXP);
-         glFogf(GL_FOG_DENSITY, 0);
-         glEnable(GL_NORMALIZE);
-         glDepthFunc(GL_LESS);
-         glClearDepth(1.0);
-         glDisable(GL_MULTISAMPLE_ARB);
-      }
-#if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
-      display.ambient = Color { 50,50,50 };
+#ifdef DIAGNOSTICS
+         PrintLn("vboAvailable is: ", vboAvailable);
+#endif
+
+#  ifdef GL_DEBUGGING
+         setupDebugging();
+#  endif
+
+#endif
+
+#if defined(__EMSCRIPTEN__)
+         emscripten_webgl_make_context_current(oglSystem.glc);
 #endif
 
+         initialDisplaySetup(display);
+      }
+
       if(!useSingleGLContext)
       {
    #if defined(__WIN32__)
          wglMakeCurrent(null, null);
    #elif defined(__unix__) || defined(__APPLE__)
-      #if defined(__ANDROID__)
+      #if defined(__ANDROID__) || defined(__ODROID__) || defined(__EMSCRIPTEN__)
          result = true;
       #else
          glXMakeCurrent(xGlobalDisplay, None, null);
       #endif
    #endif
       }
+      else
+      {
+      #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) || defined(__ODROID__)
+         result = true;
+      #endif
+      }
 
       return result;
    }
@@ -1750,12 +1331,12 @@ class OpenGLDisplayDriver : DisplayDriver
    bool DisplaySize(Display display, int width, int height)
    {
       OGLDisplay oglDisplay = display.driverData;
-      OGLSystem oglSystem = display.displaySystem.driverData;
 
       bool result = false;
 
       //printf("Inside DisplaySize\n");
 #if defined(__WIN32__) || defined(USEPBUFFER)
+      OGLSystem oglSystem = display.displaySystem.driverData;
       if(display.alphaBlend)
       {
 #if defined(__WIN32__)
@@ -1774,16 +1355,16 @@ class OpenGLDisplayDriver : DisplayDriver
             {
                //WGL_DRAW_TO_BITMAP_ARB, GL_TRUE,
                WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
-                   WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
-                   WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
-                   WGL_COLOR_BITS_ARB,24,
-                   WGL_ALPHA_BITS_ARB,8,
-                   WGL_DEPTH_BITS_ARB,16,
-                   WGL_STENCIL_BITS_ARB,0,
-                   WGL_DOUBLE_BUFFER_ARB,GL_FALSE,
-                   WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
-                   WGL_SAMPLES_ARB, 4,                                         // Check For 4x Multisampling
-                   0,0
+               WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
+               WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
+               WGL_COLOR_BITS_ARB,24,
+               WGL_ALPHA_BITS_ARB,8,
+               WGL_DEPTH_BITS_ARB,16,
+               WGL_STENCIL_BITS_ARB,0,
+               WGL_DOUBLE_BUFFER_ARB,GL_FALSE,
+               WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
+               WGL_SAMPLES_ARB, 4,                  // Check For 4x Multisampling
+               0,0
             };
 
             //Log("Found wglChoosePixelFormatARB\n");
@@ -1837,7 +1418,7 @@ class OpenGLDisplayDriver : DisplayDriver
 
          oglDisplay.pBuffer = wglCreatePbufferARB(oglSystem.hdc, pixelFormat, width, height, attributes);
          oglDisplay.hdc = wglGetPbufferDCARB(oglDisplay.pBuffer);
-         if((oglDisplay.glrc = wglCreateContext(oglDisplay.hdc)))
+         if((oglDisplay.glrc = winCreateContext(oglDisplay.hdc)))
          {
             BITMAPINFO * info;
             HDC hdc = GetDC(display.window);
@@ -1913,36 +1494,36 @@ class OpenGLDisplayDriver : DisplayDriver
             ReleaseDC(display.window, hdc);
          }
 #elif defined(__unix__) || defined(__APPLE__)
-      #if defined(__ANDROID__)
+      #if defined(__ANDROID__) || defined(__ODROID__) || defined(__EMSCRIPTEN__)
          result = true;
       #else
-       int attrib[] =
-       {
-               GLX_DOUBLEBUFFER,  True,
+         int attrib[] =
+         {
+            GLX_DOUBLEBUFFER,  True,
             GLX_DEPTH_SIZE,    1,
-               GLX_RED_SIZE,      8,
-               GLX_GREEN_SIZE,    8,
-               GLX_BLUE_SIZE,     8,
-               GLX_ALPHA_SIZE,    8,
-               GLX_STENCIL_SIZE,  1,
-               //GLX_DEPTH_SIZE,    24,
-               GLX_RENDER_TYPE,   GLX_RGBA_BIT,
-               GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
-               None
-       };
-
-       int PBattrib[] =
-       {
-               GLX_PBUFFER_WIDTH,   width,
-               GLX_PBUFFER_HEIGHT,  height,
-               GLX_LARGEST_PBUFFER, False,
+            GLX_RED_SIZE,      8,
+            GLX_GREEN_SIZE,    8,
+            GLX_BLUE_SIZE,     8,
+            GLX_ALPHA_SIZE,    8,
+            GLX_STENCIL_SIZE,  1,
+            //GLX_DEPTH_SIZE,    24,
+            GLX_RENDER_TYPE,   GLX_RGBA_BIT,
+            GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
+            None
+         };
+
+         int PBattrib[] =
+         {
+            GLX_PBUFFER_WIDTH,   width,
+            GLX_PBUFFER_HEIGHT,  height,
+            GLX_LARGEST_PBUFFER, False,
             None
-       };
+         };
 
-       // choose a pixel format that meets our minimum requirements
-       int count = 0;
+         // choose a pixel format that meets our minimum requirements
+         int count = 0;
 
-       GLXFBConfig *config = glXChooseFBConfig(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib, &count);
+         GLXFBConfig *config = glXChooseFBConfig(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib, &count);
          if(config)
          {
             if(oglDisplay.pixmap)
@@ -1991,18 +1572,18 @@ class OpenGLDisplayDriver : DisplayDriver
                XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
 
             if(oglDisplay.glContext)
-                 glXDestroyContext(xGlobalDisplay, oglDisplay.glContext);
+              glXDestroyContext(xGlobalDisplay, oglDisplay.glContext);
             if(oglDisplay.pBuffer)
                glXDestroyPbuffer(xGlobalDisplay, oglDisplay.pBuffer);
 
-               oglDisplay.pBuffer = glXCreatePbuffer(xGlobalDisplay, config[0], PBattrib);
+            oglDisplay.pBuffer = glXCreatePbuffer(xGlobalDisplay, config[0], PBattrib);
             if(oglDisplay.pBuffer)
             {
-                  oglDisplay.glContext = glXCreateNewContext(xGlobalDisplay, config[0], GLX_RGBA_TYPE, oglSystem.glContext, True);
+               oglDisplay.glContext = glXCreateNewContext(xGlobalDisplay, config[0], GLX_RGBA_TYPE, oglSystem.glContext, True);
                if(oglDisplay.glContext)
                {
                   glXMakeCurrent(xGlobalDisplay, None, null);
-                  glXMakeCurrent(xGlobalDisplay, (int)display.window, oglDisplay.glContext);
+                  glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
 
                   // Initialize Shared Memory Pixmap
                   oglDisplay.image = XShmCreateImage(xGlobalDisplay, DefaultVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 32,
@@ -2044,7 +1625,7 @@ class OpenGLDisplayDriver : DisplayDriver
                                           {
                                              XRenderPictureAttributes attributes = { 0 };
                                              XRenderPictFormat * format = XRenderFindStandardFormat(xGlobalDisplay, /*PictStandardRGB24*/ PictStandardARGB32);
-                                             #if !defined(__APPLE__) && !defined(__OLDX__)
+                                             #if !defined(__APPLE__)
                                              attributes.repeat = RepeatNormal;
                                              #else
                                              attributes.repeat = 1;
@@ -2077,17 +1658,23 @@ class OpenGLDisplayDriver : DisplayDriver
 #if defined(__WIN32__)
          wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
 #elif defined(__unix__) || defined(__APPLE__)
-      #if defined(__ANDROID__)
+      #if defined(__ANDROID__) || defined(__ODROID__)
          width = eglWidth;
          height = eglHeight;
+      #elif defined(__EMSCRIPTEN__)
+         emscripten_webgl_make_context_current(oglSystem.glc);
       #else
-         glXMakeCurrent(xGlobalDisplay, (int)display.window, oglDisplay.glContext);
+         glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
       #endif
 #endif
       }
       else
 #endif
          result = true;
+
+      if(display.alphaBlend && result)
+         initialDisplaySetup(display);
+
       if(!result && display.alphaBlend)
       {
          printf("Alpha blending windows not supported on this display\n");
@@ -2098,6 +1685,7 @@ class OpenGLDisplayDriver : DisplayDriver
       result = false;
 
       glViewport(0,0,width,height);
+      glMatrixMode(MatrixMode::projection);
       glLoadIdentity();
       glOrtho(0,width,height,0,0.0,1.0);
       displayWidth = display.width = width;
@@ -2107,7 +1695,11 @@ class OpenGLDisplayDriver : DisplayDriver
       {
          oglDisplay.flipBufW = width;
          oglDisplay.flipBufH = height;
+#if defined(_GLES) || defined(_GLES2)
+         result = true;
+#else
          oglDisplay.flippingBuffer = renew oglDisplay.flippingBuffer ColorAlpha [width * height];
+#endif
       }
       if(oglDisplay.flippingBuffer || !width || !height)
          result = true;
@@ -2145,11 +1737,16 @@ class OpenGLDisplayDriver : DisplayDriver
 
    void Update(Display display, Box updateBox)
    {
+#if defined(__WIN32__) || defined(USEPBUFFER)
       OGLDisplay oglDisplay = display.driverData;
+#endif
       //Logf("DisplayScreen\n");
 
-      glFlush();
-      glFinish();
+#if !defined(__ANDROID__)
+      /*glFlush();
+      glFinish();*/
+#endif
+
 #if defined(__WIN32__) || defined(USEPBUFFER)
       if(display.alphaBlend)
       {
@@ -2209,7 +1806,7 @@ class OpenGLDisplayDriver : DisplayDriver
 
             ReleaseDC(0, hdc);
 #elif defined(__unix__) || defined(__APPLE__)
-      #if defined(__ANDROID__)
+      #if defined(__ANDROID__) || defined(__ODROID__) || defined(__EMSCRIPTEN__)
       #else
             XTransform transform =
             {
@@ -2222,7 +1819,7 @@ class OpenGLDisplayDriver : DisplayDriver
             XRenderSetPictureTransform(xGlobalDisplay, oglDisplay.pixmapPicture, &transform);
             XRenderComposite(xGlobalDisplay, PictOpSrc, oglDisplay.pixmapPicture, None, oglDisplay.shapePicture, 0, 0, 0, 0, 0, 0, display.width, display.height);
             XRenderComposite(xGlobalDisplay, PictOpSrc, oglDisplay.pixmapPicture, None, oglDisplay.windowPicture, 0, 0, 0, 0, 0, 0, display.width, display.height);
-            #if !defined(__APPLE__) && !defined(__OLDX__)
+            #if !defined(__APPLE__)
             XShapeCombineMask(xGlobalDisplay, (X11Window)display.window, ShapeInput, 0, 0, oglDisplay.shapePixmap, ShapeSet);
             #else
             XShapeCombineMask(xGlobalDisplay, display.window, 2, 0, 0, oglDisplay.shapePixmap, ShapeSet);
@@ -2238,11 +1835,13 @@ class OpenGLDisplayDriver : DisplayDriver
 #if defined(__WIN32__)
          //wglSwapLayerBuffers(oglDisplay.hdc,WGL_SWAP_MAIN_PLANE);
          SwapBuffers(oglDisplay.hdc);
+         //ecere::sys::Sleep(0.1);
 #elif defined(__unix__) || defined(__APPLE__)
-      #if defined(__ANDROID__)
-         eglSwapBuffers(eglDisplay, eglSurface);
+      #if defined(__ANDROID__) || defined(__ODROID__)
+         egl_swap_buffers();
+      #elif defined(__EMSCRIPTEN__)
       #else
-         glXSwapBuffers(xGlobalDisplay, (int)display.window);
+         glXSwapBuffers(xGlobalDisplay, (GLXDrawable)display.window);
       #endif
 #endif
       }
@@ -2251,9 +1850,12 @@ class OpenGLDisplayDriver : DisplayDriver
 
    void FreeBitmap(DisplaySystem displaySystem, Bitmap bitmap)
    {
-      glDeleteTextures(1, (int *)&bitmap.driverData);
-      bitmap.driverData = 0;
-
+      if(bitmap.driverData)
+      {
+         GLuint tex = (GLuint)(uintptr)bitmap.driverData;
+         glDeleteTextures(1, &tex);
+         bitmap.driverData = 0;
+      }
       bitmap.driver = ((subclass(DisplayDriver))class(LFBDisplayDriver));
    }
 
@@ -2262,7 +1864,7 @@ class OpenGLDisplayDriver : DisplayDriver
       OGLSystem oglSystem = displaySystem.driverData;
       bool result = false;
       Bitmap mipMap { };
-      int glBitmap = -1;
+      GLuint glBitmap = 0;
 
       uint w = width, h = height;
       if(oglSystem.pow2textures)
@@ -2284,7 +1886,9 @@ class OpenGLDisplayDriver : DisplayDriver
       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 
+#if !defined(SHADERS)
       glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
+#endif
 
       mipMap.Allocate(null, w, h, w, pixelFormatRGBA, false);
 
@@ -2293,7 +1897,7 @@ class OpenGLDisplayDriver : DisplayDriver
 
       delete mipMap;
 
-      bitmap.driverData = (void *)glBitmap;
+      bitmap.driverData = (void *)(uintptr)glBitmap;
       bitmap.driver = displaySystem.driver;
       bitmap.width = w;
       bitmap.height = h;
@@ -2306,13 +1910,19 @@ class OpenGLDisplayDriver : DisplayDriver
    {
       bool result = false;
       OGLSystem oglSystem = displaySystem.driverData;
+      Bitmap convBitmap = bitmap;
+      if(bitmap.keepData)
+      {
+         convBitmap = { };
+         convBitmap.Copy(bitmap);
+      }
 
       // Pre process the bitmap... First make it 32 bit
-      if(/*bitmap.pixelFormat == pixelFormatRGBA || */bitmap.Convert(null, pixelFormat888, null))
+      if(/*bitmap.pixelFormat == pixelFormatRGBA || */convBitmap.Convert(null, pixelFormat888, null))
       {
          int c, level;
          uint w = bitmap.width, h = bitmap.height;
-         int glBitmap = -1;
+         GLuint glBitmap = 0;
          if(oglSystem.pow2textures)
          {
             w = pow2i(w);
@@ -2321,6 +1931,12 @@ class OpenGLDisplayDriver : DisplayDriver
          w = Min(w, oglSystem.maxTextureSize);
          h = Min(h, oglSystem.maxTextureSize);
 
+         if(mipMaps)
+         {
+            while(w * 2 < h) w *= 2;
+            while(h * 2 < w) h *= 2;
+         }
+
          // Switch ARGB to RGBA
          //if(bitmap.format != pixelFormatRGBA)
          {
@@ -2328,26 +1944,26 @@ class OpenGLDisplayDriver : DisplayDriver
             {
                // ((ColorRGBA *)bitmap.picture)[c] = ((ColorAlpha *)bitmap.picture)[c];
                // TODO:
-               ColorAlpha color = ((ColorAlpha *)bitmap.picture)[c];
-               ((ColorRGBA *)bitmap.picture)[c] = ColorRGBA { color.color.r, color.color.g, color.color.b, color.a };
+               ColorAlpha color = ((ColorAlpha *)convBitmap.picture)[c];
+               ((ColorRGBA *)convBitmap.picture)[c] = ColorRGBA { color.color.r, color.color.g, color.color.b, color.a };
             }
          }
-         bitmap.pixelFormat = pixelFormat888;
+         // convBitmap.pixelFormat = pixelFormat888;
 
          glGetError();
          glGenTextures(1, &glBitmap);
-         if(glBitmap == -1)
+         if(glBitmap == 0)
          {
-            int error = glGetError();
+            //int error = glGetError();
             return false;
-            //Print("");
          }
 
          glBindTexture(GL_TEXTURE_2D, glBitmap);
          glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
 
-         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mipMaps ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
+         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mipMaps ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
+         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+
          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
 
          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
@@ -2355,21 +1971,28 @@ class OpenGLDisplayDriver : DisplayDriver
 
          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+#ifdef GL_TEXTURE_MAX_ANISOTROPY_EXT
+         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 16.0 );
+#endif
 
+#if !defined(SHADERS)
          glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
+#endif
 
          result = true;
 
-         for(level = 0; result && (w > 1 || h > 1); level++, w >>= 1, h >>= 1)
+         for(level = 0; result && (w >= 1 || h >= 1); level++, w >>= 1, h >>= 1)
          {
             Bitmap mipMap;
+            if(!w) w = 1;
+            if(!h) h = 1;
             if(bitmap.width != w || bitmap.height != h)
             {
                mipMap = Bitmap { };
-               if(mipMap.Allocate(null, w, h, w, bitmap.pixelFormat, false))
+               if(mipMap.Allocate(null, w, h, w, convBitmap.pixelFormat, false))
                {
                   Surface mipSurface = mipMap.GetSurface(0,0,null);
-                  mipSurface.Filter(bitmap, 0,0,0,0, w, h, bitmap.width, bitmap.height);
+                  mipSurface.Filter(convBitmap, 0,0,0,0, w, h, convBitmap.width, convBitmap.height);
                   delete mipSurface;
                }
                else
@@ -2379,7 +2002,7 @@ class OpenGLDisplayDriver : DisplayDriver
                }
             }
             else
-               mipMap = bitmap;
+               mipMap = convBitmap;
 
             if(result)
             {
@@ -2398,15 +2021,16 @@ class OpenGLDisplayDriver : DisplayDriver
                   result = false;
                }
             }
-            if(mipMap != bitmap)
+            if(mipMap != convBitmap)
                delete mipMap;
             if(!mipMaps) break;
          }
 
-         if(!bitmap.keepData)
-            bitmap.driver.FreeBitmap(bitmap.displaySystem, bitmap);
-         bitmap.driverData = (void *)glBitmap;
+         convBitmap.driver.FreeBitmap(convBitmap.displaySystem, convBitmap);
+         bitmap.driverData = (void *)(uintptr)glBitmap;
          bitmap.driver = displaySystem.driver;
+         if(bitmap.keepData)
+            delete convBitmap;
 
          if(!result)
             FreeBitmap(displaySystem, bitmap);
@@ -2610,7 +2234,7 @@ class OpenGLDisplayDriver : DisplayDriver
 
       glColor4fv(oglSurface.foreground);
       glBegin(GL_LINES);
-#ifdef __ANDROID__
+#if defined(_GLES) || defined(_GLES2) || defined(SHADERS)
       if(stippleEnabled)
       {
          glTexCoord2f(0.5f, 0);
@@ -2643,7 +2267,7 @@ class OpenGLDisplayDriver : DisplayDriver
       //Logf("Rectangle\n");
 
       glColor4fv(oglSurface.foreground);
-#ifdef __ANDROID__
+#if defined(_GLES) || defined(_GLES2) || defined(SHADERS)
       if(stippleEnabled)
       {
          glBegin(GL_LINES);
@@ -2692,9 +2316,9 @@ class OpenGLDisplayDriver : DisplayDriver
       //Logf("Area\n");
 
       glColor4fv(oglSurface.background);
+
       glRecti(x1+surface.offset.x, y1+surface.offset.y,
               x2+surface.offset.x + 1, y2+surface.offset.y + 1);
-
       /*
       glRectf(x1+surface.offset.x, y1+surface.offset.y,
               x2+surface.offset.x + 1, y2+surface.offset.y + 1);
@@ -2730,23 +2354,17 @@ class OpenGLDisplayDriver : DisplayDriver
    {
       OGLSurface oglSurface = surface.driverData;
 
-#if !defined(__OLDX__)
-         // WHY DO WE HAVE GL_ONE HERE ?
-         /*if(glBlendFuncSeparate && !oglSurface.writingText)
-            glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
-#endif
-
       if(!oglSurface.writingText)
       {
          // glTranslatef(-0.375f, -0.375f, 0.0f);
-         glEnable(GL_TEXTURE_2D);
+         GLSetupTexturing(true);
          glColor4fv(oglSurface.bitmapMult);
       }
       else if(oglSurface.xOffset)
          glTranslated(oglSurface.xOffset / 64.0/*-0.375*/, 0.0, 0.0);
 
-      glBindTexture(GL_TEXTURE_2D, (uint)bitmap.driverData);
-      glBegin(GL_QUADS);
+      glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)bitmap.driverData);
+      glBegin(GLIMTKMode::quads);
 
       if(h < 0)
       {
@@ -2785,17 +2403,12 @@ class OpenGLDisplayDriver : DisplayDriver
 
       if(!oglSurface.writingText)
       {
-         glDisable(GL_TEXTURE_2D);
+         GLSetupTexturing(false);
 
          //glTranslate(0.375, 0.375, 0.0);
       }
       else if(oglSurface.xOffset)
          glTranslated(-oglSurface.xOffset / 64.0/*+0.375*/, 0.0, 0.0);
-
-#if !defined(__OLDX__)
-         /*if(glBlendFuncSeparate && !oglSurface.writingText)
-            glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
-#endif
    }
 
    void Stretch(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
@@ -2804,19 +2417,12 @@ class OpenGLDisplayDriver : DisplayDriver
 
       //glTranslate(-0.375, -0.375, 0.0);
 
-      //Logf("Stretch\n");
-
-#if !defined(__OLDX__)
-      /*if(glBlendFuncSeparate)
-         glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
-#endif
-
-      glEnable(GL_TEXTURE_2D);
-      glBindTexture(GL_TEXTURE_2D, (uint)bitmap.driverData);
+      GLSetupTexturing(true);
+      glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)bitmap.driverData);
 
       glColor4fv(oglSurface.bitmapMult);
 
-      glBegin(GL_QUADS);
+      glBegin(GLIMTKMode::quads);
 
       if(h < 0)
       {
@@ -2849,14 +2455,9 @@ class OpenGLDisplayDriver : DisplayDriver
 
       glEnd();
 
-      glDisable(GL_TEXTURE_2D);
+      GLSetupTexturing(false);
 
       //glTranslate(0.375, 0.375, 0.0);
-#if !defined(__OLDX__)
-      /*if(glBlendFuncSeparate)
-         glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
-#endif
-
    }
 
    void Filter(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
@@ -2867,7 +2468,7 @@ class OpenGLDisplayDriver : DisplayDriver
    void StretchDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
    {
       float s2dw,s2dh,d2sw,d2sh;
-      bool flipX = false, flipY = false;
+      //bool flipX = false, flipY = false;
 
       //Logf("StretchDI\n");
 
@@ -2875,13 +2476,13 @@ class OpenGLDisplayDriver : DisplayDriver
       {
          w = Abs(w);
          sw = Abs(sw);
-         flipX = true;
+         //flipX = true;
       }
       if(Sgn(h) != Sgn(sh))
       {
          h = Abs(h);
          sh = Abs(sh);
-         flipY = true;
+         //flipY = true;
       }
 
       s2dw=(float)w / sw;
@@ -2953,10 +2554,12 @@ class OpenGLDisplayDriver : DisplayDriver
          glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.stride);
          glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
          glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
+#if !defined(SHADERS)
          glRasterPos2d(dx,dy);
          //glPixelZoom(flipX ? -s2dw : s2dw, flipY ? s2dh : -s2dh);
          glPixelZoom(s2dw, -s2dh);
          glDrawPixels(sw,sh,GL_BGRA_EXT,GL_UNSIGNED_BYTE, bitmap.picture);
+#endif
          glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
          glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
          glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
@@ -3018,9 +2621,11 @@ class OpenGLDisplayDriver : DisplayDriver
          glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.stride);
          glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
          glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
+#if !defined(SHADERS)
          glRasterPos2d(dx,dy);
          glPixelZoom(1,-1);
          glDrawPixels(w,h,GL_BGRA_EXT,GL_UNSIGNED_BYTE, bitmap.picture);
+#endif
          glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
          glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
          glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
@@ -3038,21 +2643,21 @@ class OpenGLDisplayDriver : DisplayDriver
       ((subclass(DisplayDriver))class(LFBDisplayDriver)).UnloadFont(displaySystem, font);
    }
 
-   Font LoadFont(DisplaySystem displaySystem, char * faceName, float size, FontFlags flags)
+   Font LoadFont(DisplaySystem displaySystem, const char * faceName, float size, FontFlags flags, float outlineSize, float outlineFade)
    {
       Font font;
       OGLSystem oglSystem = displaySystem.driverData;
       oglSystem.loadingFont = true;
-      font = ((subclass(DisplayDriver))class(LFBDisplayDriver)).LoadFont(displaySystem, faceName, size, flags);
+      font = ((subclass(DisplayDriver))class(LFBDisplayDriver)).LoadFont(displaySystem, faceName, size, flags, outlineSize, outlineFade);
       return font;
    }
 
-   void FontExtent(DisplaySystem displaySystem, Font font, char * text, int len, int * width, int * height)
+   void FontExtent(DisplaySystem displaySystem, Font font, const char * text, int len, int * width, int * height, int prevGlyph, int * rPrevGlyph, int * adv)
    {
-      ((subclass(DisplayDriver))class(LFBDisplayDriver)).FontExtent(displaySystem, font, text, len, width, height);
+      ((subclass(DisplayDriver))class(LFBDisplayDriver)).FontExtent(displaySystem, font, text, len, width, height, prevGlyph, rPrevGlyph, adv);
    }
 
-   void WriteText(Display display, Surface surface, int x, int y, char * text, int len)
+   void WriteText(Display display, Surface surface, int x, int y, const char * text, int len, int prevGlyph, int * rPrevGlyph)
    {
       OGLSurface oglSurface = surface.driverData;
       OGLSystem oglSystem = display.displaySystem.driverData;
@@ -3064,21 +2669,31 @@ class OpenGLDisplayDriver : DisplayDriver
 
       if(surface.textOpacity)
       {
-         int w, h;
-         FontExtent(display.displaySystem, surface.font, text, len, &w, &h);
+         int w, h, adv;
+         FontExtent(display.displaySystem, surface.font, text, len, &w, &h, 0, null, &adv);
+         w += adv;
          display.displaySystem.driver.Area(display, surface,x,y,x+w-1,y+h-1);
       }
 
       oglSurface.writingText = true;
 
-      glEnable(GL_TEXTURE_2D);
+      GLSetupTexturing(true);
+
+      if(surface.font.outlineSize)
+      {
+         ColorAlpha outlineColor = surface.outlineColor;
+         glColor4ub(outlineColor.color.r, outlineColor.color.g, outlineColor.color.b, outlineColor.a);
+         oglSurface.writingOutline = true;
+         ((subclass(DisplayDriver))class(LFBDisplayDriver)).WriteText(display, surface, x, y, text, len, prevGlyph, rPrevGlyph);
+         oglSurface.writingOutline = false;
+      }
       glColor4fv(oglSurface.foreground);
 
-      ((subclass(DisplayDriver))class(LFBDisplayDriver)).WriteText(display, surface, x, y, text, len);
+      ((subclass(DisplayDriver))class(LFBDisplayDriver)).WriteText(display, surface, x, y, text, len, prevGlyph, rPrevGlyph);
       oglSurface.writingText = false;
       oglSystem.loadingFont = false;
 
-      glDisable(GL_TEXTURE_2D);
+      GLSetupTexturing(false);
 
       //glTranslated(0.375, 0.375, 0.0);
    }
@@ -3094,12 +2709,12 @@ class OpenGLDisplayDriver : DisplayDriver
       oglSurface.opaqueText = opaque;
    }
 
-   void TextExtent(Display display, Surface surface, char * text, int len, int * width, int * height)
+   void TextExtent(Display display, Surface surface, const char * text, int len, int * width, int * height, int prevGlyph, int * rPrevGlyph, int * adv)
    {
       OGLSurface oglSurface = surface.driverData;
       OGLSystem oglSystem = display.displaySystem.driverData;
       oglSystem.loadingFont = true;
-      FontExtent(display.displaySystem, oglSurface.font, text, len, width, height);
+      FontExtent(display.displaySystem, oglSurface.font, text, len, width, height, prevGlyph, rPrevGlyph, adv);
       oglSystem.loadingFont = false;
    }
 
@@ -3114,7 +2729,7 @@ class OpenGLDisplayDriver : DisplayDriver
 
       if(stipple)
       {
-#if defined(__ANDROID__)
+#if defined(_GLES) || defined(_GLES2) || defined(SHADERS)
          stippleEnabled = true;
          glesLineStipple(1, (uint16)stipple);
 #else
@@ -3124,17 +2739,18 @@ class OpenGLDisplayDriver : DisplayDriver
       }
       else
       {
-#if defined(__ANDROID__)
+#if defined(_GLES) || defined(_GLES2) || defined(SHADERS)
          stippleEnabled = false;
          glMatrixMode(GL_TEXTURE);
          glLoadIdentity();
-         glMatrixMode(GL_PROJECTION);
-         glDisable(GL_TEXTURE_2D);
+         glMatrixMode(MatrixMode::projection);
+         GLSetupTexturing(false);   // TODO: Special shading code for stipple?
 #else
          glDisable(GL_LINE_STIPPLE);
 #endif
       }
    }
+
 #if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
    void SetRenderState(Display display, RenderState state, uint value)
    {
@@ -3144,38 +2760,55 @@ class OpenGLDisplayDriver : DisplayDriver
       switch(state)
       {
          case antiAlias:
+#ifndef __EMSCRIPTEN__
             if(value)
                glEnable(GL_MULTISAMPLE_ARB);
             else
                glDisable(GL_MULTISAMPLE_ARB);
+#endif
             break;
          case fillMode:
+#if !defined(_GLES) && !defined(_GLES2)
             glPolygonMode(GL_FRONT_AND_BACK, ((FillModeValue)value == solid) ? GL_FILL : GL_LINE);
+#endif
             break;
          case depthTest:
             if(value) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
             break;
          case depthWrite:
             if(value) glDepthMask((byte)bool::true); else glDepthMask((byte)bool::false);
-            oglDisplay.depthWrite = value;
+            oglDisplay.depthWrite = (bool)value;
             break;
          case fogColor:
          {
             float color[4] = { ((Color)value).r/255.0f, ((Color)value).g/255.0f, ((Color)value).b/255.0f, 1.0f };
+#if defined(SHADERS)
+            shader_fogColor(color[0], color[1], color[2]);
+#else
             glFogfv(GL_FOG_COLOR, (float *)&color);
+#endif
             break;
          }
          case fogDensity:
-            value *= nearPlane;
-            glFogf(GL_FOG_DENSITY, *(float *)(void *)&value);
+#if defined(SHADERS)
+            shader_fogDensity((float)(RenderStateFloat { ui = value }.f * nearPlane));
+#else
+            glFogf(GL_FOG_DENSITY, (float)(RenderStateFloat { ui = value }.f * nearPlane));
+#endif
             break;
          case blend:
+//#if !defined(__EMSCRIPTEN__)
             if(value) glEnable(GL_BLEND); else glDisable(GL_BLEND);
+//#endif
             break;
          case ambient:
          {
+#if defined(SHADERS)
+            shader_setGlobalAmbient(((Color)value).r / 255.0f, ((Color)value).g / 255.0f, ((Color)value).b / 255.0f, 1.0f);
+#else
             float ambient[4] = { ((Color)value).r/255.0f, ((Color)value).g/255.0f, ((Color)value).b/255.0f, 1.0f };
             glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
+#endif
             break;
          }
          case alphaWrite:
@@ -3186,7 +2819,8 @@ class OpenGLDisplayDriver : DisplayDriver
          case vSync:
          {
 #if defined(__WIN32__)
-            wglSwapIntervalEXT(value ? 1 : 0);
+            if(wglSwapIntervalEXT)
+               wglSwapIntervalEXT(value ? 1 : 0);
 #endif
             break;
          }
@@ -3195,6 +2829,9 @@ class OpenGLDisplayDriver : DisplayDriver
 
    void SetLight(Display display, int id, Light light)
    {
+#if defined(SHADERS)
+      shader_setLight(display, id, light);
+#else
       //Logf("SetLight\n");
 
       if(light != null)
@@ -3329,7 +2966,6 @@ class OpenGLDisplayDriver : DisplayDriver
          }
          else
          {
-
             Vector3Df vector { 0,0,-1 };
             Vector3Df direction;
             Matrix mat;
@@ -3346,6 +2982,7 @@ class OpenGLDisplayDriver : DisplayDriver
       }
       else
          glDisable(GL_LIGHT0 + id);
+#endif
    }
 
    void SetCamera(Display display, Surface surface, Camera camera)
@@ -3353,7 +2990,7 @@ class OpenGLDisplayDriver : DisplayDriver
       OGLDisplay oglDisplay = display.driverData;
       //Logf("SetCamera\n");
 
-      if(camera)
+      if(surface && camera)
       {
          int left = surface.box.left + surface.offset.x;
          int top = surface.box.top  + surface.offset.y;
@@ -3370,15 +3007,15 @@ class OpenGLDisplayDriver : DisplayDriver
          glViewport(x, y, w, h);
 
          // *** Projection Matrix ***
+         glMatrixMode(MatrixMode::projection);
          if(!display.display3D.camera)
             glPushMatrix();
-         else
-            glMatrixMode(GL_PROJECTION);
+
          if(display.display3D.collectingHits)
          {
             float pickX = display.display3D.pickX + surface.offset.x;
             float pickY = display.height - (display.display3D.pickY + surface.offset.y) - 1;
-            Matrix pickMatrix =
+            Matrix pickMatrix
             {
                {
                   w / display.display3D.pickWidth, 0, 0, 0,
@@ -3402,7 +3039,7 @@ class OpenGLDisplayDriver : DisplayDriver
          glDisable(GL_BLEND);
 
          // *** Z Inverted Identity Matrix ***
-         glMatrixMode(GL_MODELVIEW);
+         glMatrixMode(MatrixMode::modelView);
          if(!display.display3D.camera)
             glPushMatrix();
 
@@ -3417,36 +3054,52 @@ class OpenGLDisplayDriver : DisplayDriver
          // ...
 
          glEnable(GL_DEPTH_TEST);
-         glEnable(GL_LIGHTING);
+
+         GLSetupLighting(true);
+#if !defined(SHADERS)
          glShadeModel(GL_SMOOTH);
+#endif
          glDepthMask((byte)bool::true);
          oglDisplay.depthWrite = true;
 
+#ifndef __EMSCRIPTEN__
          glEnable(GL_MULTISAMPLE_ARB);
+#endif
       }
-      else if(display.display3D.camera)
+      else if(surface && display.display3D.camera)
       {
+         nearPlane = 1;
          oglDisplay.depthWrite = false;
          glViewport(0,0,display.width,display.height);
 
          glDisable(GL_CULL_FACE);
          glDisable(GL_DEPTH_TEST);
-         glDisable(GL_LIGHTING);
-         glDisable(GL_FOG);
-         glDisable(GL_TEXTURE_2D);
+
+
+         GLSetupTexturing(false);
+         GLSetupLighting(false);
+         GLSetupFog(false);
+
+         glDisableClientState(GL_COLOR_ARRAY);
+
+#if defined(SHADERS)
+         shader_setPerVertexColor(false);
+#else
          glShadeModel(GL_FLAT);
+#endif
          glEnable(GL_BLEND);
+#if !defined(__EMSCRIPTEN__)
          glDisable(GL_MULTISAMPLE_ARB);
+#endif
 
          // *** Restore 2D MODELVIEW Matrix ***
          glPopMatrix();
 
          // *** Restore 2D PROJECTION Matrix ***
-         glMatrixMode(GL_PROJECTION);
+         glMatrixMode(MatrixMode::projection);
          glPopMatrix();
       }
 
-      GLBindBuffer(GL_ARRAY_BUFFER_ARB, 0);
    }
 
    void ApplyMaterial(Display display, Material material, Mesh mesh)
@@ -3456,27 +3109,34 @@ class OpenGLDisplayDriver : DisplayDriver
       // Basic Properties
       if(material.flags.doubleSided)
       {
+#if !defined(SHADERS)
          glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, !material.flags.singleSideLight);
+#endif
          glDisable(GL_CULL_FACE);
       }
       else
       {
+#if !defined(SHADERS)
          glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, bool::false);
+#endif
          glEnable(GL_CULL_FACE);
       }
 
       // Fog
-      if(material.flags.noFog)
-         glDisable(GL_FOG);
-      else
-         glEnable(GL_FOG);
+      GLSetupFog(!material.flags.noFog);
 
       // Maps
-      if(material.baseMap && mesh.texCoords)
+      if(material.baseMap && (mesh.texCoords || mesh.flags.texCoords1))
       {
          Bitmap map = material.baseMap;
-         glEnable(GL_TEXTURE_2D);
-         glBindTexture(GL_TEXTURE_2D, (uint)map.driverData);
+         GLSetupTexturing(true);
+         glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)map.driverData);
+
+         glMatrixMode(GL_TEXTURE);
+         glLoadIdentity();
+         if(material.uScale && material.vScale)
+            glScalef(material.uScale, material.vScale, 1);
+         glMatrixMode(MatrixMode::modelView);
 
          if(material.flags.tile)
          {
@@ -3490,8 +3150,11 @@ class OpenGLDisplayDriver : DisplayDriver
          }
       }
       else
-         glDisable(GL_TEXTURE_2D);
+         GLSetupTexturing(false);
 
+#if defined(SHADERS)
+      shader_setMaterial(material, mesh.flags.colors);
+#else
       if(mesh.flags.colors)
       {
          glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
@@ -3519,6 +3182,7 @@ class OpenGLDisplayDriver : DisplayDriver
       }
 
       glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &material.power);
+#endif
    }
 
    void FreeMesh(DisplaySystem displaySystem, Mesh mesh)
@@ -3528,49 +3192,28 @@ class OpenGLDisplayDriver : DisplayDriver
       {
          if(!mesh.flags.vertices)
          {
-            if(oglMesh.vertices)
-            {
-               GLDeleteBuffers(1, &oglMesh.vertices);
-               oglMesh.vertices = 0;
-            }
+            oglMesh.vertices.free();
             delete mesh.vertices;
          }
          if(!mesh.flags.normals)
          {
-            if(oglMesh.normals)
-            {
-               GLDeleteBuffers(1, &oglMesh.normals);
-               oglMesh.normals = 0;
-            }
+            oglMesh.normals.free();
             delete mesh.normals;
          }
          if(!mesh.flags.texCoords1)
          {
-            if(oglMesh.texCoords)
-            {
-               GLDeleteBuffers(1, &oglMesh.texCoords);
-               oglMesh.texCoords = 0;
-            }
+            oglMesh.texCoords.free();
             delete mesh.texCoords;
          }
          if(!mesh.flags.texCoords2)
          {
-            if(oglMesh.texCoords2)
-            {
-               GLDeleteBuffers(1, &oglMesh.texCoords2);
-               oglMesh.texCoords2 = 0;
-            }
-            /*
-            delete mesh.texCoords2;
-            */
+            oglMesh.texCoords2.free();
+            // delete mesh.texCoords2;
          }
          if(!mesh.flags.colors)
          {
-            if(oglMesh.colors)
-            {
-               GLDeleteBuffers(1, &oglMesh.colors);
-               oglMesh.colors = 0;
-            }
+            oglMesh.colors.free();
+            delete mesh.colors;
          }
          if(!mesh.flags)
          {
@@ -3580,7 +3223,7 @@ class OpenGLDisplayDriver : DisplayDriver
       }
    }
 
-   bool AllocateMesh(DisplaySystem displaySystem, Mesh mesh)
+   bool AllocateMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags, int nVertices)
    {
       bool result = false;
 
@@ -3588,27 +3231,69 @@ class OpenGLDisplayDriver : DisplayDriver
          mesh.data = OGLMesh { };
       if(mesh.data)
       {
-         OGLMesh oglMesh = mesh.data;
-
-         if(mesh.flags.vertices && !oglMesh.vertices && !mesh.vertices)
-         {
-            mesh.vertices = mesh.flags.doubleVertices ? (Vector3Df *)new Vector3D[mesh.nVertices] : new Vector3Df[mesh.nVertices];
-            GLGenBuffers(1, &oglMesh.vertices);
-         }
-         if(mesh.flags.normals && !oglMesh.normals && !mesh.normals)
-         {
-            GLGenBuffers( 1, &oglMesh.normals);
-            mesh.normals = mesh.flags.doubleNormals ? (Vector3Df *)new Vector3D[mesh.nVertices] : new Vector3Df[mesh.nVertices];
-         }
-         if(mesh.flags.texCoords1 && !oglMesh.texCoords && !mesh.texCoords)
+         if(mesh.nVertices == nVertices)
          {
-            GLGenBuffers( 1, &oglMesh.texCoords);
-            mesh.texCoords = new Pointf[mesh.nVertices];
+            // Same number of vertices, adding features (Leaves the other features pointers alone)
+            if(mesh.flags != flags)
+            {
+               if(!mesh.flags.vertices && flags.vertices)
+               {
+                  if(flags.doubleVertices)
+                  {
+                     mesh.vertices = (Vector3Df *)new Vector3D[nVertices];
+                  }
+                  else
+                     mesh.vertices = new Vector3Df[nVertices];
+               }
+               if(!mesh.flags.normals && flags.normals)
+               {
+                  if(flags.doubleNormals)
+                  {
+                     mesh.normals = (Vector3Df *)new Vector3D[nVertices];
+                  }
+                  else
+                     mesh.normals = new Vector3Df[nVertices];
+               }
+               if(!mesh.flags.texCoords1 && flags.texCoords1)
+               {
+                  mesh.texCoords = new Pointf[nVertices];
+               }
+               if(!mesh.flags.colors && flags.colors)
+               {
+                  mesh.colors = new ColorRGBAf[nVertices];
+               }
+            }
          }
-         if(mesh.flags.colors && !oglMesh.colors && !mesh.colors)
+         else
          {
-            GLGenBuffers( 1, &oglMesh.colors);
-            mesh.colors = new ColorRGBAf[mesh.nVertices];
+            // New number of vertices, reallocate all current and new features
+            flags |= mesh.flags;
+            if(flags.vertices)
+            {
+               if(flags.doubleVertices)
+               {
+                  mesh.vertices = (Vector3Df *)renew mesh.vertices Vector3D[nVertices];
+               }
+               else
+                  mesh.vertices = renew mesh.vertices Vector3Df[nVertices];
+            }
+            if(flags.normals)
+            {
+               if(flags.doubleNormals)
+               {
+                  mesh.normals = (Vector3Df *)renew mesh.normals Vector3D[nVertices];
+               }
+               else
+                  mesh.normals = renew mesh.normals Vector3Df[nVertices];
+            }
+            if(flags.texCoords1)
+            {
+               mesh.texCoords = renew mesh.texCoords Pointf[nVertices];
+            }
+            if(flags.colors)
+            {
+               mesh.colors = renew mesh.colors ColorRGBAf[nVertices];
+            }
          }
          result = true;
       }
@@ -3622,31 +3307,21 @@ class OpenGLDisplayDriver : DisplayDriver
 
       if(vboAvailable)
       {
-         if(!(flags.vertices) || oglMesh.vertices)
-         {
-            GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.vertices);
-            GLBufferData( mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT, GL_ARRAY_BUFFER_ARB, mesh.nVertices * (mesh.flags.doubleVertices ? sizeof(Vector3D) : sizeof(Vector3Df)), mesh.vertices, GL_STATIC_DRAW_ARB );
-         }
-
-         if(!(flags.normals) || oglMesh.normals)
-         {
-            GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.normals);
-            GLBufferData( mesh.flags.doubleNormals ? GL_DOUBLE : GL_FLOAT, GL_ARRAY_BUFFER_ARB, mesh.nVertices * (mesh.flags.doubleNormals ? sizeof(Vector3D) : sizeof(Vector3Df)), mesh.normals, GL_STATIC_DRAW_ARB );
-         }
+         if(flags.vertices)
+            oglMesh.vertices.upload(
+               mesh.nVertices * (mesh.flags.doubleVertices ? sizeof(Vector3D) : sizeof(Vector3Df)), mesh.vertices); //, GL_STATIC_DRAW_ARB );
 
-         if(!(flags.texCoords1) || oglMesh.texCoords)
-         {
-            GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.texCoords);
-            GLBufferData( GL_FLOAT, GL_ARRAY_BUFFER_ARB, mesh.nVertices * sizeof(Pointf), mesh.texCoords, GL_STATIC_DRAW_ARB );
-         }
+         if(flags.normals)
+            oglMesh.normals.upload(
+               mesh.nVertices * (mesh.flags.doubleNormals ? sizeof(Vector3D) : sizeof(Vector3Df)), mesh.normals); //, GL_STATIC_DRAW_ARB );
 
-         if(!(flags.colors) || oglMesh.colors)
-         {
-            GLBindBuffer( GL_ARRAY_BUFFER_ARB, oglMesh.colors);
-            GLBufferData( GL_FLOAT, GL_ARRAY_BUFFER_ARB, mesh.nVertices * sizeof(ColorRGBAf), mesh.colors, GL_STATIC_DRAW_ARB );
-         }
+         if(flags.texCoords1)
+            oglMesh.texCoords.upload(
+               mesh.nVertices * sizeof(Pointf), mesh.texCoords); //, GL_STATIC_DRAW_ARB );
 
-         GLBindBuffer( GL_ARRAY_BUFFER_ARB, 0);
+         if(flags.colors)
+            oglMesh.colors.upload(
+               mesh.nVertices * sizeof(ColorRGBAf), mesh.colors); //, GL_STATIC_DRAW_ARB );
       }
    }
 
@@ -3654,15 +3329,14 @@ class OpenGLDisplayDriver : DisplayDriver
    {
       bool result = true;
 
-       return result;
+      return result;
    }
 
    void FreeIndices(DisplaySystem displaySystem, OGLIndices oglIndices)
    {
       if(oglIndices)
       {
-         if(oglIndices.buffer)
-            GLDeleteBuffers(1, &oglIndices.buffer);
+         oglIndices.buffer.free();
          delete oglIndices.indices;
          delete oglIndices;
       }
@@ -3674,7 +3348,6 @@ class OpenGLDisplayDriver : DisplayDriver
       if(oglIndices)
       {
          oglIndices.indices = (void *)(indices32bit ? new uint32[nIndices] : new uint16[nIndices]);
-         GLGenBuffers( 1, &oglIndices.buffer);
          oglIndices.nIndices = nIndices;
       }
       return oglIndices;
@@ -3684,10 +3357,20 @@ class OpenGLDisplayDriver : DisplayDriver
    {
       if(vboAvailable)
       {
-         GLBindBuffer( GL_ELEMENT_ARRAY_BUFFER_ARB, oglIndices.buffer);
-         GLBufferData( indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, GL_ELEMENT_ARRAY_BUFFER_ARB, nIndices * (indices32bit ? sizeof(uint32) : sizeof(uint16)),
-            oglIndices.indices, GL_STATIC_DRAW_ARB);
-         GLBindBuffer( GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
+#if defined(_GLES) || defined(_GLES2)
+         if(indices32bit)
+         {
+            if(!oglIndices.buffer.buffer)
+               glGenBuffers(1, &oglIndices.buffer.buffer);
+            if(glabCurElementBuffer != oglIndices.buffer.buffer)
+               GLABBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oglIndices.buffer.buffer);
+            glimtkBufferDatai(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint32) * nIndices, oglIndices.indices, GL_STATIC_DRAW_ARB);
+         }
+         else
+#endif
+         oglIndices.buffer.upload(
+            nIndices * (indices32bit ? sizeof(uint32) : sizeof(uint16)),
+            oglIndices.indices); //GL_STATIC_DRAW_ARB);
       }
    }
 
@@ -3701,91 +3384,92 @@ class OpenGLDisplayDriver : DisplayDriver
    {
       //Logf("SelectMesh\n");
 
-#if !defined( __ANDROID__) && !defined(__APPLE__)
-      if(display.display3D.mesh && glUnlockArraysEXT)
-         glUnlockArraysEXT();
+#if !defined( __ANDROID__) && !defined(__APPLE__) && !defined(__ODROID__) && !defined(__EMSCRIPTEN__)
+
+#if defined(__WIN32__)
+      if(glUnlockArraysEXT)
+#endif
+         if(!vboAvailable && display.display3D.mesh)
+            glUnlockArraysEXT();
+
 #endif
       if(mesh)
       {
-         OGLDisplay oglDisplay = display.driverData;
          OGLMesh oglMesh = mesh.data;
 
          // *** Vertex Stream ***
          glEnableClientState(GL_VERTEX_ARRAY);
          if(!display.display3D.collectingHits && oglMesh)
          {
-            GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.vertices );
-            glVertexPointer(3, mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT, 0, vboAvailable ? null : mesh.vertices);
+            oglMesh.vertices.use(vertex, 3, (mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT), 0, oglMesh.vertices.buffer ? null : (double *)mesh.vertices);
 
             // *** Normals Stream ***
-            if(mesh.normals)
+            if(mesh.normals || mesh.flags.normals)
             {
                glEnableClientState(GL_NORMAL_ARRAY);
-               GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.normals);
-               glNormalPointer(mesh.flags.doubleNormals ? GL_DOUBLE : GL_FLOAT, 0, vboAvailable ? null : mesh.normals);
+               oglMesh.normals.use(normal, 3, GL_FLOAT, 0, oglMesh.normals.buffer ? null : mesh.normals);
             }
             else
                glDisableClientState(GL_NORMAL_ARRAY);
 
             // *** Texture Coordinates Stream ***
-            if(mesh.texCoords)
+            if(mesh.texCoords || mesh.flags.texCoords1)
             {
                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-               GLBindBuffer( GL_ARRAY_BUFFER_ARB, oglMesh.texCoords);
-               glTexCoordPointer(2, GL_FLOAT, 0, vboAvailable ? null : mesh.texCoords);
+               oglMesh.texCoords.use(texCoord, 2, GL_FLOAT, 0, oglMesh.texCoords.buffer ? null : mesh.texCoords);
             }
             else
                glDisableClientState(GL_TEXTURE_COORD_ARRAY);
 
             // *** Color Stream ***
-            if(mesh.colors)
+            if(mesh.colors || mesh.flags.colors)
             {
                glEnableClientState(GL_COLOR_ARRAY);
-               GLBindBuffer( GL_ARRAY_BUFFER_ARB, oglMesh.colors);
-               glColorPointer(4, GL_FLOAT, 0, vboAvailable ? null : mesh.colors);
+               oglMesh.colors.use(color, 4, GL_FLOAT, 0, oglMesh.colors.buffer ? null : mesh.colors);
             }
             else
                glDisableClientState(GL_COLOR_ARRAY);
-
          }
          else
          {
-            GLBindBuffer( GL_ARRAY_BUFFER_ARB, 0);
-            glVertexPointer(3,mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT,0,mesh.vertices);
-            if(mesh.normals && !display.display3D.collectingHits)
+            noAB.use(vertex, 3, (mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT), 0, (double *)mesh.vertices);
+            if((mesh.normals || mesh.flags.normals) && !display.display3D.collectingHits)
             {
                glEnableClientState(GL_NORMAL_ARRAY);
-               glNormalPointer(mesh.flags.doubleNormals ? GL_DOUBLE : GL_FLOAT, 0, mesh.normals);
+               noAB.use(normal, 3, GL_FLOAT, 0, mesh.normals);
             }
             else
                glDisableClientState(GL_NORMAL_ARRAY);
-            if(mesh.texCoords && !display.display3D.collectingHits)
+            if((mesh.texCoords || mesh.flags.texCoords1) && !display.display3D.collectingHits)
             {
                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-               glTexCoordPointer(2, GL_FLOAT, 0, mesh.texCoords);
+               noAB.use(texCoord, 2, GL_FLOAT, 0, mesh.texCoords);
             }
             else
                glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-            if(mesh.colors && !display.display3D.collectingHits)
+            if((mesh.colors || mesh.flags.colors) && !display.display3D.collectingHits)
             {
                glEnableClientState(GL_COLOR_ARRAY);
-               glColorPointer(4, GL_FLOAT, 0, mesh.colors);
+               noAB.use(color, 4, GL_FLOAT, 0, mesh.colors);
             }
             else
                glDisableClientState(GL_COLOR_ARRAY);
          }
 
-#if !defined(__ANDROID__) && !defined(__APPLE__)
-         if(glLockArraysEXT) glLockArraysEXT(0, mesh.nVertices);
+#if !defined(__ANDROID__) && !defined(__APPLE__) && !defined(__ODROID__) && !defined(__EMSCRIPTEN__)
+
+#if defined(__WIN32__)
+         if(glLockArraysEXT)
+#endif
+            if(!vboAvailable)
+               glLockArraysEXT(0, mesh.nVertices);
+
 #endif
       }
-      else
-         GLBindBuffer(GL_ARRAY_BUFFER_ARB, 0);
    }
 
    void DrawPrimitives(Display display, PrimitiveSingle * primitive, Mesh mesh)
    {
-      OGLDisplay oglDisplay = display.driverData;
       //Logf("DrawPrimitives\n");
 
       if(primitive->type.vertexRange)
@@ -3795,18 +3479,18 @@ class OpenGLDisplayDriver : DisplayDriver
          //    *** Hoping the data won't be uploaded at all (Won't really work if another group of the mesh is using the mesh ) ***
          // HACK TO SPEED THINGS UP...
 #ifndef __ANDROID__
-         GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
+         /*GLABBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
          if(primitive->nIndices < (mesh.nVertices >> 2) && !primitive->type.indices32bit)
          {
             int c;
-            glBegin(primitiveTypes[primitive->type.primitiveType]);
+            glBegin((GLIMTKMode)primitiveTypes[primitive->type.primitiveType]);
             if(primitive->data)
             {
                OGLIndices oglIndices = primitive->data;
                MeshFeatures flags = mesh.flags;
                for(c = 0; c<primitive->nIndices; c++)
                {
-                  short index = ((short *) oglIndices.indices)[c];
+                  uint16 index = ((uint16 *) oglIndices.indices)[c];
                   if(flags.normals) glNormal3fv((float *)&mesh.normals[index]);
                   if(flags.texCoords1) glTexCoord2fv((float *)&mesh.texCoords[index]);
                   if(flags.colors) glColor4fv((float *)&mesh.colors[index]);
@@ -3815,21 +3499,29 @@ class OpenGLDisplayDriver : DisplayDriver
             }
             glEnd();
          }
-         else
+         else*/
 #endif
+
          {
             OGLIndices oglIndices = primitive->data;
-
-            if(!display.display3D.collectingHits && vboAvailable && oglIndices)
+            GLEAB eab = ((!display.display3D.collectingHits && oglIndices && vboAvailable) ? oglIndices.buffer : noEAB);
+#if defined(_GLES) || defined(_GLES2)
+            if(!vboAvailable && primitive->type.indices32bit)
             {
-               GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, oglIndices.buffer);
-               glDrawElements(primitiveTypes[primitive->type.primitiveType], primitive->nIndices,
-                  primitive->type.indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0);
-               GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
+               uint16 * temp = new uint16[primitive->nIndices];
+               uint32 * src = (uint32 *)(oglIndices ? oglIndices.indices : primitive->indices);
+               int i;
+               for(i = 0; i < primitive->nIndices; i++)
+                  temp[i] = (uint16)src[i];
+               eab.draw(primitiveTypes[primitive->type.primitiveType], primitive->nIndices, GL_UNSIGNED_SHORT, temp);
+               delete temp;
             }
             else
-               glDrawElements(primitiveTypes[primitive->type.primitiveType], primitive->nIndices,
-                  primitive->type.indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, oglIndices ? oglIndices.indices : primitive->indices);
+#endif
+            eab.draw(primitiveTypes[primitive->type.primitiveType], primitive->nIndices,
+               primitive->type.indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT,
+               eab.buffer ? 0 : (oglIndices ? oglIndices.indices : primitive->indices));
+            GLABBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
          }
       }
    }
@@ -3881,15 +3573,24 @@ public void UseSingleGLContext(bool useSingle)
    useSingleGLContext = useSingle;
 }
 
-default dllexport void * __attribute__((stdcall)) IS_GLGetContext(DisplaySystem displaySystem)
+default dllexport void *
+#if defined(__WIN32__)
+__attribute__((stdcall))
+#endif
+IS_GLGetContext(DisplaySystem displaySystem)
 {
-   void * context = null;
    if(displaySystem)
    {
-      OGLSystem system = displaySystem.driverData;
 #if defined(__WIN32__)
+      OGLSystem system = displaySystem.driverData;
       return system.glrc;
+#elif defined(__ANDROID__) || defined(__ODROID__)
+      return eglContext;
+#elif defined(__EMSCRIPTEN__)
+      OGLSystem system = displaySystem.driverData;
+      return (void *)system.glc;
 #else
+      OGLSystem system = displaySystem.driverData;
       return system.glContext;
 #endif
    }