ecere.epj; ecere/gfx/drivers/OpenGL: GL ES/Android fixes & tweaks
[sdk] / ecere / src / gfx / drivers / OpenGLDisplayDriver.ec
1 // We were using PBUFFER for alpha compositing on Linux before, but it does not seem to work, nor be required anymore.
2 // #define USEPBUFFER
3
4 namespace gfx::drivers;
5
6 // OpenGL Extensions
7 #if defined(__unix__) || defined(__APPLE__)
8
9 #if !defined(__MINGW32__)
10    #define GL_GLEXT_PROTOTYPES
11 #endif
12
13 #ifdef ECERE_MINIGLX
14
15 //#include <GL/miniglx.h>
16
17 #else
18
19    #if !defined(__ANDROID__)
20
21       #define property _property
22       #define new _new
23       #define class _class
24
25       #define Window    X11Window
26       #define Cursor    X11Cursor
27       #define Font      X11Font
28       #define Display   X11Display
29       #define Time      X11Time
30       #define KeyCode   X11KeyCode
31       #define Picture   X11Picture
32       #define uint _uint
33
34       #include <X11/Xlib.h>
35       #include <X11/Xutil.h>
36       #include <GL/glx.h>
37       #include <X11/extensions/XShm.h>
38       #include <sys/ipc.h>
39       #include <sys/shm.h>
40       #include <X11/extensions/Xrender.h>
41       #include <X11/extensions/shape.h>
42
43       #undef Window
44       #undef Cursor
45       #undef Font
46       #undef Display
47       #undef Time
48       #undef KeyCode
49       #undef Picture
50       #undef uint
51       #undef new
52       #undef property
53       #undef class
54
55    #endif
56
57 #endif
58
59 #endif
60
61 #if defined(__APPLE__)
62 #include <OpenGl/gl.h>
63 #endif
64
65 #if defined(__WIN32__) || defined(__unix__) || defined(__APPLE__)
66
67 #if defined(__WIN32__)
68    #define WIN32_LEAN_AND_MEAN
69    #undef _WIN32_WINNT
70    #define _WIN32_WINNT 0x0502
71    #define String Sting_
72    #include <windows.h>
73    #undef String
74 #endif
75
76 #if defined(__ANDROID__)
77
78    #include <GLES/gl.h>
79    #include <EGL/egl.h>
80
81 #else
82
83    #include <GL/gl.h>
84    #include <GL/glext.h>
85
86 #endif
87
88 import "Display"
89
90 #if defined(__unix__) || defined(__APPLE__)
91
92    #ifndef __ANDROID__
93    import "XInterface"
94    #endif
95
96 #endif
97
98 static double nearPlane = 1;
99
100 #define glLoadMatrix glLoadMatrixd
101 #define glMultMatrix glMultMatrixd
102 #define glGetMatrix  glGetDoublev
103 #define glTranslate glTranslated
104 #define glScale glScaled
105
106 /*
107 #define glVertex3v glVertex3dv
108 #define glNormal3v glNormal3dv
109 */
110
111 /*
112 //#ifdef VERTEX_FORMAT_DOUBLE
113
114 #define glLoadMatrix glLoadMatrixd
115 #define glMultMatrix glMultMatrixd
116 #define glGetMatrix  glGetDoublev
117 #define glVertex3v glVertex3dv
118 #define glNormal3v glNormal3dv
119 #define glTranslate glTranslated
120 #define glScale glScaled
121 //#define GL_VERTEX_FORMAT   GL_DOUBLE
122
123 #else
124
125 #define glLoadMatrix glLoadMatrixf
126 #define glMultMatrix glMultMatrixf
127 #define glGetMatrix  glGetFloatv
128 #define glVertex3v glVertex3fv
129 #define glNormal3v glNormal3fv
130 #define glTranslate glTranslatef
131 #define glScale glScalef
132 //#define GL_VERTEX_FORMAT   GL_FLOAT
133
134 #endif
135 */
136
137 #define GL_ARRAY_BUFFER_ARB            0x8892
138 #define GL_ELEMENT_ARRAY_BUFFER_ARB    0x8893
139 #define GL_STATIC_DRAW_ARB             0x88E4
140 #define GL_LIGHT_MODEL_COLOR_CONTROL   0x81F8
141 #define GL_SEPARATE_SPECULAR_COLOR     0x81FA
142
143 #define GL_MULTISAMPLE_ARB             0x809D
144
145 #if defined(__WIN32__)
146
147    #define WGL_SAMPLE_BUFFERS_ARB              0x2041
148    #define WGL_SAMPLES_ARB                     0x2042
149
150    #define  WGL_WGLEXT_VERSION   1
151    #define  WGL_FRONT_COLOR_BUFFER_BIT_ARB   0x00000001
152    #define  WGL_BACK_COLOR_BUFFER_BIT_ARB   0x00000002
153    #define  WGL_DEPTH_BUFFER_BIT_ARB   0x00000004
154    #define  WGL_STENCIL_BUFFER_BIT_ARB   0x00000008
155    #define  WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
156    #define  WGL_DRAW_TO_WINDOW_ARB   0x2001
157    #define  WGL_DRAW_TO_BITMAP_ARB   0x2002
158    #define  WGL_ACCELERATION_ARB   0x2003
159    #define  WGL_NEED_PALETTE_ARB   0x2004
160    #define  WGL_NEED_SYSTEM_PALETTE_ARB   0x2005
161    #define  WGL_SWAP_LAYER_BUFFERS_ARB   0x2006
162    #define  WGL_SWAP_METHOD_ARB   0x2007
163    #define  WGL_NUMBER_OVERLAYS_ARB   0x2008
164    #define  WGL_NUMBER_UNDERLAYS_ARB   0x2009
165    #define  WGL_TRANSPARENT_ARB   0x200A
166    #define  WGL_TRANSPARENT_RED_VALUE_ARB   0x2037
167    #define  WGL_TRANSPARENT_GREEN_VALUE_ARB   0x2038
168    #define  WGL_TRANSPARENT_BLUE_VALUE_ARB   0x2039
169    #define  WGL_TRANSPARENT_ALPHA_VALUE_ARB   0x203A
170    #define  WGL_TRANSPARENT_INDEX_VALUE_ARB   0x203B
171    #define  WGL_SHARE_DEPTH_ARB   0x200C
172    #define  WGL_SHARE_STENCIL_ARB   0x200D
173    #define  WGL_SHARE_ACCUM_ARB   0x200E
174    #define  WGL_SUPPORT_GDI_ARB   0x200F
175    #define  WGL_SUPPORT_OPENGL_ARB   0x2010
176    #define  WGL_DOUBLE_BUFFER_ARB   0x2011
177    #define  WGL_STEREO_ARB   0x2012
178    #define  WGL_PIXEL_TYPE_ARB   0x2013
179    #define  WGL_COLOR_BITS_ARB   0x2014
180    #define  WGL_RED_BITS_ARB   0x2015
181    #define  WGL_RED_SHIFT_ARB   0x2016
182    #define  WGL_GREEN_BITS_ARB   0x2017
183    #define  WGL_GREEN_SHIFT_ARB   0x2018
184    #define  WGL_BLUE_BITS_ARB   0x2019
185    #define  WGL_BLUE_SHIFT_ARB   0x201A
186    #define  WGL_ALPHA_BITS_ARB   0x201B
187    #define  WGL_ALPHA_SHIFT_ARB   0x201C
188    #define  WGL_ACCUM_BITS_ARB   0x201D
189    #define  WGL_ACCUM_RED_BITS_ARB   0x201E
190    #define  WGL_ACCUM_GREEN_BITS_ARB   0x201F
191    #define  WGL_ACCUM_BLUE_BITS_ARB   0x2020
192    #define  WGL_ACCUM_ALPHA_BITS_ARB   0x2021
193    #define  WGL_DEPTH_BITS_ARB   0x2022
194    #define  WGL_STENCIL_BITS_ARB   0x2023
195    #define  WGL_AUX_BUFFERS_ARB   0x2024
196    #define  WGL_NO_ACCELERATION_ARB   0x2025
197    #define  WGL_GENERIC_ACCELERATION_ARB   0x2026
198    #define  WGL_FULL_ACCELERATION_ARB   0x2027
199    #define  WGL_SWAP_EXCHANGE_ARB   0x2028
200    #define  WGL_SWAP_COPY_ARB   0x2029
201    #define  WGL_SWAP_UNDEFINED_ARB   0x202A
202    #define  WGL_TYPE_RGBA_ARB   0x202B
203    #define  WGL_TYPE_COLORINDEX_ARB   0x202C
204    #define  ERROR_INVALID_PIXEL_TYPE_ARB   0x2043
205    #define  ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB   0x2054
206    #define  WGL_DRAW_TO_PBUFFER_ARB   0x202D
207    #define  WGL_MAX_PBUFFER_PIXELS_ARB   0x202E
208    #define  WGL_MAX_PBUFFER_WIDTH_ARB   0x202F
209    #define  WGL_MAX_PBUFFER_HEIGHT_ARB   0x2030
210    #define  WGL_PBUFFER_LARGEST_ARB   0x2033
211    #define  WGL_PBUFFER_WIDTH_ARB   0x2034
212    #define  WGL_PBUFFER_HEIGHT_ARB   0x2035
213    #define  WGL_PBUFFER_LOST_ARB   0x2036
214    #define  ERROR_INVALID_PIXEL_TYPE_EXT   0x2043
215    #define  WGL_NUMBER_PIXEL_FORMATS_EXT   0x2000
216    #define  WGL_DRAW_TO_WINDOW_EXT   0x2001
217    #define  WGL_DRAW_TO_BITMAP_EXT   0x2002
218    #define  WGL_ACCELERATION_EXT   0x2003
219    #define  WGL_NEED_PALETTE_EXT   0x2004
220    #define  WGL_NEED_SYSTEM_PALETTE_EXT   0x2005
221    #define  WGL_SWAP_LAYER_BUFFERS_EXT   0x2006
222    #define  WGL_SWAP_METHOD_EXT   0x2007
223    #define  WGL_NUMBER_OVERLAYS_EXT   0x2008
224    #define  WGL_NUMBER_UNDERLAYS_EXT   0x2009
225    #define  WGL_TRANSPARENT_EXT   0x200A
226    #define  WGL_TRANSPARENT_VALUE_EXT   0x200B
227    #define  WGL_SHARE_DEPTH_EXT   0x200C
228    #define  WGL_SHARE_STENCIL_EXT   0x200D
229    #define  WGL_SHARE_ACCUM_EXT   0x200E
230    #define  WGL_SUPPORT_GDI_EXT   0x200F
231    #define  WGL_SUPPORT_OPENGL_EXT   0x2010
232    #define  WGL_DOUBLE_BUFFER_EXT   0x2011
233    #define  WGL_STEREO_EXT   0x2012
234    #define  WGL_PIXEL_TYPE_EXT   0x2013
235    #define  WGL_COLOR_BITS_EXT   0x2014
236    #define  WGL_RED_BITS_EXT   0x2015
237    #define  WGL_RED_SHIFT_EXT   0x2016
238    #define  WGL_GREEN_BITS_EXT   0x2017
239    #define  WGL_GREEN_SHIFT_EXT   0x2018
240    #define  WGL_BLUE_BITS_EXT   0x2019
241    #define  WGL_BLUE_SHIFT_EXT   0x201A
242    #define  WGL_ALPHA_BITS_EXT   0x201B
243    #define  WGL_ALPHA_SHIFT_EXT   0x201C
244    #define  WGL_ACCUM_BITS_EXT   0x201D
245    #define  WGL_ACCUM_RED_BITS_EXT   0x201E
246    #define  WGL_ACCUM_GREEN_BITS_EXT   0x201F
247    #define  WGL_ACCUM_BLUE_BITS_EXT   0x2020
248    #define  WGL_ACCUM_ALPHA_BITS_EXT   0x2021
249    #define  WGL_DEPTH_BITS_EXT   0x2022
250    #define  WGL_STENCIL_BITS_EXT   0x2023
251    #define  WGL_AUX_BUFFERS_EXT   0x2024
252    #define  WGL_NO_ACCELERATION_EXT   0x2025
253    #define  WGL_GENERIC_ACCELERATION_EXT   0x2026
254    #define  WGL_FULL_ACCELERATION_EXT   0x2027
255    #define  WGL_SWAP_EXCHANGE_EXT   0x2028
256    #define  WGL_SWAP_COPY_EXT   0x2029
257    #define  WGL_SWAP_UNDEFINED_EXT   0x202A
258    #define  WGL_TYPE_RGBA_EXT   0x202B
259    #define  WGL_TYPE_COLORINDEX_EXT   0x202C
260    #define  WGL_DRAW_TO_PBUFFER_EXT   0x202D
261    #define  WGL_MAX_PBUFFER_PIXELS_EXT   0x202E
262    #define  WGL_MAX_PBUFFER_WIDTH_EXT   0x202F
263    #define  WGL_MAX_PBUFFER_HEIGHT_EXT   0x2030
264    #define  WGL_OPTIMAL_PBUFFER_WIDTH_EXT   0x2031
265    #define  WGL_OPTIMAL_PBUFFER_HEIGHT_EXT   0x2032
266    #define  WGL_PBUFFER_LARGEST_EXT   0x2033
267    #define  WGL_PBUFFER_WIDTH_EXT   0x2034
268    #define  WGL_PBUFFER_HEIGHT_EXT   0x2035
269    #define  WGL_DEPTH_FLOAT_EXT   0x2040
270    #define  WGL_SAMPLE_BUFFERS_3DFX   0x2060
271    #define  WGL_SAMPLES_3DFX   0x2061
272    #define  WGL_SAMPLE_BUFFERS_EXT   0x2041
273    #define  WGL_SAMPLES_EXT   0x2042
274    #define  WGL_GENLOCK_SOURCE_MULTIVIEW_I3D   0x2044
275    #define  WGL_GENLOCK_SOURCE_EXTENAL_SYNC_I3D   0x2045
276    #define  WGL_GENLOCK_SOURCE_EXTENAL_FIELD_I3D   0x2046
277    #define  WGL_GENLOCK_SOURCE_EXTENAL_TTL_I3D   0x2047
278    #define  WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D   0x2048
279    #define  WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D   0x2049
280    #define  WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D   0x204A
281    #define  WGL_GENLOCK_SOURCE_EDGE_RISING_I3D   0x204B
282    #define  WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D   0x204C
283    #define  WGL_GAMMA_TABLE_SIZE_I3D   0x204E
284    #define  WGL_GAMMA_EXCLUDE_DESKTOP_I3D   0x204F
285    #define  WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D   0x2050
286    #define  WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D   0x2051
287    #define  WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D   0x2052
288    #define  WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D   0x2053
289    #define  WGL_ARB_buffer_region   1
290    #define  WGL_ARB_extensions_string   1
291    #define  WGL_ARB_pixel_format   1
292    #define  WGL_ARB_make_current_read   1
293    #define  WGL_ARB_pbuffer   1
294    #define  WGL_EXT_display_color_table   1
295    #define  WGL_EXT_extensions_string   1
296    #define  WGL_EXT_make_current_read   1
297    #define  WGL_EXT_pbuffer   1
298    #define  WGL_EXT_pixel_format   1
299    #define  WGL_EXT_swap_control   1
300    #define  WGL_WGL_EXT_depth_float   1
301    #define  WGL_WGL_3DFX_multisample   1
302    #define  WGL_WGL_EXT_multisample   1
303    #define  WGL_NV_allocate_memory   1
304
305    /*
306    typedef void (APIENTRY * PFNGLACTIVETEXTUREARBPROC) (GLenum target);
307    typedef void (APIENTRY * PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t);
308    typedef void (APIENTRY * PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum target);
309    typedef void (APIENTRY * PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count);
310    typedef void (APIENTRY * PFNGLUNLOCKARRAYSEXTPROC) (void);
311    */
312
313    /*
314    typedef int (APIENTRY * PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
315    typedef int (APIENTRY * PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
316    typedef int (APIENTRY * PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
317    typedef int (APIENTRY * PFNGLBUFFERDATAARBPROC) (GLenum target, int size, const GLvoid *data, GLenum usage);
318    */
319    typedef int (APIENTRY * PFNWGLCHOOSEPIXELFORMATARBPROC) ();
320    typedef void * (APIENTRY * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
321    typedef HDC (APIENTRY * PFNWGLGETPBUFFERDCARBPROC) (void * hPbuffer);
322    typedef int (APIENTRY * PFNWGLRELEASEPBUFFERDCARBPROC) (void * hPbuffer, HDC hDC);
323    typedef BOOL (APIENTRY * PFNWGLDESTROYPBUFFERARBPROC) (void * hPbuffer);
324    typedef BOOL (APIENTRY * PFNWGLQUERYPBUFFERARBPROC) (void * hPbuffer, int iAttribute, int *piValue);
325    typedef const char * (APIENTRY * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
326    typedef BOOL (APIENTRY * PFNWGLBINDTEXIMAGEARBPROC) (void * hPbuffer, int iBuffer);
327    typedef BOOL (APIENTRY * PFNWGLRELEASETEXIMAGEARBPROC) (void * hPbuffer, int iBuffer);
328
329    static PFNGLMAPBUFFERARBPROC glMapBufferARB = null;
330    static PFNGLUNMAPBUFFERARBPROC glUnmapBufferARB = null;
331    static PFNGLACTIVETEXTUREARBPROC glActiveTextureARB = null;
332    static PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB = null;
333    static PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTextureARB = null;
334    static PFNGLLOCKARRAYSEXTPROC glLockArraysEXT = null;
335    static PFNGLUNLOCKARRAYSEXTPROC glUnlockArraysEXT = null;
336    static PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate = null;
337
338    static PFNGLGENBUFFERSARBPROC glGenBuffersARB = null;
339    static PFNGLBINDBUFFERARBPROC glBindBufferARB = null;
340    static PFNGLBUFFERDATAARBPROC glBufferDataARB = null;
341    static PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB = null;
342    static PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = null;
343    static PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = null;
344    static PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB = null;
345    static PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB = null;
346    static PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB = null;
347    static PFNWGLDESTROYPBUFFERARBPROC wglDestroyPbufferARB = null;
348    static PFNWGLRELEASEPBUFFERDCARBPROC wglReleasePbufferDCARB = null;
349    static PFNWGLBINDTEXIMAGEARBPROC wglBindTexImageARB = null;
350    static PFNWGLRELEASETEXIMAGEARBPROC wglReleaseTexImageARB = null;
351
352    #define glBufferData glBufferDataARB
353
354    #ifdef WGL_WGLEXT_PROTOTYPES
355    extern BOOL WINAPI wglSwapIntervalEXT (int);
356    extern int WINAPI wglGetSwapIntervalEXT (void);
357    #endif /* WGL_WGLEXT_PROTOTYPES */
358    typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
359    typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
360
361    static PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL;
362
363 #endif
364
365 // Our own matrix stack
366 static Matrix matrixStack[3][32];
367 static int matrixIndex[3];
368 static int curStack = 0;
369
370 #if defined(_GLES)
371
372    // OpenGL ES Porting Kit
373
374    #define glBindFramebuffer        glBindFramebufferOES
375    #define glBindRenderbuffer       glBindRenderbufferOES
376    #define GL_FRAMEBUFFER           GL_FRAMEBUFFER_OES
377    #define GL_RENDERBUFFER          GL_RENDERBUFFER_OES
378    #define glFramebufferTexture2D   glFramebufferTexture2DOES
379    #define GL_COLOR_ATTACHMENT0     GL_COLOR_ATTACHMENT0_OES
380    #define glGenFramebuffers        glGenFramebuffersOES
381    #define glGenRenderbuffers       glGenRenderbuffersOES
382    #define glDeleteFramebuffers     glDeleteFramebuffersOES
383    #define glDeleteRenderbuffers    glDeleteRenderbuffersOES
384
385 #if defined(__ANDROID__)
386    #define GL_POLYGON_STIPPLE 0xFFFF
387    #define GL_LINE_STIPPLE 0xFFFF
388    #define GL_LINE 0xFFFF
389    #define GL_FILL 0xFFFF
390    #define GL_ALL_ATTRIB_BITS 0xFFFF
391    #define GL_LIGHT_MODEL_LOCAL_VIEWER 0xFFFF
392    #define GL_INT                                  0x1404
393    #define GL_UNSIGNED_INT                         0x1405
394    #define GL_DOUBLE                               0x140A
395    #define GL_POLYGON      9
396    #define GL_QUADS        7
397    #define APIENTRY
398 #endif
399
400    #define glDrawElementsi(type, count, start)  glDrawElements(type, count, GL_UNSIGNED_SHORT, start)
401
402    #define glBufferDatai         glesBufferDatai
403    #define glBufferDatad         glesBufferDatad
404    #define glVertexPointeri      glesVertexPointeri
405    #define glVertexPointerd      glesVertexPointerd
406
407    #define glRecti               glesRecti
408    #define glBegin               glesBegin
409    #define glTexCoord2i          glesTexCoord2i
410    #define glVertex2i            glesVertex2i
411    #define glTexCoord2d          glesTexCoord2d
412    #define glVertex2d            glesVertex2d
413    #define glTexCoord2f          glesTexCoord2f
414    #define glVertex2f            glesVertex2f
415    #define glEnd                 glesEnd
416    #define glColor3f             glesColor3f
417    #define glColor4ub            glesColor4ub
418    #define glColor4fv            glesColor4fv
419    #define glLineStipple         glesLineStipple
420    #define glNormal3fv           glesNormal3fv
421    #define glTexCoord2fv         glesTexCoord2fv
422    #define glColorMaterial       glesColorMaterial
423
424    #define glLoadMatrixd         glesLoadMatrixd
425    #define glMultMatrixd         glesMultMatrixd
426    #define glFrustum             glesFrustum
427    #define glOrtho               glesOrtho
428    #define glScaled              glesScaled
429    #define glTranslated          glesTranslated
430    #define glRotated             glesRotated
431    #define glVertex3d            glesVertex3d
432    #define glVertex3dv           glesVertex3dv
433    #define glVertex3f            glesVertex3f
434    #define glVertex3fv           glesVertex3fv
435    #define glLightModeli         glesLightModeli
436
437 #if defined(__ANDROID__)
438    //#define GL_QUADS              0
439    #define GL_QUAD_STRIP         0
440    //#define GL_DOUBLE             0
441    //#define GL_UNSIGNED_INT       0
442    //#define GL_FILL               0
443    //#define GL_LINE               0
444    //#define GL_LINE_STIPPLE       0
445    #define GL_BGRA_EXT           0
446    #define GL_UNPACK_ROW_LENGTH  0
447    #define GL_UNPACK_SKIP_PIXELS 0
448    #define GL_UNPACK_SKIP_ROWS   0
449    #define GL_RGBA8              0
450    #define GL_PACK_ROW_LENGTH    0
451    #define GL_PACK_SKIP_ROWS     0
452    #define GL_PACK_SKIP_PIXELS   0
453 #endif
454
455 #else
456
457 #define glVertexPointerd(nc, s, p, nv)       glVertexPointer(nc, GL_DOUBLE, s, p)
458 #define glDrawElementsi(type, count, start)  glDrawElements(type, count, GL_UNSIGNED_INT, start)
459
460 #endif
461
462 #if defined(__ANDROID__)
463    static EGLDisplay eglDisplay;
464    static EGLSurface eglSurface;
465    static EGLContext eglContext;
466    static int eglWidth, eglHeight;
467
468    static bool egl_init_display(ANativeWindow* window)
469    {
470       const EGLint attribs[] =
471       {
472          EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
473          EGL_BLUE_SIZE, 8,
474          EGL_GREEN_SIZE, 8,
475          EGL_RED_SIZE, 8,
476          EGL_DEPTH_SIZE, 16, //24,
477          /*EGL_SAMPLE_BUFFERS, 1,
478          EGL_SAMPLES, 0, //2,*/
479          EGL_NONE
480       };
481       EGLint w, h, format;
482       EGLint numConfigs;
483       EGLConfig config;
484       EGLSurface surface;
485       EGLContext context;
486
487       EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
488       eglInitialize(display, 0, 0);
489       eglChooseConfig(display, attribs, &config, 1, &numConfigs);
490       eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
491
492       surface = eglCreateWindowSurface(display, config, window, null);
493       context = eglCreateContext(display, config, null, null);
494
495       if(!eglMakeCurrent(display, surface, surface, context))
496          return false;
497
498       eglQuerySurface(display, surface, EGL_WIDTH, &w);
499       eglQuerySurface(display, surface, EGL_HEIGHT, &h);
500
501       eglDisplay = display;
502       eglContext = context;
503       eglSurface = surface;
504       eglWidth = w;
505       eglHeight = h;
506
507       glEnableClientState(GL_VERTEX_ARRAY);
508       /*
509       // Initialize GL state.
510       glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
511       glEnable(GL_CULL_FACE);
512       glShadeModel(GL_SMOOTH);
513       glDisable(GL_DEPTH_TEST);
514       */
515       glDisable(GL_CULL_FACE);
516       glDisable(GL_DEPTH_TEST);
517
518       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
519       glEnable(GL_BLEND);
520
521       matrixStack[0][0].Identity();
522       matrixStack[1][0].Identity();
523       matrixStack[2][0].Identity();
524
525       glesMatrixMode(GL_MODELVIEW);
526       glScaled(1.0, 1.0, -1.0);
527       glesMatrixMode(GL_PROJECTION);
528       glShadeModel(GL_FLAT);
529
530       glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
531       glFogi(GL_FOG_MODE, GL_EXP);
532       glFogf(GL_FOG_DENSITY, 0);
533       glEnable(GL_NORMALIZE);
534       glDepthFunc(GL_LESS);
535       glClearDepth(1.0);
536       glDisable(GL_MULTISAMPLE_ARB);
537
538       glViewport(0,0,w,h);
539       glesLoadIdentity();
540       glOrtho(0,w,h,0,0.0,1.0);
541
542       currentVertexBuffer = 0;
543       return true;
544    }
545
546    static void egl_term_display()
547    {
548       if(stippleTexture)
549       {
550          glDeleteTextures(1, &stippleTexture);
551          stippleTexture = 0;
552       }
553       if(eglDisplay != EGL_NO_DISPLAY)
554       {
555          eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
556          if(eglContext != EGL_NO_CONTEXT)
557             eglDestroyContext(eglDisplay, eglContext);
558          if(eglSurface != EGL_NO_SURFACE)
559             eglDestroySurface(eglDisplay, eglSurface);
560          eglTerminate(eglDisplay);
561       }
562       eglDisplay = EGL_NO_DISPLAY;
563       eglContext = EGL_NO_CONTEXT;
564       eglSurface = EGL_NO_SURFACE;
565    }
566
567 #endif
568
569 // OpenGL Immediate Mode Porting Kit
570 static int beginCount;
571 static int vertexCount;
572 static int normalCount;
573 static float *vertexPointer;
574 static float *normalPointer;
575 static GLenum beginMode;
576 static unsigned int beginBufferSize, normalBufferSize;
577 static int numVertexCoords = 2;
578
579 public void glesRecti(int a, int b, int c, int d)
580 {
581    glBegin(GL_QUADS);
582    glVertex2i(a, b);
583    glVertex2i(a, d);
584    glVertex2i(c, d);
585    glVertex2i(c, b);
586    glEnd();
587 }
588
589 public void glesBegin(GLenum mode)
590 {
591    beginMode = mode;
592    beginCount = 0;
593    vertexCount = 0;
594    if(!vertexPointer)
595    {
596       normalBufferSize = beginBufferSize = 1024;  // default number of vertices
597       vertexPointer = new float[beginBufferSize * 5];
598       normalPointer = new float[normalBufferSize * 3];
599    }
600 }
601
602 public void glesTexCoord2f(float x, float y)
603 {
604    int count = vertexCount;
605
606    if(vertexCount + numVertexCoords > beginBufferSize)
607    {
608       beginBufferSize = beginBufferSize + beginBufferSize/2;
609       vertexPointer = renew vertexPointer float[beginBufferSize * 5];
610    }
611
612    vertexPointer[count*(2+numVertexCoords)  ] = x;
613    vertexPointer[count*(2+numVertexCoords)+1] = y;
614    count++;
615
616    if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
617    {
618       vertexPointer[count*(2+numVertexCoords)  ] = vertexPointer[(count-4)*(2+numVertexCoords)];
619       vertexPointer[count*(2+numVertexCoords)+1] = vertexPointer[(count-4)*(2+numVertexCoords)+1];
620       count++;
621       vertexPointer[count*(2+numVertexCoords)  ] = vertexPointer[(count-3)*(2+numVertexCoords)];
622       vertexPointer[count*(2+numVertexCoords)+1] = vertexPointer[(count-3)*(2+numVertexCoords)+1];
623       count++;
624    }
625 }
626 public void glesTexCoord2i(int x, int y)       { glesTexCoord2f((float)x, (float)y); }
627 public void glesTexCoord2d(double x, double y) { glesTexCoord2f((float)x, (float)y); }
628 public void glesTexCoord2fv(float * a)         { glesTexCoord2f(a[0], a[1]); }
629
630 public void glesVertex2f(float x, float y)
631 {
632    numVertexCoords = 2;
633    if(vertexCount + 4 > beginBufferSize)
634    {
635       beginBufferSize = beginBufferSize + beginBufferSize/2;
636       vertexPointer = renew vertexPointer float[beginBufferSize * 5];
637    }
638
639    vertexPointer[vertexCount*4+2] = x;
640    vertexPointer[vertexCount*4+3] = y;
641    vertexCount++;
642
643    if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
644    {
645       vertexPointer[vertexCount*4+2] = vertexPointer[(vertexCount-4)*4+2];
646       vertexPointer[vertexCount*4+3] = vertexPointer[(vertexCount-4)*4+3];
647       vertexCount++;
648       vertexPointer[vertexCount*4+2] = vertexPointer[(vertexCount-3)*4+2];
649       vertexPointer[vertexCount*4+3] = vertexPointer[(vertexCount-3)*4+3];
650       vertexCount++;
651    }
652    beginCount++;
653 }
654 public void glesVertex2i(int x, int y)         { glesVertex2f((float)x, (float)y); }
655 public void glesVertex2d(double x, double y)   { glesVertex2f((float)x, (float)y); }
656
657 public void glesEnd(void)
658 {
659    int mode = beginMode;
660    if(mode == GL_QUADS)        mode = GL_TRIANGLES;
661    else if(mode == GL_POLYGON) mode = GL_TRIANGLE_FAN;
662    GLSelectVBO(0);
663    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
664    glTexCoordPointer(numVertexCoords, GL_FLOAT, (numVertexCoords+2)*sizeof(float),vertexPointer);
665    glVertexPointer  (numVertexCoords, GL_FLOAT, (numVertexCoords+2)*sizeof(float),vertexPointer+2);
666    if(normalCount && normalCount == vertexCount)
667    {
668       glEnableClientState(GL_NORMAL_ARRAY);
669       glNormalPointer  (GL_FLOAT, 3*sizeof(float),normalPointer);
670    }
671
672    glDrawArrays(mode, 0, vertexCount);
673    if(normalCount)
674       glDisableClientState(GL_NORMAL_ARRAY);
675    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
676    normalCount = 0;
677 }
678
679 // Vertex Pointer
680 static float *floatVPBuffer = null;
681 static short *shortVPBuffer = null;
682 static unsigned int shortVPSize = 0, floatVPSize = 0;
683
684 // Buffer Data
685 //static float *floatVPBuffer = null;  // For floats we reuse floatVPBuffer
686 static unsigned short *shortBDBuffer = null;
687 static unsigned int shortBDSize = 0/*, floatVPSize = 0*/;
688
689 public void glesVertexPointeri(int numCoords, int stride, int *pointer, int numVertices)
690 {
691    if(pointer)
692    {
693       int i;
694       if(numVertices*numCoords > shortVPSize)
695       {
696          shortVPSize = numVertices*numCoords;
697          shortVPBuffer = renew shortVPBuffer short[shortVPSize];
698       }
699       for(i = 0; i < numVertices*numCoords; i++)
700          shortVPBuffer[i] = (short)pointer[i];
701       glVertexPointer(numCoords, GL_SHORT, stride, shortVPBuffer);
702    }
703    else
704       glVertexPointer(numCoords, GL_SHORT, stride, 0);
705 }
706
707 public void glesVertexPointerd(int numCoords, int stride, double *pointer, int numVertices)
708 {
709    if(pointer)
710    {
711       int i;
712       if(numVertices*numCoords > floatVPSize)
713       {
714          floatVPSize = numVertices*numCoords;
715          floatVPBuffer = renew floatVPBuffer float[floatVPSize];
716       }
717       for(i = 0; i < numVertices*numCoords; i++)
718          floatVPBuffer[i] = (float)pointer[i];
719       glVertexPointer(numCoords, GL_FLOAT, stride, floatVPBuffer);
720    }
721    else
722       glVertexPointer(numCoords, GL_FLOAT, stride, 0);
723 }
724
725 public void glesTexReuseIntVP(int numCoords)
726 {
727    glTexCoordPointer(numCoords, GL_SHORT, 0, floatVPBuffer);
728 }
729
730 public void glesTexReuseDoubleVP(int numCoords)
731 {
732    glTexCoordPointer(numCoords, GL_FLOAT, 0, floatVPBuffer);
733 }
734
735 public void glesColor3f( float r, float g, float b )
736 {
737    glColor4f(r, g, b, 1.0f);
738 }
739
740 public void glesColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
741 {
742    glColor4f(r/255.0f, g/255.0f, b/255.0f, a/255.0f);
743 }
744
745 public void glesColor4fv(float * a)
746 {
747    glColor4f(a[0], a[1], a[2], a[3]);
748 }
749
750 public void glesBufferDatad(int target, int size, void * data, int usage)
751 {
752    int numElems = size/sizeof(double);
753    double * dblPtr = (double *)data;
754    int i;
755    if (numElems > floatVPSize)
756    {
757       floatVPSize = numElems;
758       floatVPBuffer = renew floatVPBuffer float[floatVPSize];
759    }
760    for (i=0; i< numElems; i++)
761       floatVPBuffer[i] = (float)dblPtr[i];
762
763    glBufferData(target, numElems*sizeof(float), floatVPBuffer, usage);
764 }
765
766 public void glesBufferDatai(int target, int size, void * data, int usage)
767 {
768    int numElems = size/sizeof(unsigned int);
769    unsigned int * pointer = (unsigned int *)data;
770    int i;
771    if (numElems > shortBDSize)
772    {
773       shortBDSize = numElems;
774       shortBDBuffer = renew shortBDBuffer uint16[shortBDSize];
775    }
776    for (i=0; i< numElems; i++)
777       shortBDBuffer[i] = (unsigned short)pointer[i];
778
779    glBufferData(target, numElems*sizeof(unsigned short), shortBDBuffer, usage);
780 }
781
782 // *** Our Custom Matrix Stack ***
783
784 static void LoadCurMatrix()
785 {
786    double * i = matrixStack[curStack][matrixIndex[curStack]].array;
787    float m[16] =
788    {
789       (float)i[0],(float)i[1],(float)i[2],(float)i[3],
790       (float)i[4],(float)i[5],(float)i[6],(float)i[7],
791       (float)i[8],(float)i[9],(float)i[10],(float)i[11],
792       (float)i[12],(float)i[13],(float)i[14],(float)i[15]
793    };
794    glLoadMatrixf(m);
795 }
796
797 public void glesLoadIdentity()
798 {
799    matrixStack[curStack][matrixIndex[curStack]].Identity();
800    LoadCurMatrix();
801 }
802
803 public void glesPushMatrix()
804 {
805    if(matrixIndex[curStack] + 1 < sizeof(matrixStack[0]) / sizeof(Matrix))
806    {
807       matrixIndex[curStack]++;
808       memcpy(matrixStack[curStack][matrixIndex[curStack]].array, matrixStack[curStack][matrixIndex[curStack]-1].array, sizeof(Matrix));
809    }
810 }
811
812 public void glesPopMatrix()
813 {
814    if(matrixIndex[curStack] > 0)
815    {
816       matrixIndex[curStack]--;
817       LoadCurMatrix();
818    }
819 }
820
821 public void glesLoadMatrixd(double * i)
822 {
823    memcpy(matrixStack[curStack][matrixIndex[curStack]].array, i, sizeof(Matrix));
824    LoadCurMatrix();
825 }
826
827 public void glesOrtho( double l, double r, double b, double t, double n, double f )
828 {
829    Matrix m
830    { {
831       (2 / (r - l)), 0, 0, 0,
832       0, (2 / (t - b)), 0, 0,
833       0, 0, (-2 / (f - n)), 0,
834       (-(r + l) / (r - l)), (-(t + b) / (t - b)), (-(f + n) / (f - n)), 1
835    } };
836    Matrix res;
837    res.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
838    matrixStack[curStack][matrixIndex[curStack]] = res;
839    LoadCurMatrix();
840 }
841
842 public void glesFrustum( double l, double r, double b, double t, double n, double f )
843 {
844    nearPlane = n;
845    n = 1;
846    l /= nearPlane;
847    r /= nearPlane;
848    b /= nearPlane;
849    t /= nearPlane;
850    f /= nearPlane;
851    {
852       double A = ((r + l) / (r - l));
853       double B = ((t + b) / (t - b));
854       double C = (-(f + n) / (f - n));
855       double D = (-2*f*n/(f-n));
856       Matrix m
857       { {
858          (2.0*n / (r - l)), 0, 0, 0,
859          0, (2.0*n / (t - b)), 0, 0,
860          A, B,             C,-1,
861          0, 0,             D, 0
862       } };
863       Matrix res;
864       res.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
865       matrixStack[curStack][matrixIndex[curStack]] = res;
866       LoadCurMatrix();
867    }
868 }
869
870 public void glesRotated( double a, double b, double c, double d )
871 {
872    Quaternion q;
873    Matrix m, r;
874
875    q.RotationAxis({(float)b,(float)c,(float)-d}, a );
876    m.RotationQuaternion(q);
877    r.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
878    matrixStack[curStack][matrixIndex[curStack]] = r;
879    LoadCurMatrix();
880 }
881 public void glesScaled( double a, double b, double c )
882 {
883    Matrix m, r;
884
885    m.Identity();
886    m.Scale(a,b,c);
887    r.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
888    matrixStack[curStack][matrixIndex[curStack]] = r;
889    LoadCurMatrix();
890 }
891
892 public void glesTranslated( double a, double b, double c )
893 {
894    Matrix m, r;
895
896    m.Identity();
897    m.Translate(a,b,c);
898    r.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
899    matrixStack[curStack][matrixIndex[curStack]] = r;
900    LoadCurMatrix();
901 }
902
903 public void glesMultMatrixd( double * i )
904 {
905    Matrix r;
906    r.Multiply((Matrix *)i, matrixStack[curStack][matrixIndex[curStack]]);
907    matrixStack[curStack][matrixIndex[curStack]] = r;
908    LoadCurMatrix();
909 }
910
911 public void glesMatrixMode(int mode)
912 {
913    curStack = (mode == GL_MODELVIEW) ? 0 : (mode == GL_PROJECTION) ? 1 : 2;
914    glMatrixMode(mode);
915 }
916
917 #if defined(_GLES)
918
919 #define glPushMatrix          glesPushMatrix
920 #define glPopMatrix           glesPopMatrix
921 #define glLoadIdentity        glesLoadIdentity
922 #define glMatrixMode          glesMatrixMode
923
924 #endif
925
926 /* Using the built-in matrix stack
927 void glesLoadMatrixd( double * i )
928 {
929    float m[16] =
930    {
931       (float)i[0],(float)i[1],(float)i[2],(float)i[3],
932       (float)i[4],(float)i[5],(float)i[6],(float)i[7],
933       (float)i[8],(float)i[9],(float)i[10],(float)i[11],
934       (float)i[12],(float)i[13],(float)i[14],(float)i[15]
935    };
936    glLoadMatrixf(m);
937 }
938
939 void glesOrtho( double l, double r, double b, double t, double n, double f )
940 {
941    float matrix[4][4] =
942    {
943       { (float)(2 / (r - l)), 0, 0, 0 },
944       { 0, (float)(2 / (t - b)), 0, 0 },
945       { 0, 0, (float)(-2 / (f - n)), 0 },
946       { (float)(-(r + l) / (r - l)), (float)(-(t + b) / (t - b)), (float)(-(f + n) / (f - n)), 1 }
947    };
948    glMultMatrixf((float *)matrix);
949 }
950
951 void glesFrustum( double l, double r, double b, double t, double n, double f )
952 {
953    float A = (float)((r + l) / (r - l));
954    float B = (float)((t + b) / (t - b));
955    float C = (float)(-(f + n) / (f - n));
956    float D = (float)(-2*f*n/(f-n));
957    float matrix[4][4] =
958    {
959       { (float)(2*n / (r - l)), 0, 0, 0 },
960       { 0, (float)(2*n / (t - b)), 0, 0 },
961       { A, B,             C,-1 },
962       { 0, 0,             D, 0 }
963    };
964    glMultMatrixf((float *)matrix);
965 }
966
967 void glesRotated( double a, double b, double c, double d ) { glRotatef((float)a, (float)b, (float)c, (float)d); }
968 void glesScaled( double a, double b, double c ) { glScalef((float)a, (float)b, (float)c); }
969 void glesTranslated( double a, double b, double c ) { glTranslatef((float)a, (float)b, (float)c); }
970
971 void glesMultMatrixd( double * i )
972 {
973    float m[16] =
974    {
975       (float)i[0], (float)i[1], (float)i[2], (float)i[3],
976       (float)i[4], (float)i[5], (float)i[6], (float)i[7],
977       (float)i[8], (float)i[9], (float)i[10], (float)i[11],
978       (float)i[12], (float)i[13], (float)i[14], (float)i[15]
979    };
980    glMultMatrixf(m);
981 }
982 */
983
984 // Need to do these...
985 public void glesVertex3f( float x, float y, float z )
986 {
987    numVertexCoords = 3;
988    if(vertexCount + 4 > beginBufferSize)
989    {
990       beginBufferSize = beginBufferSize + beginBufferSize/2;
991       vertexPointer = renew vertexPointer float[beginBufferSize * 5];
992    }
993
994    vertexPointer[vertexCount*5+2] = x;
995    vertexPointer[vertexCount*5+3] = y;
996    vertexPointer[vertexCount*5+4] = z;
997    vertexCount++;
998
999    if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
1000    {
1001       vertexPointer[vertexCount*5+2] = vertexPointer[(vertexCount-4)*5+2];
1002       vertexPointer[vertexCount*5+3] = vertexPointer[(vertexCount-4)*5+3];
1003       vertexPointer[vertexCount*5+4] = vertexPointer[(vertexCount-4)*5+4];
1004       vertexCount++;
1005       vertexPointer[vertexCount*5+2] = vertexPointer[(vertexCount-3)*5+2];
1006       vertexPointer[vertexCount*5+3] = vertexPointer[(vertexCount-3)*5+3];
1007       vertexPointer[vertexCount*5+4] = vertexPointer[(vertexCount-3)*5+4];
1008       vertexCount++;
1009    }
1010    beginCount++;
1011 }
1012
1013 public void glesVertex3d( double x, double y, double z )  { glesVertex3f((float)x, (float)y, (float)z); }
1014 public void glesVertex3fv( float* coords )                { glesVertex3f(coords[0], coords[1], coords[2]); }
1015 public void glesVertex3dv( double* coords )               { glesVertex3f((float)coords[0], (float)coords[1], (float)coords[2]); }
1016
1017 public void glesNormal3f(float x, float y, float z)
1018 {
1019    normalCount = vertexCount;
1020    if(vertexCount + 4 > normalBufferSize)
1021    {
1022       normalBufferSize = normalBufferSize + normalBufferSize/2;
1023       normalPointer = renew normalPointer float[normalBufferSize * 2];
1024    }
1025
1026    normalPointer[normalCount*3+0] = x;
1027    normalPointer[normalCount*3+1] = y;
1028    normalPointer[normalCount*3+2] = z;
1029    normalCount++;
1030
1031    if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
1032    {
1033       normalPointer[normalCount*3+0] = normalPointer[(normalCount-4)*3+0];
1034       normalPointer[normalCount*3+1] = normalPointer[(normalCount-4)*3+1];
1035       normalPointer[normalCount*3+2] = normalPointer[(normalCount-4)*3+2];
1036       normalCount++;
1037       normalPointer[normalCount*3+0] = normalPointer[(normalCount-3)*3+0];
1038       normalPointer[normalCount*3+1] = normalPointer[(normalCount-3)*3+1];
1039       normalPointer[normalCount*3+2] = normalPointer[(normalCount-3)*3+2];
1040       normalCount++;
1041    }
1042 }
1043 public void glesNormal3fd(double x, double y, double z)         { glesNormal3f((float)x, (float)y, (float)z); }
1044 public void glesNormal3fv(float * coords)                       { glesNormal3f(coords[0], coords[1], coords[2]); }
1045
1046 public void glesColorMaterial(int a, int b)
1047 {
1048    PrintLn("glColorMaterial stub");
1049 }
1050
1051 public void glesTerminate()
1052 {
1053    delete vertexPointer;
1054    delete normalPointer;
1055    beginBufferSize = 0;
1056
1057    delete floatVPBuffer;
1058    shortVPSize = 0;
1059
1060    delete shortVPBuffer;
1061    floatVPSize = 0;
1062
1063    delete shortBDBuffer;
1064    shortBDSize = 0;
1065 }
1066
1067 static GLuint stippleTexture;
1068 #if defined(_GLES)
1069 static bool stippleEnabled;
1070 #endif
1071
1072 public void glesLineStipple( int i, unsigned short j )
1073 {
1074    uint texture[1*16];
1075    int x;
1076    for(x = 0; x < 16; x++)
1077    {
1078       bool v = (j & (1 << x)) != 0;
1079       texture[x] = v ? 0xFFFFFFFF : 0;
1080    }
1081    if(!stippleTexture)
1082       glGenTextures(1, &stippleTexture);
1083    glBindTexture(GL_TEXTURE_2D, stippleTexture);
1084    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 16, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture);
1085    glEnable(GL_TEXTURE_2D);
1086    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1087    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1088    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
1089    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1090    glMatrixMode(GL_TEXTURE);
1091    glLoadIdentity();
1092    //glTranslated(1.0/backAttrib->texW/2.0f, 1.0/backAttrib->texH/2.0f, 0.0f);
1093    glScaled(i/16.0, 1, 1.0f);
1094    glTranslated(0.5, 0.5, 0);
1095    glMatrixMode(GL_PROJECTION);
1096 }
1097
1098 public void glesLightModeli( unsigned int pname, int param )
1099 {
1100    if(pname == GL_LIGHT_MODEL_TWO_SIDE)
1101       glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, param);
1102 }
1103
1104 #ifdef __ANDROID__
1105 void glClearDepth( double depth ) { glClearDepthf((float)depth); }
1106 void glFogi( unsigned int pname, int param ) { }
1107 void glPolygonMode( unsigned int i, unsigned int j ) { }
1108
1109
1110 // *** Picking won't be supported for now ***
1111 void glPushName( unsigned int i ) { }
1112 void glLoadName( unsigned int i ) { }
1113 void glPopName() { }
1114
1115 // Probably replace by regular glBlendFunc ...
1116 void glBlendFuncSeparate(int a, int b, int c, int d)
1117 {
1118    glBlendFunc(a, b);
1119 }
1120
1121 // For direct pixel blitting...
1122 void glRasterPos2d(double a, double b) { }
1123 void glPixelZoom(float a, float b) { }
1124 void glDrawPixels(int a, int b, int c, int d, void * e) { }
1125
1126 #endif
1127
1128 #if !defined(__APPLE__) && !defined(__WIN32__)
1129 void (APIENTRY * glBindBufferARB) (GLenum target, GLuint buffer);
1130 void (APIENTRY * glGenBuffersARB) (GLsizei n, GLuint *buffers);
1131 void (APIENTRY * glDeleteBuffersARB) (GLsizei n, const GLuint *buffers);
1132 void (APIENTRY * glBufferDataARB) (GLenum target, int size, const GLvoid *data, GLenum usage);
1133 #endif
1134
1135 static int currentVertexBuffer;
1136
1137 bool GLSelectVBO(uint vbo)
1138 {
1139    if(currentVertexBuffer != vbo)
1140    {
1141       GLBindBuffer(GL_ARRAY_BUFFER, vbo);
1142       currentVertexBuffer = vbo;
1143       return true;
1144    }
1145    return false;
1146 }
1147
1148 void GLGenBuffers(int count, uint * buffer)
1149 {
1150 #ifdef __ANDROID__
1151    glGenBuffers(count, buffer);
1152 #else
1153 #if defined(__WIN32__)
1154    if(glGenBuffersARB)
1155 #endif
1156       glGenBuffersARB(count, buffer);
1157 #endif
1158 }
1159
1160 void GLDeleteBuffers(int count, GLuint * buffer)
1161 {
1162 #ifdef __ANDROID__
1163    glDeleteBuffers(count, buffer);
1164 #else
1165 #if defined(__WIN32__)
1166    if(glDeleteBuffersARB)
1167 #endif
1168       glDeleteBuffersARB(count, buffer);
1169 #endif
1170 }
1171
1172 void GLBindBuffer(int target, uint buffer)
1173 {
1174 #ifdef __ANDROID__
1175    glBindBuffer(target, buffer);
1176 #else
1177 #if defined(__WIN32__)
1178    if(glBindBufferARB)
1179 #endif
1180       glBindBufferARB(target, buffer);
1181 #endif
1182 }
1183
1184 public void GLVertexPointer(int numCoords, int glType, int stride, void *ptr, int numVertices)
1185 {
1186 #ifdef _GLES
1187    if(glType == GL_DOUBLE)
1188       glesVertexPointerd(numCoords, stride, ptr, numVertices);
1189    else if(glType == GL_INT)
1190       glesVertexPointeri(numCoords, stride, ptr, numVertices);
1191    else
1192 #endif
1193       glVertexPointer(numCoords, glType, stride, ptr);
1194 }
1195
1196 public void GLBufferData(int type, GLenum target, int size, const GLvoid *data, GLenum usage)
1197 {
1198 #ifdef _GLES
1199    if(type == GL_DOUBLE)
1200       glesBufferDatad(target, size, (void *)data, usage);
1201    else if(type == GL_UNSIGNED_INT)
1202       glesBufferDatai(target, size, (void *)data, usage);
1203    else
1204 #endif
1205
1206 #ifdef __ANDROID__
1207       glBufferData(target, size, data, usage);
1208 #else
1209
1210 #if defined(__WIN32__)
1211    if(glBufferDataARB)
1212 #endif
1213       glBufferDataARB(target, size, data, usage);
1214 #endif
1215 }
1216
1217 #if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
1218 static int primitiveTypes[RenderPrimitiveType] =
1219 {
1220    GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUADS, GL_QUAD_STRIP, GL_LINE_STRIP
1221 };
1222 #endif
1223
1224
1225 // Non OpenGL ES friendly stuff
1226
1227 #if defined(_GLES)
1228
1229 //#undef GL_UNSIGNED_INT
1230 //#undef GL_DOUBLE
1231 #undef GL_INT
1232 //#undef GL_POLYGON
1233 //#undef GL_QUADS
1234 #undef GL_QUAD_STRIP
1235 #undef GL_POLYGON_STIPPLE
1236 #undef GL_LINE_STIPPLE
1237 #undef GL_LINE
1238 #undef GL_FILL
1239 #undef GL_ALL_ATTRIB_BITS
1240 #undef GL_LIGHT_MODEL_LOCAL_VIEWER
1241
1242 #endif
1243
1244 static int displayWidth, displayHeight;
1245
1246 #define GL_CLAMP_TO_EDGE 0x812F
1247
1248 static bool vboAvailable;
1249
1250 static bool useSingleGLContext = false;
1251 class OGLDisplay : struct
1252 {
1253 #if defined(__WIN32__)
1254    HDC hdc;
1255    HGLRC glrc;
1256
1257    HBITMAP memBitmap;
1258    HDC memDC;
1259    byte * picture;
1260    uint stride;
1261    void * pBuffer;
1262    /*
1263    int imageBuffers[2];
1264    byte * pboMemory1, * pboMemory2;
1265    */
1266 #elif !defined(__ANDROID__)
1267    GLXContext glContext;
1268
1269    Pixmap pixmap;
1270    XShmSegmentInfo shminfo;
1271    XImage * image;
1272    XShmSegmentInfo shminfoShape;
1273    XImage * shapeImage;
1274    byte * picture;
1275    uint stride;
1276    GLXPbuffer pBuffer;
1277    X11Picture windowPicture;
1278    X11Picture pixmapPicture;
1279    Pixmap shapePixmap;
1280    X11Picture shapePicture;
1281 #endif
1282
1283    ColorAlpha * flippingBuffer;
1284    int flipBufH, flipBufW;
1285    bool depthWrite;
1286    int x, y;
1287 };
1288
1289 class OGLSystem : struct
1290 {
1291    int maxTextureSize;
1292    bool loadingFont;
1293    bool pow2textures;
1294 #if defined(__WIN32__)
1295    PIXELFORMATDESCRIPTOR pfd;
1296    int format;
1297    HDC hdc;
1298    HGLRC glrc;
1299    HWND hwnd;
1300 #elif !defined(__ANDROID__)
1301    XVisualInfo * visualInfo;
1302    GLXContext glContext;
1303    GLXDrawable glxDrawable;
1304 #endif
1305 };
1306
1307 class OGLSurface : struct
1308 {
1309    Font font;
1310    bool opaqueText;
1311    int xOffset;
1312    bool writingText;
1313
1314    float foreground[4], background[4], bitmapMult[4];
1315 } OGLSurface;
1316
1317 class OGLMesh : struct
1318 {
1319    uint vertices;
1320    uint normals;
1321    uint texCoords;
1322    uint texCoords2;
1323    uint colors;
1324 };
1325
1326 class OGLIndices : struct
1327 {
1328    uint16 * indices;
1329    uint buffer;
1330    uint nIndices;
1331 };
1332
1333 int current;
1334 void * previous;
1335
1336 class OpenGLDisplayDriver : DisplayDriver
1337 {
1338    class_property(name) = "OpenGL";
1339
1340    bool LockSystem(DisplaySystem displaySystem)
1341    {
1342 #if !defined(__ANDROID__)
1343       OGLSystem oglSystem = displaySystem.driverData;
1344       if(useSingleGLContext) return true;
1345    #if defined(__WIN32__)
1346       wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1347    #elif defined(__unix__) || defined(__APPLE__)
1348       //if(previous) return true;
1349       // printf("Making SYSTEM current\n");
1350       glXMakeCurrent(xGlobalDisplay, (GLXDrawable)oglSystem.glxDrawable, oglSystem.glContext);
1351       //previous = oglSystem.glContext;
1352    #endif
1353 #endif
1354       return true;
1355    }
1356
1357    void UnlockSystem(DisplaySystem displaySystem)
1358    {
1359       if(useSingleGLContext) return;
1360    #if defined(__WIN32__)
1361       wglMakeCurrent(null, null);
1362    #elif defined(__unix__) || defined(__APPLE__)
1363       // printf("Making NULL current\n");
1364       #if defined(__ANDROID__)
1365       #else
1366       glXMakeCurrent(xGlobalDisplay, None, null);
1367       #endif
1368       // previous = null;
1369    #endif
1370    }
1371
1372    bool Lock(Display display)
1373    {
1374 #if !defined(__ANDROID__)
1375       OGLDisplay oglDisplay = display.driverData;
1376       if(useSingleGLContext) return true;
1377    #if defined(__WIN32__)
1378       wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1379    #elif defined(__unix__) || defined(__APPLE__)
1380       // if(previous) glXMakeCurrent(xGlobalDisplay, None, null);
1381       // printf("   Making DISPLAY current\n");
1382       glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
1383    #endif
1384 #endif
1385       return true;
1386    }
1387
1388    void Unlock(Display display)
1389    {
1390       if(useSingleGLContext) return;
1391       //printf("   Making NULL current\n");
1392       //glXMakeCurrent(xGlobalDisplay, None, null);
1393       // if(previous)
1394          LockSystem(display.displaySystem);
1395    }
1396
1397    void DestroyDisplay(Display display)
1398    {
1399       OGLDisplay oglDisplay = display.driverData;
1400
1401       if(oglDisplay)
1402       {
1403    #if defined(__WIN32__)
1404          wglMakeCurrent( null, null );
1405
1406          if(oglDisplay.glrc)
1407             wglDeleteContext(oglDisplay.glrc);
1408
1409          if(oglDisplay.hdc && oglDisplay.pBuffer)
1410             wglReleasePbufferDCARB(oglDisplay.pBuffer, oglDisplay.hdc);
1411
1412          if(oglDisplay.pBuffer)
1413             wglDestroyPbufferARB(oglDisplay.pBuffer);
1414
1415          if(oglDisplay.hdc)
1416             ReleaseDC(display.window, oglDisplay.hdc);
1417
1418          if(oglDisplay.memDC) DeleteDC(oglDisplay.memDC);
1419          if(oglDisplay.memBitmap) DeleteObject(oglDisplay.memBitmap);
1420
1421    #elif defined(__unix__) || defined(__APPLE__)
1422       #if defined(__ANDROID__)
1423       #else
1424          if(oglDisplay.shapePixmap)
1425             XFreePixmap(xGlobalDisplay, oglDisplay.shapePixmap);
1426          if(oglDisplay.pixmap)
1427             XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
1428          if(oglDisplay.image)
1429          {
1430             if(oglDisplay.shminfoShape.shmid != -1)
1431             {
1432                XShmDetach(xGlobalDisplay, &oglDisplay.shminfo);
1433                if(oglDisplay.shminfo.shmaddr != (void *)-1)
1434                   shmdt(oglDisplay.shminfo.shmaddr);
1435                shmctl(oglDisplay.shminfo.shmid, IPC_RMID, 0);
1436             }
1437          }
1438          if(oglDisplay.shapeImage)
1439          {
1440             if(oglDisplay.shminfoShape.shmid != -1)
1441             {
1442                XShmDetach(xGlobalDisplay, &oglDisplay.shminfoShape);
1443                if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
1444                   shmdt(oglDisplay.shminfoShape.shmaddr);
1445                shmctl(oglDisplay.shminfoShape.shmid, IPC_RMID, 0);
1446             }
1447             XDestroyImage(oglDisplay.shapeImage);
1448             oglDisplay.shapeImage = None;
1449          }
1450
1451          glXMakeCurrent(xGlobalDisplay, None, null);
1452
1453          if(oglDisplay.glContext)
1454             glXDestroyContext(xGlobalDisplay, oglDisplay.glContext);
1455       #endif
1456    #endif
1457          delete oglDisplay.flippingBuffer;
1458          delete oglDisplay;
1459          display.driverData = null;
1460       }
1461    }
1462
1463    void ::CheckExtensions(OGLSystem oglSystem)
1464    {
1465       const char * extensions = (const char *)glGetString(GL_EXTENSIONS);
1466       if(extensions)
1467          oglSystem.pow2textures = strstr(extensions, "GL_ARB_texture_non_power_of_two") ? false : true;
1468       glGetIntegerv(GL_MAX_TEXTURE_SIZE, &oglSystem.maxTextureSize);
1469    }
1470
1471    bool CreateDisplaySystem(DisplaySystem displaySystem)
1472    {
1473       bool result = false;
1474       OGLSystem oglSystem = displaySystem.driverData = OGLSystem { };
1475
1476    #ifdef __WIN32__
1477       oglSystem.hwnd = CreateWindow("static", null, 0,0,0,0,0,null,null,null,null);
1478
1479       oglSystem.hdc = GetDC(oglSystem.hwnd);
1480       if(oglSystem.hdc)
1481       {
1482
1483          oglSystem.pfd.nSize = (short)sizeof(oglSystem.pfd);
1484          oglSystem.pfd.nVersion = 1;
1485          oglSystem.pfd.dwFlags = PFD_DRAW_TO_WINDOW /*PFD_DRAW_TO_BITMAP*/ | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
1486          oglSystem.pfd.iPixelType = PFD_TYPE_RGBA;
1487          oglSystem.pfd.cColorBits = 24;
1488          oglSystem.pfd.cAlphaBits = 8;
1489          oglSystem.pfd.cDepthBits = 24;
1490          oglSystem.pfd.iLayerType = PFD_MAIN_PLANE;
1491
1492          oglSystem.format = ChoosePixelFormat(oglSystem.hdc, &oglSystem.pfd);
1493          DescribePixelFormat(oglSystem.hdc, oglSystem.format, sizeof(oglSystem.pfd), &oglSystem.pfd);
1494
1495          if(oglSystem.pfd.cColorBits > 8)
1496          {
1497             SetPixelFormat(oglSystem.hdc, oglSystem.format, &oglSystem.pfd);
1498             oglSystem.glrc = wglCreateContext(oglSystem.hdc);
1499             if(oglSystem.glrc)
1500             {
1501                wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1502
1503                  // Get Pointers To The GL Functions
1504                glActiveTextureARB = (void *) wglGetProcAddress("glActiveTextureARB");
1505                glMultiTexCoord2fARB = (void *) wglGetProcAddress("glMultiTexCoord2fARB");
1506                glClientActiveTextureARB = (void *) wglGetProcAddress("glClientActiveTextureARB");
1507                glLockArraysEXT = (void *) wglGetProcAddress("glLockArraysEXT" );
1508                glUnlockArraysEXT = (void *) wglGetProcAddress("glUnlockArraysEXT");
1509                  glGenBuffersARB = (void *) wglGetProcAddress("glGenBuffersARB");
1510                  glBindBufferARB = (void *) wglGetProcAddress("glBindBufferARB");
1511                  glBufferDataARB = (void *) wglGetProcAddress("glBufferDataARB");
1512                glMapBufferARB  = (void *) wglGetProcAddress("glMapBufferARB");
1513                glUnmapBufferARB  = (void *) wglGetProcAddress("glUnmapBufferARB");
1514                  glDeleteBuffersARB = (void *) wglGetProcAddress("glDeleteBuffersARB");
1515                glBlendFuncSeparate = (void *) wglGetProcAddress("glBlendFuncSeparate");
1516
1517                wglChoosePixelFormatARB = (void *) wglGetProcAddress("wglChoosePixelFormatARB");
1518                wglGetExtensionsStringARB = (void *)wglGetProcAddress("wglGetExtensionsStringARB");
1519                wglCreatePbufferARB = (void *)wglGetProcAddress("wglCreatePbufferARB");
1520                wglGetPbufferDCARB = (void *)wglGetProcAddress("wglGetPbufferDCARB");
1521                wglQueryPbufferARB = (void *)wglGetProcAddress("wglQueryPbufferARB");
1522                wglDestroyPbufferARB = (void *)wglGetProcAddress("wglDestroyPbufferARB");
1523                wglReleasePbufferDCARB = (void *)wglGetProcAddress("wglReleasePbufferDCARB");
1524                wglBindTexImageARB = (void *)wglGetProcAddress("wglBindTexImageARB");
1525                wglReleaseTexImageARB = (void *)wglGetProcAddress("wglReleaseTexImageARB");
1526
1527                wglSwapIntervalEXT = (void *)wglGetProcAddress("wglSwapIntervalEXT");
1528
1529                vboAvailable = glBindBufferARB != null;
1530
1531                // eSystem_LoggingMode(LOG_MSGBOX, null);
1532
1533                if(wglChoosePixelFormatARB)
1534                {
1535                     int pixelFormat;
1536                     int valid;
1537                     int numFormats;
1538                     float fAttributes[] = {0,0};
1539                     int iAttributes[] =
1540                   {
1541                      WGL_DRAW_TO_WINDOW_ARB,GL_TRUE,
1542                             WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
1543                             WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
1544                             WGL_COLOR_BITS_ARB,24,
1545                             WGL_ALPHA_BITS_ARB,8,
1546                             WGL_DEPTH_BITS_ARB,16,
1547                             WGL_STENCIL_BITS_ARB,0,
1548                             WGL_DOUBLE_BUFFER_ARB,GL_TRUE,
1549                             WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
1550                             WGL_SAMPLES_ARB, 4,                                         // Check For 4x Multisampling
1551                             0,0
1552                   };
1553
1554                   //Log("Found wglChoosePixelFormatARB\n");
1555
1556                     valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1557                     if(!valid || !numFormats)
1558                     {
1559                      //Log("Can't find 4x multi sampling\n");
1560                        iAttributes[19] = 2;
1561                        valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1562                      if(!valid || !numFormats)
1563                      {
1564                         // Log("Can't find 2x multi sampling\n");
1565                         iAttributes[16] = 0;
1566                         iAttributes[17] = 0;
1567                         valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1568                      }
1569                     }
1570                   if(valid && numFormats)
1571                   {
1572                      oglSystem.format = pixelFormat;
1573                      wglMakeCurrent(null, null);
1574                      wglDeleteContext(oglSystem.glrc);
1575
1576                      // *** DescribePixelFormat does not support WGL pixel formats! ***
1577                      //DescribePixelFormat(oglSystem.hdc, oglSystem.format, sizeof(oglSystem.pfd), &oglSystem.pfd);
1578                      SetPixelFormat(oglSystem.hdc, oglSystem.format, &oglSystem.pfd);
1579                      //Log("Successfully set pixel format\n");
1580
1581                      oglSystem.glrc = wglCreateContext(oglSystem.hdc);
1582                      wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1583                   }
1584                }
1585                /*else
1586                   eSystem_Logf("Can't find wglChoosePixelFormatARB\n");*/
1587
1588                result = true;
1589
1590                CheckExtensions(oglSystem);
1591
1592                wglMakeCurrent(null, null);
1593
1594                //eSystem_DumpErrors(true);
1595             }
1596          }
1597       }
1598    #elif defined(__unix__) || defined(__APPLE__)
1599       vboAvailable = true;
1600       #if defined(__ANDROID__)
1601          egl_init_display(guiApp.desktop.windowHandle);
1602          CheckExtensions(oglSystem);
1603          result = true;
1604       #else
1605       {
1606          X11Window root = RootWindow( xGlobalDisplay, DefaultScreen( xGlobalDisplay ) );
1607          XSetWindowAttributes attr;
1608          unsigned long mask;
1609
1610          int attrList[] =
1611          {
1612       #ifndef ECERE_MINIGLX
1613             GLX_USE_GL, GLX_DEPTH_SIZE, 1,
1614       #endif
1615             GLX_RGBA,
1616             GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
1617             GLX_DOUBLEBUFFER,
1618             None
1619          };
1620          oglSystem.visualInfo = glXChooseVisual( xGlobalDisplay,  DefaultScreen( xGlobalDisplay ), attrList );
1621          attr.background_pixel = 0;
1622          attr.border_pixel = 0;
1623          attr.colormap = XCreateColormap( xGlobalDisplay, root, oglSystem.visualInfo->visual, AllocNone);
1624          attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
1625          mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
1626
1627          oglSystem.glxDrawable = XCreateWindow( xGlobalDisplay, root, 0, 0, 1, 1, 0, oglSystem.visualInfo->depth, InputOutput,
1628             oglSystem.visualInfo->visual, mask, &attr );
1629       }
1630       if(oglSystem.visualInfo)
1631       {
1632          oglSystem.glContext = glXCreateContext(xGlobalDisplay, oglSystem.visualInfo, null, True);
1633          if(oglSystem.glContext)
1634          {
1635             glXMakeCurrent(xGlobalDisplay, oglSystem.glxDrawable, oglSystem.glContext);
1636             // Setup Extensions
1637             CheckExtensions(oglSystem);
1638             glXMakeCurrent(xGlobalDisplay, None, null);
1639             result = true;
1640          }
1641       }
1642       #endif
1643    #endif
1644
1645       displaySystem.flags.alpha = true;
1646       displaySystem.flags.flipping = true;
1647       displaySystem.pixelFormat = pixelFormat888;
1648       return result;
1649    }
1650
1651    void DestroyDisplaySystem(DisplaySystem displaySystem)
1652    {
1653       OGLSystem oglSystem = displaySystem.driverData;
1654
1655    #if defined(__WIN32__)
1656       wglMakeCurrent( null, null );
1657
1658       if(oglSystem.glrc)
1659          wglDeleteContext(oglSystem.glrc);
1660
1661       if(oglSystem.hdc)
1662          ReleaseDC(oglSystem.hwnd, oglSystem.hdc);
1663       DestroyWindow(oglSystem.hwnd);
1664
1665    #elif defined(__unix__) || defined(__APPLE__)
1666       #if defined(__ANDROID__)
1667          egl_term_display();
1668       #else
1669       if(oglSystem.visualInfo)
1670       {
1671    #ifdef   ECERE_MINIGLX
1672          __miniglx_XFree(oglSystem.visualInfo);
1673    #else
1674          XFree(oglSystem.visualInfo);
1675    #endif
1676       }
1677
1678       if(oglSystem.glxDrawable)
1679       {
1680          XDestroyWindow(xGlobalDisplay, oglSystem.glxDrawable);
1681          oglSystem.glxDrawable = 0;
1682       }
1683       #endif
1684    #endif
1685       delete oglSystem;
1686    }
1687
1688    bool CreateDisplay(Display display)
1689    {
1690       bool result = false;
1691       OGLDisplay oglDisplay = display.driverData;
1692 #if !defined(__ANDROID__)
1693       OGLSystem oglSystem = display.displaySystem.driverData;
1694 #endif
1695       if(!oglDisplay)
1696          oglDisplay = display.driverData = OGLDisplay { };
1697       //printf("Inside CreateDisplay\n");
1698
1699 #if defined(__WIN32__) || defined(USEPBUFFER)
1700       if(!display.alphaBlend)
1701 #endif
1702       {
1703    #if defined(__WIN32__)
1704          oglDisplay.hdc = GetDC(display.window);
1705          SetPixelFormat(oglDisplay.hdc, oglSystem.format, &oglSystem.pfd);
1706          if((oglDisplay.glrc = wglCreateContext(oglDisplay.hdc)))
1707          {
1708             wglShareLists(oglSystem.glrc, oglDisplay.glrc);
1709             wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1710             result = true;
1711          }
1712          else
1713             ReleaseDC(display.window, oglDisplay.hdc);
1714    #elif defined(__unix__) || defined(__APPLE__)
1715       #if defined(__ANDROID__)
1716       #else
1717          XVisualInfo * visualInfo = ((XWindowData)display.windowDriverData).visual;
1718          /*
1719 #if defined(__APPLE__)
1720          XVisualInfo template = { 0 };
1721          XWindowAttributes winAttr;
1722          int n;
1723          XGetWindowAttributes(xGlobalDisplay, (X11Window)display.window, &winAttr);
1724          template.visualid = XVisualIDFromVisual(winAttr.visual);
1725          visualInfo = XGetVisualInfo(xGlobalDisplay, VisualIDMask, &template, &n);
1726 #ifdef _DEBUG
1727          printf("XGetVisualInfo visual ID = %d\n", template.visualid);
1728          printf("visualInfo visual ID = %d\n", visualInfo->visualid);
1729          printf("oglSystem.visualInfo visual ID = %d\n", oglSystem.visualInfo->visualid);
1730          printf("((XWindowData)display.windowDriverData).visual visual ID = %d\n", ((XWindowData)display.windowDriverData).visual->visualid);
1731 #endif
1732          // visualInfo = oglSystem.visualInfo;
1733 //#endif
1734          */
1735          if(visualInfo)
1736          {
1737             //printf("visualInfo is not null\n");
1738             // printf("Creating Display Context, sharing with %x!\n", oglSystem.glContext);
1739             oglDisplay.glContext = glXCreateContext(xGlobalDisplay, visualInfo, oglSystem.glContext, True);
1740             //XFree(visualInfo);
1741          }
1742
1743          // oglDisplay.glContext = glXCreateContext(xGlobalDisplay, oglSystem.visualInfo, oglSystem.glContext, True);
1744          if(oglDisplay.glContext)
1745          {
1746             //printf("CreateDisplay Got a Context\n");
1747             glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
1748             result = true;
1749          }
1750       #endif
1751    #endif
1752       }
1753 #if defined(__WIN32__) || defined(USEPBUFFER)
1754       else
1755          result = true;
1756 #endif
1757       if(result)
1758       {
1759 #if defined(__WIN32__)
1760          if(glBlendFuncSeparate)
1761             glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
1762          else
1763             glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1764 #else
1765 #if !defined(__OLDX__)
1766           glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
1767 #else
1768          glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1769 #endif
1770 #endif
1771          glEnable(GL_BLEND);
1772
1773          glMatrixMode(GL_MODELVIEW);
1774          glScaled(1.0, 1.0, -1.0);
1775          // glTranslatef(0.375f, 0.375f, 0.0f);
1776          // glTranslatef(-0.625f, -0.625f, 0.0f);
1777          glMatrixMode(GL_PROJECTION);
1778          glShadeModel(GL_FLAT);
1779
1780          // glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, true);
1781          glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1782          glFogi(GL_FOG_MODE, GL_EXP);
1783          glFogf(GL_FOG_DENSITY, 0);
1784          glEnable(GL_NORMALIZE);
1785          glDepthFunc(GL_LESS);
1786          glClearDepth(1.0);
1787          glDisable(GL_MULTISAMPLE_ARB);
1788       }
1789 #if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
1790       display.ambient = Color { 50,50,50 };
1791 #endif
1792
1793       if(!useSingleGLContext)
1794       {
1795    #if defined(__WIN32__)
1796          wglMakeCurrent(null, null);
1797    #elif defined(__unix__) || defined(__APPLE__)
1798       #if defined(__ANDROID__)
1799          result = true;
1800       #else
1801          glXMakeCurrent(xGlobalDisplay, None, null);
1802       #endif
1803    #endif
1804       }
1805
1806       return result;
1807    }
1808
1809    bool DisplaySize(Display display, int width, int height)
1810    {
1811       OGLDisplay oglDisplay = display.driverData;
1812
1813       bool result = false;
1814
1815       //printf("Inside DisplaySize\n");
1816 #if defined(__WIN32__) || defined(USEPBUFFER)
1817       OGLSystem oglSystem = display.displaySystem.driverData;
1818       if(display.alphaBlend)
1819       {
1820 #if defined(__WIN32__)
1821          const int attributes[]=
1822          {
1823             /*WGL_TEXTURE_FORMAT_ARB, WGL_TEXTURE_RGBA_ARB,
1824             WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB, */0
1825          };
1826          int pixelFormat = 0;
1827          if(wglChoosePixelFormatARB)
1828          {
1829             int valid;
1830             int numFormats;
1831             float fAttributes[] = {0,0};
1832             int iAttributes[] =
1833             {
1834                //WGL_DRAW_TO_BITMAP_ARB, GL_TRUE,
1835                WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
1836                     WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
1837                     WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
1838                     WGL_COLOR_BITS_ARB,24,
1839                     WGL_ALPHA_BITS_ARB,8,
1840                     WGL_DEPTH_BITS_ARB,16,
1841                     WGL_STENCIL_BITS_ARB,0,
1842                     WGL_DOUBLE_BUFFER_ARB,GL_FALSE,
1843                     WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
1844                     WGL_SAMPLES_ARB, 4,                                         // Check For 4x Multisampling
1845                     0,0
1846             };
1847
1848             //Log("Found wglChoosePixelFormatARB\n");
1849
1850             valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1851             if(!valid || !numFormats)
1852             {
1853                //Log("Can't find 4x multi sampling\n");
1854                iAttributes[19] = 2;
1855                valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1856                if(!valid || !numFormats)
1857                {
1858                   // Log("Can't find 2x multi sampling\n");
1859                   iAttributes[16] = 0;
1860                   iAttributes[17] = 0;
1861                   valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1862                   if(!valid || !numFormats)
1863                   {
1864                      int iAttributes[] =
1865                      {
1866                         WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
1867                         //WGL_DRAW_TO_BITMAP_ARB,GL_TRUE,
1868                         WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
1869                         WGL_COLOR_BITS_ARB,24,
1870                         WGL_ALPHA_BITS_ARB,8,
1871                         WGL_DEPTH_BITS_ARB,16,
1872                         0,0
1873                      };
1874                      valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1875                   }
1876                }
1877             }
1878             if(valid && numFormats)
1879             {
1880                wglMakeCurrent(null, null);
1881             }
1882          }
1883
1884          wglMakeCurrent( null, null );
1885          wglMakeCurrent( oglDisplay.hdc, oglDisplay.glrc );
1886          if(oglDisplay.hdc && oglDisplay.pBuffer)
1887             wglReleasePbufferDCARB(oglDisplay.pBuffer, oglDisplay.hdc);
1888
1889          wglDestroyPbufferARB(oglDisplay.pBuffer);
1890
1891          if(!useSingleGLContext)
1892             wglMakeCurrent( null, null );
1893
1894          if(oglDisplay.glrc)
1895             wglDeleteContext(oglDisplay.glrc);
1896
1897          oglDisplay.pBuffer = wglCreatePbufferARB(oglSystem.hdc, pixelFormat, width, height, attributes);
1898          oglDisplay.hdc = wglGetPbufferDCARB(oglDisplay.pBuffer);
1899          if((oglDisplay.glrc = wglCreateContext(oglDisplay.hdc)))
1900          {
1901             BITMAPINFO * info;
1902             HDC hdc = GetDC(display.window);
1903
1904             wglShareLists(oglSystem.glrc, oglDisplay.glrc);
1905             wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1906
1907             //wglQueryPbufferARB(pBuffer, WGL_PBUFFER_WIDTH_ARB, &width);
1908             //wglQueryPbufferARB(pBuffer, WGL_PBUFFER_HEIGHT_ARB, &height);
1909
1910             // glDeleteBuffersARB(2, oglDisplay.imageBuffers);
1911
1912             if((info = (BITMAPINFO *)new0 byte[sizeof(BITMAPINFOHEADER)+sizeof(RGBQUAD)*256]))
1913             {
1914                HBITMAP newBitmap;
1915
1916                if(oglDisplay.memDC) DeleteDC(oglDisplay.memDC);
1917                oglDisplay.memDC = CreateCompatibleDC(hdc);
1918                SetMapMode(oglDisplay.memDC, MM_TEXT);
1919                info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1920                info->bmiHeader.biPlanes = 1;
1921                info->bmiHeader.biCompression = BI_RGB;
1922                info->bmiHeader.biBitCount = 32; //(uint16)GetDeviceCaps(hdc, BITSPIXEL);
1923                info->bmiHeader.biWidth = width;
1924                info->bmiHeader.biHeight = height;
1925                newBitmap = CreateDIBSection(hdc, info, DIB_RGB_COLORS, &oglDisplay.picture, null, 0);
1926                if(newBitmap)
1927                {
1928                   SelectObject(oglDisplay.memDC, newBitmap);
1929                   if(oglDisplay.memBitmap) DeleteObject(oglDisplay.memBitmap);
1930                   /*
1931                   {
1932                      PIXELFORMATDESCRIPTOR pfd = { 0 };
1933                      pfd.nSize = (short)sizeof(pfd);
1934                      pfd.nVersion = 1;
1935                      pfd.dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_OPENGL;
1936                      pfd.iPixelType = PFD_TYPE_RGBA;
1937                      pfd.cColorBits = 32;
1938                      //pfd.cAlphaBits = 8;
1939                      pfd.cDepthBits = 24;
1940                      pfd.iLayerType = PFD_MAIN_PLANE;
1941
1942                      oglDisplay.hdc = oglDisplay.memDC;
1943
1944                      pixelFormat = ChoosePixelFormat(oglSystem.hdc, &pfd);
1945                      DescribePixelFormat(oglDisplay.hdc, pixelFormat, sizeof(pfd), &pfd);
1946                      SetPixelFormat(oglDisplay.hdc, pixelFormat, &pfd);
1947
1948                      oglDisplay.glrc = wglCreateContext(oglDisplay.hdc);
1949                      wglShareLists(oglSystem.glrc, oglDisplay.glrc);
1950                      wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1951                   }
1952                   */
1953                   /*
1954                   {
1955                      const int imageSize = width * height * 4;
1956
1957                      glGenBuffersARB(2, oglDisplay.imageBuffers);
1958
1959                      glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
1960                      glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, imageSize, null, GL_STREAM_READ);
1961                      // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
1962                      // glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, imageSize / 2, null, GL_STREAM_READ);
1963                   }
1964                   */
1965                   oglDisplay.memBitmap = newBitmap;
1966                   oglDisplay.stride = width;
1967
1968                   result = true;
1969                }
1970                delete info;
1971             }
1972             ReleaseDC(display.window, hdc);
1973          }
1974 #elif defined(__unix__) || defined(__APPLE__)
1975       #if defined(__ANDROID__)
1976          result = true;
1977       #else
1978         int attrib[] =
1979         {
1980                 GLX_DOUBLEBUFFER,  True,
1981             GLX_DEPTH_SIZE,    1,
1982                 GLX_RED_SIZE,      8,
1983                 GLX_GREEN_SIZE,    8,
1984                 GLX_BLUE_SIZE,     8,
1985                 GLX_ALPHA_SIZE,    8,
1986                 GLX_STENCIL_SIZE,  1,
1987                 //GLX_DEPTH_SIZE,    24,
1988                 GLX_RENDER_TYPE,   GLX_RGBA_BIT,
1989                 GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
1990                 None
1991         };
1992
1993         int PBattrib[] =
1994         {
1995                 GLX_PBUFFER_WIDTH,   width,
1996                 GLX_PBUFFER_HEIGHT,  height,
1997                 GLX_LARGEST_PBUFFER, False,
1998             None
1999         };
2000
2001         // choose a pixel format that meets our minimum requirements
2002         int count = 0;
2003
2004         GLXFBConfig *config = glXChooseFBConfig(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib, &count);
2005          if(config)
2006          {
2007             if(oglDisplay.pixmap)
2008             {
2009                XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
2010                oglDisplay.pixmap = None;
2011             }
2012             if(oglDisplay.shapePixmap)
2013             {
2014                XFreePixmap(xGlobalDisplay, oglDisplay.shapePixmap);
2015                oglDisplay.shapePixmap = None;
2016             }
2017
2018             // Free Shared Memory Pixmap
2019             if(oglDisplay.image)
2020             {
2021                if(oglDisplay.shminfoShape.shmid != -1)
2022                {
2023                   XShmDetach(xGlobalDisplay, &oglDisplay.shminfo);
2024                   if(oglDisplay.shminfo.shmaddr != (void *)-1)
2025                      shmdt(oglDisplay.shminfo.shmaddr);
2026                   shmctl(oglDisplay.shminfo.shmid, IPC_RMID, 0);
2027                }
2028                XDestroyImage(oglDisplay.image);
2029                oglDisplay.image = None;
2030             }
2031             if(oglDisplay.shapeImage)
2032             {
2033                if(oglDisplay.shminfoShape.shmid != -1)
2034                {
2035                   XShmDetach(xGlobalDisplay, &oglDisplay.shminfoShape);
2036                   if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
2037                      shmdt(oglDisplay.shminfoShape.shmaddr);
2038                   shmctl(oglDisplay.shminfoShape.shmid, IPC_RMID, 0);
2039                }
2040                XDestroyImage(oglDisplay.shapeImage);
2041                oglDisplay.shapeImage = None;
2042             }
2043
2044             if(oglDisplay.windowPicture)
2045                XRenderFreePicture(xGlobalDisplay, oglDisplay.windowPicture);
2046             if(oglDisplay.pixmapPicture)
2047                XRenderFreePicture(xGlobalDisplay, oglDisplay.pixmapPicture);
2048
2049             if(oglDisplay.pixmap)
2050                XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
2051
2052             if(oglDisplay.glContext)
2053                   glXDestroyContext(xGlobalDisplay, oglDisplay.glContext);
2054             if(oglDisplay.pBuffer)
2055                glXDestroyPbuffer(xGlobalDisplay, oglDisplay.pBuffer);
2056
2057                 oglDisplay.pBuffer = glXCreatePbuffer(xGlobalDisplay, config[0], PBattrib);
2058             if(oglDisplay.pBuffer)
2059             {
2060                    oglDisplay.glContext = glXCreateNewContext(xGlobalDisplay, config[0], GLX_RGBA_TYPE, oglSystem.glContext, True);
2061                if(oglDisplay.glContext)
2062                {
2063                   glXMakeCurrent(xGlobalDisplay, None, null);
2064                   glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
2065
2066                   // Initialize Shared Memory Pixmap
2067                   oglDisplay.image = XShmCreateImage(xGlobalDisplay, DefaultVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 32,
2068                      ZPixmap, null, &oglDisplay.shminfo, width, height);
2069                   if(oglDisplay.image)
2070                   {
2071                      oglDisplay.shminfo.shmid = shmget(IPC_PRIVATE,
2072                         oglDisplay.image->bytes_per_line * oglDisplay.image->height, IPC_CREAT|0777);
2073                      if(oglDisplay.shminfo.shmid != -1)
2074                      {
2075                         oglDisplay.shminfo.shmaddr = shmat(oglDisplay.shminfo.shmid, 0, 0);
2076                         if(oglDisplay.shminfo.shmaddr != (void *)-1)
2077                         {
2078                            oglDisplay.shminfo.readOnly = False;
2079                            if(XShmAttach(xGlobalDisplay, &oglDisplay.shminfo))
2080                            {
2081                               oglDisplay.pixmap = XShmCreatePixmap(xGlobalDisplay, (X11Window)display.window, oglDisplay.shminfo.shmaddr,
2082                                  &oglDisplay.shminfo, width, height, 32);
2083
2084                               // Initialize Shared Memory Shape Pixmap
2085                               oglDisplay.shapeImage = XShmCreateImage(xGlobalDisplay, DefaultVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 1,
2086                                  ZPixmap, null, &oglDisplay.shminfoShape, width, height);
2087                               if(oglDisplay.shapeImage)
2088                               {
2089                                  oglDisplay.shminfoShape.shmid = shmget(IPC_PRIVATE,
2090                                     oglDisplay.shapeImage->bytes_per_line * oglDisplay.shapeImage->height, IPC_CREAT|0777);
2091                                  if(oglDisplay.shminfoShape.shmid != -1)
2092                                  {
2093                                     oglDisplay.shminfoShape.shmaddr = shmat(oglDisplay.shminfoShape.shmid, 0, 0);
2094                                     if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
2095                                     {
2096                                        oglDisplay.shminfoShape.readOnly = False;
2097                                        if(XShmAttach(xGlobalDisplay, &oglDisplay.shminfoShape))
2098                                        {
2099                                           oglDisplay.shapePixmap = XShmCreatePixmap(xGlobalDisplay, (X11Window)display.window, oglDisplay.shminfoShape.shmaddr,
2100                                              &oglDisplay.shminfoShape, width, height, 1);
2101                                           //oglDisplay.shapePixmap = XCreatePixmap(xGlobalDisplay, (X11Window)display.window, width, height, 1);
2102
2103                                           {
2104                                              XRenderPictureAttributes attributes = { 0 };
2105                                              XRenderPictFormat * format = XRenderFindStandardFormat(xGlobalDisplay, /*PictStandardRGB24*/ PictStandardARGB32);
2106                                              #if !defined(__APPLE__) && !defined(__OLDX__)
2107                                              attributes.repeat = RepeatNormal;
2108                                              #else
2109                                              attributes.repeat = 1;
2110                                              #endif
2111                                              oglDisplay.pixmapPicture = XRenderCreatePicture(xGlobalDisplay, oglDisplay.pixmap, format, CPRepeat, &attributes);
2112                                              oglDisplay.windowPicture = XRenderCreatePicture(xGlobalDisplay, (X11Window)display.window, format, 0, &attributes);
2113                                              oglDisplay.shapePicture = XRenderCreatePicture(xGlobalDisplay, oglDisplay.shapePixmap,
2114                                                 XRenderFindStandardFormat(xGlobalDisplay, PictStandardA1), 0, &attributes);
2115                                           }
2116
2117                                           oglDisplay.picture = oglDisplay.shminfo.shmaddr;
2118                                           oglDisplay.stride = oglDisplay.image->bytes_per_line / 4;
2119
2120                                           result = true;
2121                                        }
2122                                     }
2123                                  }
2124                               }
2125                            }
2126                         }
2127                      }
2128                   }
2129                }
2130             }
2131             XFree(config);
2132          }
2133      #endif
2134 #endif
2135          CreateDisplay(display);
2136 #if defined(__WIN32__)
2137          wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
2138 #elif defined(__unix__) || defined(__APPLE__)
2139       #if defined(__ANDROID__)
2140          width = eglWidth;
2141          height = eglHeight;
2142       #else
2143          glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
2144       #endif
2145 #endif
2146       }
2147       else
2148 #endif
2149          result = true;
2150       if(!result && display.alphaBlend)
2151       {
2152          printf("Alpha blending windows not supported on this display\n");
2153       }
2154       if(!result)
2155          return false;
2156
2157       result = false;
2158
2159       glViewport(0,0,width,height);
2160       glLoadIdentity();
2161       glOrtho(0,width,height,0,0.0,1.0);
2162       displayWidth = display.width = width;
2163       displayHeight = display.height = height;
2164
2165       if(!oglDisplay.flippingBuffer || oglDisplay.flipBufW < width || oglDisplay.flipBufH < height)
2166       {
2167          oglDisplay.flipBufW = width;
2168          oglDisplay.flipBufH = height;
2169 #ifdef _GLES
2170          result = true;
2171 #else
2172          oglDisplay.flippingBuffer = renew oglDisplay.flippingBuffer ColorAlpha [width * height];
2173 #endif
2174       }
2175       if(oglDisplay.flippingBuffer || !width || !height)
2176          result = true;
2177
2178       return result;
2179    }
2180
2181    void DisplayPosition(Display display, int x, int y)
2182    {
2183       OGLDisplay oglDisplay = display.driverData;
2184
2185       oglDisplay.x = x;
2186       oglDisplay.y = y;
2187    }
2188
2189    void SetPalette(Display display, ColorAlpha * palette, bool colorMatch)
2190    {
2191    }
2192
2193    void RestorePalette(Display display)
2194    {
2195    }
2196
2197    void StartUpdate(Display display)
2198    {
2199    }
2200
2201    void EndUpdate(Display display)
2202    {
2203    }
2204
2205    void Scroll(Display display, Box scroll, int x, int y, Extent dirty)
2206    {
2207    }
2208
2209    void Update(Display display, Box updateBox)
2210    {
2211 #if defined(__WIN32__) || defined(USEPBUFFER)
2212       OGLDisplay oglDisplay = display.driverData;
2213 #endif
2214       //Logf("DisplayScreen\n");
2215
2216       glFlush();
2217       glFinish();
2218 #if defined(__WIN32__) || defined(USEPBUFFER)
2219       if(display.alphaBlend)
2220       {
2221          glPixelStorei(GL_PACK_ALIGNMENT, 4);
2222          glPixelStorei(GL_PACK_ROW_LENGTH, oglDisplay.stride);
2223          glPixelStorei(GL_PACK_SKIP_ROWS, 0);
2224          glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
2225          glReadPixels(0,0,display.width,display.height,GL_BGRA_EXT,GL_UNSIGNED_BYTE, oglDisplay.picture);
2226
2227          {
2228 #if defined(__WIN32__)
2229             HDC hdc = GetDC(0);
2230             POINT point = { oglDisplay.x, oglDisplay.y};
2231             POINT srcPoint = { 0, 0 };
2232             BLENDFUNCTION blend = { 0 };
2233             SIZE size;
2234             size.cx = display.width;
2235             size.cy = display.height;
2236             blend.BlendOp = AC_SRC_OVER;
2237             blend.BlendFlags = 0;
2238             blend.SourceConstantAlpha = 255;
2239             blend.AlphaFormat = AC_SRC_ALPHA;
2240
2241             /*
2242             // Process partial images.  Mapping the buffer waits for
2243             // outstanding DMA transfers into the buffer to finish.
2244             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2245             oglDisplay.pboMemory1 = (byte *)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY);
2246
2247             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2248             // oglDisplay.pboMemory2 = (byte *)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB,GL_READ_ONLY);
2249
2250
2251             memcpy(oglDisplay.picture, oglDisplay.pboMemory1, display.width * display.height * 4);
2252             //memcpy(oglDisplay.picture + display.width * display.height * 4 / 2, oglDisplay.pboMemory2, display.width * display.height * 4/ 2);
2253             */
2254
2255             UpdateLayeredWindow(display.window, hdc, &point, &size, oglDisplay.memDC, &srcPoint, 0, &blend, ULW_ALPHA);
2256             /*
2257
2258             // Unmap the image buffers
2259             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2260             glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);
2261
2262             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2263             // glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);
2264
2265             // Bind two different buffer objects and start the glReadPixels
2266             // asynchronously. Each call will return directly after
2267             // starting the DMA transfer.
2268             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2269             glReadPixels(0, 0, display.width, display.height, GL_BGRA, GL_UNSIGNED_BYTE, 0);
2270
2271             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2272             // glReadPixels(0, display.height/2, display.width, display.height/2, GL_BGRA, GL_UNSIGNED_BYTE, 0);
2273             */
2274
2275             ReleaseDC(0, hdc);
2276 #elif defined(__unix__) || defined(__APPLE__)
2277       #if defined(__ANDROID__)
2278       #else
2279             XTransform transform =
2280             {
2281                {
2282                   { (int)(1.0f * (1<<16)), (int)(0.0f * (1<<16)),  (int)(0 * (1 << 16)) },
2283                   { (int)(0.0f),           (int)(-1.0f * (1<<16)), (int)(0 * (1<<16)) },
2284                   { (int)(0.0f * (1<<16)), (int)(0.0f * (1<<16)),  (int)(1.0f * (1<<16)) }
2285                }
2286             };
2287             XRenderSetPictureTransform(xGlobalDisplay, oglDisplay.pixmapPicture, &transform);
2288             XRenderComposite(xGlobalDisplay, PictOpSrc, oglDisplay.pixmapPicture, None, oglDisplay.shapePicture, 0, 0, 0, 0, 0, 0, display.width, display.height);
2289             XRenderComposite(xGlobalDisplay, PictOpSrc, oglDisplay.pixmapPicture, None, oglDisplay.windowPicture, 0, 0, 0, 0, 0, 0, display.width, display.height);
2290             #if !defined(__APPLE__) && !defined(__OLDX__)
2291             XShapeCombineMask(xGlobalDisplay, (X11Window)display.window, ShapeInput, 0, 0, oglDisplay.shapePixmap, ShapeSet);
2292             #else
2293             XShapeCombineMask(xGlobalDisplay, display.window, 2, 0, 0, oglDisplay.shapePixmap, ShapeSet);
2294             #endif
2295             XFlush(xGlobalDisplay);
2296      #endif
2297 #endif
2298          }
2299       }
2300       else
2301 #endif
2302       {
2303 #if defined(__WIN32__)
2304          //wglSwapLayerBuffers(oglDisplay.hdc,WGL_SWAP_MAIN_PLANE);
2305          SwapBuffers(oglDisplay.hdc);
2306 #elif defined(__unix__) || defined(__APPLE__)
2307       #if defined(__ANDROID__)
2308          eglSwapBuffers(eglDisplay, eglSurface);
2309       #else
2310          glXSwapBuffers(xGlobalDisplay, (GLXDrawable)display.window);
2311       #endif
2312 #endif
2313       }
2314       //Logf("Out of DisplayScreen\n");
2315    }
2316
2317    void FreeBitmap(DisplaySystem displaySystem, Bitmap bitmap)
2318    {
2319       if(bitmap.driverData)
2320       {
2321          GLuint tex = (GLuint)(uintptr)bitmap.driverData;
2322          glDeleteTextures(1, &tex);
2323          bitmap.driverData = 0;
2324       }
2325       bitmap.driver = ((subclass(DisplayDriver))class(LFBDisplayDriver));
2326    }
2327
2328    bool AllocateBitmap(DisplaySystem displaySystem, Bitmap bitmap, int width, int height, int stride, PixelFormat format, bool allocatePalette)
2329    {
2330       OGLSystem oglSystem = displaySystem.driverData;
2331       bool result = false;
2332       Bitmap mipMap { };
2333       GLuint glBitmap = 0;
2334
2335       uint w = width, h = height;
2336       if(oglSystem.pow2textures)
2337       {
2338          w = pow2i(w);
2339          h = pow2i(h);
2340       }
2341       w = Min(w, oglSystem.maxTextureSize);
2342       h = Min(h, oglSystem.maxTextureSize);
2343
2344       glGenTextures(1, &glBitmap);
2345       glBindTexture(GL_TEXTURE_2D, glBitmap);
2346
2347       glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
2348
2349       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2350       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2351
2352       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2353       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2354
2355       glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
2356
2357       mipMap.Allocate(null, w, h, w, pixelFormatRGBA, false);
2358
2359       // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2360       glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2361
2362       delete mipMap;
2363
2364       bitmap.driverData = (void *)(uintptr)glBitmap;
2365       bitmap.driver = displaySystem.driver;
2366       bitmap.width = w;
2367       bitmap.height = h;
2368
2369       result = true;
2370       return result;
2371    }
2372
2373    bool MakeDDBitmap(DisplaySystem displaySystem, Bitmap bitmap, bool mipMaps)
2374    {
2375       bool result = false;
2376       OGLSystem oglSystem = displaySystem.driverData;
2377
2378       // Pre process the bitmap... First make it 32 bit
2379       if(/*bitmap.pixelFormat == pixelFormatRGBA || */bitmap.Convert(null, pixelFormat888, null))
2380       {
2381          int c, level;
2382          uint w = bitmap.width, h = bitmap.height;
2383          GLuint glBitmap = 0;
2384          if(oglSystem.pow2textures)
2385          {
2386             w = pow2i(w);
2387             h = pow2i(h);
2388          }
2389          w = Min(w, oglSystem.maxTextureSize);
2390          h = Min(h, oglSystem.maxTextureSize);
2391
2392          if(mipMaps)
2393          {
2394             while(w * 2 < h) w *= 2;
2395             while(h * 2 < w) h *= 2;
2396          }
2397
2398          // Switch ARGB to RGBA
2399          //if(bitmap.format != pixelFormatRGBA)
2400          {
2401             for(c=0; c<bitmap.size; c++)
2402             {
2403                // ((ColorRGBA *)bitmap.picture)[c] = ((ColorAlpha *)bitmap.picture)[c];
2404                // TODO:
2405                ColorAlpha color = ((ColorAlpha *)bitmap.picture)[c];
2406                ((ColorRGBA *)bitmap.picture)[c] = ColorRGBA { color.color.r, color.color.g, color.color.b, color.a };
2407             }
2408          }
2409          bitmap.pixelFormat = pixelFormat888;
2410
2411          glGetError();
2412          glGenTextures(1, &glBitmap);
2413          if(glBitmap == 0)
2414          {
2415             //int error = glGetError();
2416             return false;
2417          }
2418
2419          glBindTexture(GL_TEXTURE_2D, glBitmap);
2420          glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
2421
2422          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mipMaps ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
2423          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2424
2425          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2426
2427          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
2428          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
2429
2430          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2431          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2432
2433          glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
2434
2435          result = true;
2436
2437          for(level = 0; result && (w >= 1 || h >= 1); level++, w >>= 1, h >>= 1)
2438          {
2439             Bitmap mipMap;
2440             if(!w) w = 1;
2441             if(!h) h = 1;
2442             if(bitmap.width != w || bitmap.height != h)
2443             {
2444                mipMap = Bitmap { };
2445                if(mipMap.Allocate(null, w, h, w, bitmap.pixelFormat, false))
2446                {
2447                   Surface mipSurface = mipMap.GetSurface(0,0,null);
2448                   mipSurface.Filter(bitmap, 0,0,0,0, w, h, bitmap.width, bitmap.height);
2449                   delete mipSurface;
2450                }
2451                else
2452                {
2453                   result = false;
2454                   delete mipMap;
2455                }
2456             }
2457             else
2458                mipMap = bitmap;
2459
2460             if(result)
2461             {
2462                int error;
2463                //int width = 0;
2464                glGetError();
2465                // glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2466                glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2467                //printf("Calling glTexImage2D\n");
2468                //glGetTexLevelParameteriv(GL_TEXTURE_2D, level, GL_TEXTURE_WIDTH, &width);
2469                //printf("width = %d (Should be %d, %d)\n", width, w, h);
2470                if((error = glGetError()))
2471                {
2472                   //Logf("OpenGL Bitmap MakeDD error: %d...\n", error);
2473                   //printf("OpenGL Bitmap MakeDD error: %d...\n", error);
2474                   result = false;
2475                }
2476             }
2477             if(mipMap != bitmap)
2478                delete mipMap;
2479             if(!mipMaps) break;
2480          }
2481
2482          if(!bitmap.keepData)
2483             bitmap.driver.FreeBitmap(bitmap.displaySystem, bitmap);
2484          bitmap.driverData = (void *)(uintptr)glBitmap;
2485          bitmap.driver = displaySystem.driver;
2486
2487          if(!result)
2488             FreeBitmap(displaySystem, bitmap);
2489          else if(oglSystem.loadingFont)
2490          {
2491             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2492             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2493             oglSystem.loadingFont = false;
2494          }
2495       }
2496       return result;
2497    }
2498
2499    void ReleaseSurface(Display display, Surface surface)
2500    {
2501       glDisable(GL_SCISSOR_TEST);
2502       delete surface.driverData;
2503       surface.driverData = null;
2504    }
2505
2506    bool GetBitmapSurface(DisplaySystem displaySystem, Surface surface, Bitmap bitmap, int x, int y, Box clip)
2507    {
2508       return false;
2509    }
2510
2511    bool GetSurface(Display display, Surface surface, int x,int y, Box clip)
2512    {
2513       bool result = false;
2514       OGLSurface oglSurface = surface.driverData = OGLSurface { };
2515
2516       //Logf("GetSurface\n");
2517
2518       if(oglSurface)
2519       {
2520          if(displayWidth != display.width || displayHeight != display.height)
2521          {
2522             displayWidth = display.width;
2523             displayHeight = display.height;
2524
2525             glViewport(0,0,display.width,display.height);
2526             glLoadIdentity();
2527             glOrtho(0,display.width,display.height,0,0.0,1.0);
2528          }
2529
2530          surface.offset.x = x;
2531          surface.offset.y = y;
2532          surface.unclippedBox = surface.box = clip;
2533          oglSurface.bitmapMult[0] = 1;
2534          oglSurface.bitmapMult[1] = 1;
2535          oglSurface.bitmapMult[2] = 1;
2536          oglSurface.bitmapMult[3] = 1;
2537
2538          glEnable(GL_SCISSOR_TEST);
2539          glScissor(
2540             x+clip.left,
2541             (display.height) -(y+clip.bottom)-1,
2542             clip.right-clip.left+1,
2543             clip.bottom-clip.top+1);
2544          result = true;
2545       }
2546       return result;
2547    }
2548
2549    void Clip(Display display, Surface surface, Box clip)
2550    {
2551       Box box;
2552
2553       //Logf("Clip\n");
2554
2555       if(clip != null)
2556       {
2557          box = clip;
2558          box.Clip(surface.unclippedBox);
2559          surface.box = box;
2560       }
2561       else
2562          box = surface.box = surface.unclippedBox;
2563       box.left += surface.offset.x;
2564       box.top  += surface.offset.y;
2565       box.right+= surface.offset.x;
2566       box.bottom += surface.offset.y;
2567
2568       glScissor(
2569          box.left,display.height - box.bottom - 1,
2570          box.right-box.left+1, box.bottom-box.top+1);
2571    }
2572
2573    bool GrabScreen(Display display, Bitmap bitmap, int x, int y, unsigned int w, unsigned int h)
2574    {
2575       bool result = false;
2576       OGLDisplay oglDisplay = display.driverData;
2577       ColorAlpha * flippingBuffer = oglDisplay.flippingBuffer;
2578
2579       if(oglDisplay.flippingBuffer)
2580       {
2581          if(bitmap.pixelFormat != pixelFormat888 || bitmap.width < w || bitmap.height < h)
2582          {
2583             bitmap.Free();
2584             bitmap.Allocate(null, w,h,w, pixelFormat888, false);
2585          }
2586          if(bitmap)
2587          {
2588             uint row;
2589
2590             glPixelStorei(GL_PACK_ALIGNMENT, 4);
2591             glPixelStorei(GL_PACK_ROW_LENGTH, bitmap.stride);
2592             glPixelStorei(GL_PACK_SKIP_ROWS, 0);
2593             glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
2594             glReadPixels(x,display.height-h-y,w,h,GL_BGRA_EXT,GL_UNSIGNED_BYTE, flippingBuffer);
2595
2596             // Need a flip...
2597             for(row = 0; row<h; row++)
2598                CopyBytesBy4(((ColorAlpha *)bitmap.picture) + row * w, ((ColorAlpha *)flippingBuffer) + (h-row-1) * w, w);
2599             result = true;
2600          }
2601       }
2602       return result;
2603    }
2604
2605    void SetForeground(Display display, Surface surface, ColorAlpha color)
2606    {
2607       OGLSurface oglSurface = surface.driverData;
2608
2609       //Logf("SetForeground\n");
2610
2611       oglSurface.foreground[0] = color.color.r/255.0f;
2612       oglSurface.foreground[1] = color.color.g/255.0f;
2613       oglSurface.foreground[2] = color.color.b/255.0f;
2614       //oglSurface.foreground[3] = 1.0f;
2615       oglSurface.foreground[3] = color.a/255.0f;
2616
2617       //if(!oglSurface.foreground[3])printf("bug");
2618    }
2619
2620    void SetBackground(Display display, Surface surface, ColorAlpha color)
2621    {
2622       OGLSurface oglSurface = surface.driverData;
2623
2624       //Logf("SetBackground\n");
2625
2626       oglSurface.background[0] = color.color.r/255.0f;
2627       oglSurface.background[1] = color.color.g/255.0f;
2628       oglSurface.background[2] = color.color.b/255.0f;
2629       //oglSurface.background[3] = 1.0;
2630       oglSurface.background[3] = color.a/255.0f;
2631    }
2632
2633    void SetBlitTint(Display display, Surface surface, ColorAlpha color)
2634    {
2635       OGLSurface oglSurface = surface.driverData;
2636
2637       oglSurface.bitmapMult[0] = color.color.r/255.0f;
2638       oglSurface.bitmapMult[1] = color.color.g/255.0f;
2639       oglSurface.bitmapMult[2] = color.color.b/255.0f;
2640       oglSurface.bitmapMult[3] = color.a/255.0f;
2641    }
2642
2643    ColorAlpha GetPixel(Display display, Surface surface,int x,int y)
2644    {
2645       return 0;
2646    }
2647
2648    void PutPixel(Display display, Surface surface,int x,int y)
2649    {
2650       OGLSurface oglSurface = surface.driverData;
2651
2652       //Logf("PutPixel\n");
2653
2654       glColor4fv(oglSurface.foreground);
2655       glBegin(GL_POINTS);
2656       // glVertex2i(x+surface.offset.x, y+surface.offset.y);
2657       glVertex2f(x+surface.offset.x + 0.5f, y+surface.offset.y + 0.5f);
2658
2659       glEnd();
2660    }
2661
2662    void DrawLine(Display display, Surface surface, int _x1, int _y1, int _x2, int _y2)
2663    {
2664       OGLSurface oglSurface = surface.driverData;
2665       float x1 = _x1, x2 = _x2, y1 = _y1, y2 = _y2;
2666       if(_x1 == _x2)
2667       {
2668          if(_y2 >= _y1)
2669             y2 += 1;
2670          else
2671             y1 += 1;
2672       }
2673       else if(_y1 == _y2)
2674       {
2675          if(_x2 >= _x1)
2676             x2 += 1;
2677          else
2678             x1 += 1;
2679       }
2680       x1 += surface.offset.x;
2681       y1 += surface.offset.y;
2682       x2 += surface.offset.x;
2683       y2 += surface.offset.y;
2684
2685       //Logf("Line\n");
2686
2687       glColor4fv(oglSurface.foreground);
2688       glBegin(GL_LINES);
2689 #ifdef _GLES
2690       if(stippleEnabled)
2691       {
2692          glTexCoord2f(0.5f, 0);
2693          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2694          glTexCoord2f(Max(x2-x1, y2-y1) + 0.5f, 0);
2695          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2696       }
2697       else
2698 #endif
2699       {
2700          /*
2701          glVertex2i(x1, y1);
2702          glVertex2i(x2, y2);
2703          */
2704          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2705          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2706       }
2707
2708       glEnd();
2709    }
2710
2711    void Rectangle(Display display, Surface surface,int x1,int y1,int x2,int y2)
2712    {
2713       OGLSurface oglSurface = surface.driverData;
2714       x1 += surface.offset.x;
2715       y1 += surface.offset.y;
2716       x2 += surface.offset.x;
2717       y2 += surface.offset.y;
2718
2719       //Logf("Rectangle\n");
2720
2721       glColor4fv(oglSurface.foreground);
2722 #ifdef _GLES
2723       if(stippleEnabled)
2724       {
2725          glBegin(GL_LINES);
2726
2727          glTexCoord2f(0.5f, 0);
2728          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2729          glTexCoord2f(y2-y1 + 0.5f, 0);
2730          glVertex2f(x1 + 0.5f, y2 + 0.5f);
2731
2732          glTexCoord2f(0.5f, 0);
2733          glVertex2f(x1 + 0.5f, y2 + 0.5f);
2734          glTexCoord2f(x2 - x1 + 0.5f, 0);
2735          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2736
2737          glTexCoord2f(0.5f, 0);
2738          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2739          glTexCoord2f(y1 - y2 + 0.5f, 0);
2740          glVertex2f(x2 + 0.5f, y1 + 0.5f);
2741
2742          glTexCoord2f(0.5f, 0);
2743          glVertex2f(x2 + 0.5f, y1 + 0.5f);
2744          glTexCoord2f(x1 - x2 + 0.5f, 0);
2745          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2746       }
2747       else
2748 #endif
2749       {
2750          glBegin(GL_LINE_LOOP);
2751          /*
2752          glVertex2i(x1, y1);
2753          glVertex2i(x1, y2);
2754          glVertex2i(x2, y2);
2755          glVertex2i(x2, y1);
2756          */
2757          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2758          glVertex2f(x1 + 0.5f, y2 + 0.5f);
2759          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2760          glVertex2f(x2 + 0.5f, y1 + 0.5f);
2761       }
2762       glEnd();
2763    }
2764
2765    void Area(Display display, Surface surface,int x1,int y1,int x2,int y2)
2766    {
2767       OGLSurface oglSurface = surface.driverData;
2768       //Logf("Area\n");
2769
2770       glColor4fv(oglSurface.background);
2771       glRecti(x1+surface.offset.x, y1+surface.offset.y,
2772               x2+surface.offset.x + 1, y2+surface.offset.y + 1);
2773
2774       /*
2775       glRectf(x1+surface.offset.x, y1+surface.offset.y,
2776               x2+surface.offset.x + 1, y2+surface.offset.y + 1);
2777       */
2778    }
2779
2780    void Clear(Display display, Surface surface, ClearType type)
2781    {
2782       OGLDisplay oglDisplay = display.driverData;
2783       OGLSurface oglSurface = surface.driverData;
2784
2785       //Logf("Clear\n");
2786       if(type != depthBuffer)
2787          glClearColor(oglSurface.background[0], oglSurface.background[1], oglSurface.background[2], oglSurface.background[3]);
2788       if(type != colorBuffer && !oglDisplay.depthWrite)
2789       {
2790          glDepthMask((byte)bool::true);
2791       }
2792       glClear(((type != depthBuffer) ? GL_COLOR_BUFFER_BIT : 0) |
2793               ((type != colorBuffer) ? GL_DEPTH_BUFFER_BIT : 0));
2794       if(type != colorBuffer && !oglDisplay.depthWrite)
2795       {
2796          glDepthMask((byte)bool::false);
2797       }
2798    }
2799
2800    bool ConvertBitmap(DisplaySystem displaySystem, Bitmap bitmap, PixelFormat format, ColorAlpha * palette)
2801    {
2802       return true;
2803    }
2804
2805    void Blit(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h)
2806    {
2807       OGLSurface oglSurface = surface.driverData;
2808
2809 #if !defined(__OLDX__)
2810          // WHY DO WE HAVE GL_ONE HERE ?
2811          /*if(glBlendFuncSeparate && !oglSurface.writingText)
2812             glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2813 #endif
2814
2815       if(!oglSurface.writingText)
2816       {
2817          // glTranslatef(-0.375f, -0.375f, 0.0f);
2818          glEnable(GL_TEXTURE_2D);
2819          glColor4fv(oglSurface.bitmapMult);
2820       }
2821       else if(oglSurface.xOffset)
2822          glTranslated(oglSurface.xOffset / 64.0/*-0.375*/, 0.0, 0.0);
2823
2824       glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)bitmap.driverData);
2825       glBegin(GL_QUADS);
2826
2827       if(h < 0)
2828       {
2829          glTexCoord2f((float)sx/ bitmap.width, (float)(sy-h)/ bitmap.height);
2830          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2831          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy-h)/ bitmap.height);
2832          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2833          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
2834          glVertex2i(dx+w+surface.offset.x, dy-h+surface.offset.y);
2835          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
2836          glVertex2i(dx+surface.offset.x, dy-h+surface.offset.y);
2837       }
2838       else
2839       {
2840          /*
2841          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
2842          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2843          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
2844          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2845          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy+h)/ bitmap.height);
2846          glVertex2i(dx+w+surface.offset.x, dy+h+surface.offset.y);
2847          glTexCoord2f((float)sx/ bitmap.width, (float)(sy+h)/ bitmap.height);
2848          glVertex2i(dx+surface.offset.x, dy+h+surface.offset.y);
2849          */
2850
2851          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
2852          glVertex2f((float)dx+surface.offset.x, (float)dy+surface.offset.y);
2853          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
2854          glVertex2f((float)dx+w+surface.offset.x, (float)dy+surface.offset.y);
2855          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy+h)/ bitmap.height);
2856          glVertex2f((float)dx+w+surface.offset.x, (float)dy+h+surface.offset.y);
2857          glTexCoord2f((float)sx/ bitmap.width, (float)(sy+h)/ bitmap.height);
2858          glVertex2f((float)dx+surface.offset.x, (float)dy+h+surface.offset.y);
2859       }
2860       glEnd();
2861
2862       if(!oglSurface.writingText)
2863       {
2864          glDisable(GL_TEXTURE_2D);
2865
2866          //glTranslate(0.375, 0.375, 0.0);
2867       }
2868       else if(oglSurface.xOffset)
2869          glTranslated(-oglSurface.xOffset / 64.0/*+0.375*/, 0.0, 0.0);
2870
2871 #if !defined(__OLDX__)
2872          /*if(glBlendFuncSeparate && !oglSurface.writingText)
2873             glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2874 #endif
2875    }
2876
2877    void Stretch(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
2878    {
2879       OGLSurface oglSurface = surface.driverData;
2880
2881       //glTranslate(-0.375, -0.375, 0.0);
2882
2883       //Logf("Stretch\n");
2884
2885 #if !defined(__OLDX__)
2886       /*if(glBlendFuncSeparate)
2887          glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2888 #endif
2889
2890       glEnable(GL_TEXTURE_2D);
2891       glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)bitmap.driverData);
2892
2893       glColor4fv(oglSurface.bitmapMult);
2894
2895       glBegin(GL_QUADS);
2896
2897       if(h < 0)
2898       {
2899          glTexCoord2f((float)(sx)/ bitmap.width, (float)(sy+sh)/ bitmap.height);
2900          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2901
2902          glTexCoord2f((float)(sx+sw) / bitmap.width, (float)(sy+sh)/ bitmap.height);
2903          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2904
2905          glTexCoord2f((float)(sx+sw)/ bitmap.width, (float)(sy)/ bitmap.height);
2906          glVertex2i(dx+w+surface.offset.x, dy-h+surface.offset.y);
2907
2908          glTexCoord2f((float)(sx) / bitmap.width, (float)(sy)/ bitmap.height);
2909          glVertex2i(dx+surface.offset.x, dy-h+surface.offset.y);
2910       }
2911       else
2912       {
2913          glTexCoord2f((float)(sx) / bitmap.width, (float)(sy)/ bitmap.height);
2914          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2915
2916          glTexCoord2f((float)(sx+sw)/ bitmap.width, (float)(sy)/ bitmap.height);
2917          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2918
2919          glTexCoord2f((float)(sx+sw) / bitmap.width, (float)(sy+sh)/ bitmap.height);
2920          glVertex2i(dx+w+surface.offset.x, dy+h+surface.offset.y);
2921
2922          glTexCoord2f((float)(sx)/ bitmap.width, (float)(sy+sh)/ bitmap.height);
2923          glVertex2i(dx+surface.offset.x, dy+h+surface.offset.y);
2924       }
2925
2926       glEnd();
2927
2928       glDisable(GL_TEXTURE_2D);
2929
2930       //glTranslate(0.375, 0.375, 0.0);
2931 #if !defined(__OLDX__)
2932       /*if(glBlendFuncSeparate)
2933          glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2934 #endif
2935
2936    }
2937
2938    void Filter(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
2939    {
2940       Stretch(display, surface, bitmap, dx, dy, sx, sy, w, h, sw, sh);
2941    }
2942
2943    void StretchDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
2944    {
2945       float s2dw,s2dh,d2sw,d2sh;
2946       //bool flipX = false, flipY = false;
2947
2948       //Logf("StretchDI\n");
2949
2950       if(Sgn(w) != Sgn(sw))
2951       {
2952          w = Abs(w);
2953          sw = Abs(sw);
2954          //flipX = true;
2955       }
2956       if(Sgn(h) != Sgn(sh))
2957       {
2958          h = Abs(h);
2959          sh = Abs(sh);
2960          //flipY = true;
2961       }
2962
2963       s2dw=(float)w / sw;
2964       s2dh=(float)h / sh;
2965       d2sw=(float)sw / w;
2966       d2sh=(float)sh / h;
2967
2968       //Clip against the edges of the source
2969       if(sx<0)
2970       {
2971          dx+=(int)((0-sx) * s2dw);
2972          w-=(int)((0-sx) * s2dw);
2973          sw-=0-sx;
2974          sx=0;
2975       }
2976       if(sy<0)
2977       {
2978          dy+=(int)((0-sy) * s2dh);
2979          h-=(int)((0-sy) * s2dh);
2980
2981          sh-=0-sy;
2982          sy=0;
2983       }
2984       if(sx+sw>bitmap.width-1)
2985       {
2986          w-=(int)((sx+sw-(bitmap.width-1)-1)*s2dw);
2987          sw-=sx+sw-(bitmap.width-1)-1;
2988       }
2989       if(sy+sh>(bitmap.height-1))
2990       {
2991          h-=(int)((sy+sh-(bitmap.height-1)-1)*s2dh);
2992          sh-=sy+sh-(bitmap.height-1)-1;
2993       }
2994       //Clip against the edges of the surfaceination
2995       if(dx<surface.box.left)
2996       {
2997          //if(!flip)
2998          sx+=(int)((surface.box.left-dx)*d2sw);
2999          sw-=(int)((surface.box.left-dx)*d2sw);
3000          w-=surface.box.left-dx;
3001          dx=surface.box.left;
3002       }
3003       if(dy<surface.box.top)
3004       {
3005          sy+=(int)((surface.box.top-dy)*d2sh);
3006          sh-=(int)((surface.box.top-dy)*d2sh);
3007          h-=surface.box.top-dy;
3008          dy=surface.box.top;
3009       }
3010       if(dx+w>surface.box.right)
3011       {
3012          //if(flip) sx+=(int)((dx+w-surface.box.right-1)*d2sw);
3013          sw-=(int)((dx+w-surface.box.right-1)*d2sw);
3014          w-=dx+w-surface.box.right-1;
3015       }
3016       if(dy+h>surface.box.bottom)
3017       {
3018          sh-=(int)((dy+h-surface.box.bottom-1)*d2sh);
3019          h-=dy+h-surface.box.bottom-1;
3020       }
3021       if((w<=0)||(h<=0)||(sw<=0)||(sh<=0)) return;
3022
3023       dx += surface.offset.x;
3024       dy += surface.offset.y;
3025
3026       if(bitmap.pixelFormat == pixelFormat888 && !bitmap.paletteShades)
3027       {
3028          glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
3029          glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.stride);
3030          glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
3031          glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
3032          glRasterPos2d(dx,dy);
3033          //glPixelZoom(flipX ? -s2dw : s2dw, flipY ? s2dh : -s2dh);
3034          glPixelZoom(s2dw, -s2dh);
3035          glDrawPixels(sw,sh,GL_BGRA_EXT,GL_UNSIGNED_BYTE, bitmap.picture);
3036          glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
3037          glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
3038          glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
3039          glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
3040       }
3041    }
3042
3043    void BlitDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h)
3044    {
3045       //Logf("BlitDI\n");
3046
3047       //Clip against the edges of the source
3048       if(sx<0)
3049       {
3050          dx+=-sx;
3051          w-=-sx;
3052          sx=0;
3053       }
3054       if(sy<0)
3055       {
3056          dy+=0-sy;
3057          h-=0-sy;
3058          sy=0;
3059       }
3060       if(sx+w>bitmap.width-1)
3061          w-=sx+w-(bitmap.width-1)-1;
3062       if(sy+h>bitmap.height-1)
3063          h-=sy+h-(bitmap.height-1)-1;
3064       //Clip against the edges of the surfaceination
3065       if(dx<surface.box.left)
3066       {
3067          //if(!flip)
3068          sx+=surface.box.left-dx;
3069          w-=surface.box.left-dx;
3070          dx=surface.box.left;
3071       }
3072       if(dy<surface.box.top)
3073       {
3074          sy+=surface.box.top-dy;
3075          h-=surface.box.top-dy;
3076          dy=surface.box.top;
3077       }
3078       if(dx+w>surface.box.right)
3079       {
3080          //if(flip) sx+=dx+w-surface.box.right-1;
3081          w-=dx+w-surface.box.right-1;
3082       }
3083       if(dy+h>surface.box.bottom)
3084          h-=dy+h-surface.box.bottom-1;
3085       if((w<=0)||(h<=0))
3086          return;
3087
3088       dx += surface.offset.x;
3089       dy += surface.offset.y;
3090
3091       if(bitmap.pixelFormat == pixelFormat888 && !bitmap.paletteShades)
3092       {
3093          glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
3094          glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.stride);
3095          glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
3096          glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
3097          glRasterPos2d(dx,dy);
3098          glPixelZoom(1,-1);
3099          glDrawPixels(w,h,GL_BGRA_EXT,GL_UNSIGNED_BYTE, bitmap.picture);
3100          glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
3101          glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
3102          glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
3103          glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
3104       }
3105    }
3106
3107    void FilterDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
3108    {
3109       StretchDI(display, surface, bitmap, dx, dy, sx, sy, w, h, sw, sh);
3110    }
3111
3112    void UnloadFont(DisplaySystem displaySystem, Font font)
3113    {
3114       ((subclass(DisplayDriver))class(LFBDisplayDriver)).UnloadFont(displaySystem, font);
3115    }
3116
3117    Font LoadFont(DisplaySystem displaySystem, const char * faceName, float size, FontFlags flags)
3118    {
3119       Font font;
3120       OGLSystem oglSystem = displaySystem.driverData;
3121       oglSystem.loadingFont = true;
3122       font = ((subclass(DisplayDriver))class(LFBDisplayDriver)).LoadFont(displaySystem, faceName, size, flags);
3123       return font;
3124    }
3125
3126    void FontExtent(DisplaySystem displaySystem, Font font, const char * text, int len, int * width, int * height)
3127    {
3128       ((subclass(DisplayDriver))class(LFBDisplayDriver)).FontExtent(displaySystem, font, text, len, width, height);
3129    }
3130
3131    void WriteText(Display display, Surface surface, int x, int y, const char * text, int len)
3132    {
3133       OGLSurface oglSurface = surface.driverData;
3134       OGLSystem oglSystem = display.displaySystem.driverData;
3135       oglSystem.loadingFont = true;
3136
3137       //glTranslated(-0.375, -0.375, 0.0);
3138
3139       //Logf("Blit\n");
3140
3141       if(surface.textOpacity)
3142       {
3143          int w, h;
3144          FontExtent(display.displaySystem, surface.font, text, len, &w, &h);
3145          display.displaySystem.driver.Area(display, surface,x,y,x+w-1,y+h-1);
3146       }
3147
3148       oglSurface.writingText = true;
3149
3150       glEnable(GL_TEXTURE_2D);
3151       glColor4fv(oglSurface.foreground);
3152
3153       ((subclass(DisplayDriver))class(LFBDisplayDriver)).WriteText(display, surface, x, y, text, len);
3154       oglSurface.writingText = false;
3155       oglSystem.loadingFont = false;
3156
3157       glDisable(GL_TEXTURE_2D);
3158
3159       //glTranslated(0.375, 0.375, 0.0);
3160    }
3161
3162    void TextFont(Display display, Surface surface, Font font)
3163    {
3164       ((subclass(DisplayDriver))class(LFBDisplayDriver)).TextFont(display, surface, font);
3165    }
3166
3167    void TextOpacity(Display display, Surface surface, bool opaque)
3168    {
3169       OGLSurface oglSurface = surface.driverData;
3170       oglSurface.opaqueText = opaque;
3171    }
3172
3173    void TextExtent(Display display, Surface surface, const char * text, int len, int * width, int * height)
3174    {
3175       OGLSurface oglSurface = surface.driverData;
3176       OGLSystem oglSystem = display.displaySystem.driverData;
3177       oglSystem.loadingFont = true;
3178       FontExtent(display.displaySystem, oglSurface.font, text, len, width, height);
3179       oglSystem.loadingFont = false;
3180    }
3181
3182    void DrawingChar(Display display, Surface surface, char character)
3183    {
3184
3185    }
3186
3187    void LineStipple(Display display, Surface surface, uint32 stipple)
3188    {
3189       //Logf("Stipple\n");
3190
3191       if(stipple)
3192       {
3193 #if defined(_GLES)
3194          stippleEnabled = true;
3195          glesLineStipple(1, (uint16)stipple);
3196 #else
3197          glLineStipple(1, (uint16)stipple);
3198          glEnable(GL_LINE_STIPPLE);
3199 #endif
3200       }
3201       else
3202       {
3203 #if defined(_GLES)
3204          stippleEnabled = false;
3205          glMatrixMode(GL_TEXTURE);
3206          glLoadIdentity();
3207          glMatrixMode(GL_PROJECTION);
3208          glDisable(GL_TEXTURE_2D);
3209 #else
3210          glDisable(GL_LINE_STIPPLE);
3211 #endif
3212       }
3213    }
3214 #if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
3215    void SetRenderState(Display display, RenderState state, uint value)
3216    {
3217       OGLDisplay oglDisplay = display.driverData;
3218       //Logf("RenderState\n");
3219
3220       switch(state)
3221       {
3222          case antiAlias:
3223             if(value)
3224                glEnable(GL_MULTISAMPLE_ARB);
3225             else
3226                glDisable(GL_MULTISAMPLE_ARB);
3227             break;
3228          case fillMode:
3229 #if !defined(_GLES)
3230             glPolygonMode(GL_FRONT_AND_BACK, ((FillModeValue)value == solid) ? GL_FILL : GL_LINE);
3231 #endif
3232             break;
3233          case depthTest:
3234             if(value) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
3235             break;
3236          case depthWrite:
3237             if(value) glDepthMask((byte)bool::true); else glDepthMask((byte)bool::false);
3238             oglDisplay.depthWrite = (bool)value;
3239             break;
3240          case fogColor:
3241          {
3242             float color[4] = { ((Color)value).r/255.0f, ((Color)value).g/255.0f, ((Color)value).b/255.0f, 1.0f };
3243             glFogfv(GL_FOG_COLOR, (float *)&color);
3244             break;
3245          }
3246          case fogDensity:
3247             glFogf(GL_FOG_DENSITY, (float)(RenderStateFloat { ui = value }.f * nearPlane));
3248             break;
3249          case blend:
3250             if(value) glEnable(GL_BLEND); else glDisable(GL_BLEND);
3251             break;
3252          case ambient:
3253          {
3254             float ambient[4] = { ((Color)value).r/255.0f, ((Color)value).g/255.0f, ((Color)value).b/255.0f, 1.0f };
3255             glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
3256             break;
3257          }
3258          case alphaWrite:
3259          {
3260             if(value) glColorMask(1,1,1,1); else glColorMask(1,1,1,0);
3261             break;
3262          }
3263          case vSync:
3264          {
3265 #if defined(__WIN32__)
3266             wglSwapIntervalEXT(value ? 1 : 0);
3267 #endif
3268             break;
3269          }
3270       }
3271    }
3272
3273    void SetLight(Display display, int id, Light light)
3274    {
3275       //Logf("SetLight\n");
3276
3277       if(light != null)
3278       {
3279          Object lightObject = light.lightObject;
3280          float position[4] = { 0, 0, 0, 0 };
3281          float color[4] = { 0, 0, 0, 1 };
3282
3283          glEnable(GL_LIGHT0 + id);
3284          /*
3285          glLightfv(GL_LIGHT0 + id, GL_DIFFUSE, (float *)&light.diffuse);
3286          glLightfv(GL_LIGHT0 + id, GL_AMBIENT, (float *)&light.ambient);
3287          glLightfv(GL_LIGHT0 + id, GL_SPECULAR,(float *)&light.specular);
3288          */
3289
3290          if(!light.multiplier) light.multiplier = 1.0f;
3291
3292          color[0] = light.diffuse.r * light.multiplier;
3293          color[1] = light.diffuse.g * light.multiplier;
3294          color[2] = light.diffuse.b * light.multiplier;
3295          glLightfv(GL_LIGHT0 + id, GL_DIFFUSE, color);
3296
3297          color[0] = light.ambient.r * light.multiplier;
3298          color[1] = light.ambient.g * light.multiplier;
3299          color[2] = light.ambient.b * light.multiplier;
3300          glLightfv(GL_LIGHT0 + id, GL_AMBIENT, color);
3301          color[0] = light.specular.r * light.multiplier;
3302          color[1] = light.specular.g * light.multiplier;
3303          color[2] = light.specular.b * light.multiplier;
3304          glLightfv(GL_LIGHT0 + id, GL_SPECULAR,color);
3305
3306          if(lightObject)
3307          {
3308             Vector3D positionVector;
3309             if(light.flags.spot)
3310             {
3311                if(lightObject.flags.root || !lightObject.parent)
3312                {
3313                   positionVector = lightObject.transform.position;
3314                   positionVector.Subtract(positionVector, display.display3D.camera.cPosition);
3315                }
3316                else
3317                {
3318                   positionVector.MultMatrix(lightObject.transform.position, lightObject.parent.matrix);
3319                   if(display.display3D.camera)
3320                      positionVector.Subtract(positionVector, display.display3D.camera.cPosition);
3321                }
3322                position[3] = 1;
3323             }
3324             else
3325             {
3326                if(!light.direction.x && !light.direction.y && !light.direction.z)
3327                {
3328                   Vector3Df vector { 0,0,-1 };
3329                   Matrix mat;
3330                   mat.RotationQuaternion(light.orientation);
3331                   positionVector.MultMatrixf(vector, mat);
3332                }
3333                else
3334                {
3335                   positionVector = light.direction;
3336                   position[3] = 1;
3337                }
3338             }
3339
3340             position[0] = (float)positionVector.x;
3341             position[1] = (float)positionVector.y;
3342             position[2] = (float)positionVector.z;
3343
3344             glLightfv(GL_LIGHT0 + id, GL_POSITION, position);
3345
3346             /*
3347             // Display Light Position
3348             glDisable(GL_LIGHTING);
3349             glDisable(GL_DEPTH_TEST);
3350             glColor3f(1,1,1);
3351             glPointSize(10);
3352             glBegin(GL_POINTS);
3353             glVertex3fv(position);
3354             glEnd();
3355             glEnable(GL_DEPTH_TEST);
3356             glEnable(GL_LIGHTING);
3357
3358
3359             // Display Target
3360             if(lightObject.flags.root || !lightObject.parent)
3361             {
3362                positionVector = light.target.transform.position;
3363                positionVector.Subtract(positionVector, display.camera.cPosition);
3364             }
3365             else
3366             {
3367                positionVector.MultMatrix(light.target.transform.position,
3368                   lightObject.light.target.parent.matrix);
3369                positionVector.Subtract(positionVector, display.camera.cPosition);
3370             }
3371
3372             position[0] = positionVector.x;
3373             position[1] = positionVector.y;
3374             position[2] = positionVector.z;
3375
3376             glDisable(GL_LIGHTING);
3377             glDisable(GL_DEPTH_TEST);
3378             glColor3f(1,1,0);
3379             glPointSize(10);
3380             glBegin(GL_POINTS);
3381             glVertex3fv(position);
3382             glEnd();
3383             glEnable(GL_DEPTH_TEST);
3384             glEnable(GL_LIGHTING);
3385             */
3386
3387             if(light.flags.attenuation)
3388             {
3389                glLightf(GL_LIGHT0 + id, GL_CONSTANT_ATTENUATION, light.Kc);
3390                glLightf(GL_LIGHT0 + id, GL_LINEAR_ATTENUATION, light.Kl);
3391                glLightf(GL_LIGHT0 + id, GL_QUADRATIC_ATTENUATION, light.Kq);
3392             }
3393
3394             if(light.flags.spot)
3395             {
3396                float exponent = 0;
3397                #define MAXLIGHT  0.9
3398                float direction[4] = { (float)light.direction.x, (float)light.direction.y, (float)light.direction.z, 1 };
3399                // Figure out exponent out of the hot spot
3400                exponent = (float)(log(MAXLIGHT) / log(cos((light.hotSpot / 2))));
3401
3402                glLightfv(GL_LIGHT0 + id, GL_SPOT_DIRECTION, direction);
3403                glLightf(GL_LIGHT0 + id, GL_SPOT_CUTOFF, (float)(light.fallOff / 2));
3404                glLightf(GL_LIGHT0 + id, GL_SPOT_EXPONENT, exponent);
3405             }
3406          }
3407          else
3408          {
3409
3410             Vector3Df vector { 0,0,-1 };
3411             Vector3Df direction;
3412             Matrix mat;
3413
3414             mat.RotationQuaternion(light.orientation);
3415             direction.MultMatrix(vector, mat);
3416
3417             position[0] = direction.x;
3418             position[1] = direction.y;
3419             position[2] = direction.z;
3420
3421             glLightfv(GL_LIGHT0 + id, GL_POSITION, position);
3422          }
3423       }
3424       else
3425          glDisable(GL_LIGHT0 + id);
3426    }
3427
3428    void SetCamera(Display display, Surface surface, Camera camera)
3429    {
3430       OGLDisplay oglDisplay = display.driverData;
3431       //Logf("SetCamera\n");
3432
3433       if(camera)
3434       {
3435          int left = surface.box.left + surface.offset.x;
3436          int top = surface.box.top  + surface.offset.y;
3437          int right = surface.box.right + surface.offset.x;
3438          int bottom = surface.box.bottom + surface.offset.y;
3439          float origX = surface.offset.x + camera.origin.x;
3440          float origY = surface.offset.y + camera.origin.y;
3441          int x = left;
3442          int y = display.height - bottom - 1;
3443          int w = right - left + 1;
3444          int h = bottom - top + 1;
3445
3446          // *** ViewPort ***
3447          glViewport(x, y, w, h);
3448
3449          // *** Projection Matrix ***
3450          if(!display.display3D.camera)
3451             glPushMatrix();
3452          else
3453             glMatrixMode(GL_PROJECTION);
3454          if(display.display3D.collectingHits)
3455          {
3456             float pickX = display.display3D.pickX + surface.offset.x;
3457             float pickY = display.height - (display.display3D.pickY + surface.offset.y) - 1;
3458             Matrix pickMatrix
3459             {
3460                {
3461                   w / display.display3D.pickWidth, 0, 0, 0,
3462                   0, h / display.display3D.pickHeight, 0, 0,
3463                   0, 0, 1, 0,
3464                   (w + 2.0f * (x - pickX)) / display.display3D.pickWidth,
3465                   (h + 2.0f * (y - pickY)) / display.display3D.pickHeight, 0, 1
3466                }
3467             };
3468             glLoadMatrixd(pickMatrix.array);
3469          }
3470          else
3471             glLoadIdentity();
3472          glFrustum(
3473             (left   - origX) * camera.zMin / camera.focalX,
3474             (right  - origX) * camera.zMin / camera.focalX,
3475             (bottom - origY) * camera.zMin / camera.focalY,
3476             (top    - origY) * camera.zMin / camera.focalY,
3477             camera.zMin, camera.zMax);
3478
3479          glDisable(GL_BLEND);
3480
3481          // *** Z Inverted Identity Matrix ***
3482          glMatrixMode(GL_MODELVIEW);
3483          if(!display.display3D.camera)
3484             glPushMatrix();
3485
3486          glLoadIdentity();
3487
3488          glScaled(1.0/nearPlane, 1.0/nearPlane, -1.0/nearPlane);
3489
3490          // *** View Matrix ***
3491          glMultMatrixd(camera.viewMatrix.array);
3492
3493          // *** Lights ***
3494          // ...
3495
3496          glEnable(GL_DEPTH_TEST);
3497          glEnable(GL_LIGHTING);
3498          glShadeModel(GL_SMOOTH);
3499          glDepthMask((byte)bool::true);
3500          oglDisplay.depthWrite = true;
3501
3502          glEnable(GL_MULTISAMPLE_ARB);
3503       }
3504       else if(display.display3D.camera)
3505       {
3506          oglDisplay.depthWrite = false;
3507          glViewport(0,0,display.width,display.height);
3508
3509          glDisable(GL_CULL_FACE);
3510          glDisable(GL_DEPTH_TEST);
3511          glDisable(GL_LIGHTING);
3512          glDisable(GL_FOG);
3513          glDisable(GL_TEXTURE_2D);
3514          glShadeModel(GL_FLAT);
3515          glEnable(GL_BLEND);
3516          glDisable(GL_MULTISAMPLE_ARB);
3517
3518          // *** Restore 2D MODELVIEW Matrix ***
3519          glPopMatrix();
3520
3521          // *** Restore 2D PROJECTION Matrix ***
3522          glMatrixMode(GL_PROJECTION);
3523          glPopMatrix();
3524       }
3525
3526       GLBindBuffer(GL_ARRAY_BUFFER_ARB, 0);
3527    }
3528
3529    void ApplyMaterial(Display display, Material material, Mesh mesh)
3530    {
3531       //Logf("ApplyMaterial\n");
3532
3533       // Basic Properties
3534       if(material.flags.doubleSided)
3535       {
3536          glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, !material.flags.singleSideLight);
3537          glDisable(GL_CULL_FACE);
3538       }
3539       else
3540       {
3541          glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, bool::false);
3542          glEnable(GL_CULL_FACE);
3543       }
3544
3545       // Fog
3546       if(material.flags.noFog)
3547          glDisable(GL_FOG);
3548       else
3549          glEnable(GL_FOG);
3550
3551       // Maps
3552       if(material.baseMap && (mesh.texCoords || mesh.flags.texCoords1))
3553       {
3554          Bitmap map = material.baseMap;
3555          glEnable(GL_TEXTURE_2D);
3556          glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)map.driverData);
3557
3558          glMatrixMode(GL_TEXTURE);
3559          glLoadIdentity();
3560          if(material.uScale && material.vScale)
3561             glScalef(material.uScale, material.vScale, 1);
3562          glMatrixMode(GL_MODELVIEW);
3563
3564          if(material.flags.tile)
3565          {
3566             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
3567             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
3568          }
3569          else
3570          {
3571             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
3572             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
3573          }
3574       }
3575       else
3576          glDisable(GL_TEXTURE_2D);
3577
3578       if(mesh.flags.colors)
3579       {
3580          glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
3581          glEnable(GL_COLOR_MATERIAL);
3582       }
3583       else
3584       {
3585          glDisable(GL_COLOR_MATERIAL);
3586          {
3587             float color[4] = { material.diffuse.r, material.diffuse.g, material.diffuse.b, material.opacity };
3588             glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color);
3589          }
3590          {
3591             float color[4] = { material.ambient.r, material.ambient.g, material.ambient.b, 0 };
3592             glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color);
3593          }
3594       }
3595       {
3596          float color[4] = { material.specular.r, material.specular.g, material.specular.b, 0 };
3597          glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, color);
3598       }
3599       {
3600          float color[4] = { material.emissive.r, material.emissive.g, material.emissive.b, 0 };
3601          glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, color);
3602       }
3603
3604       glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &material.power);
3605    }
3606
3607    void FreeMesh(DisplaySystem displaySystem, Mesh mesh)
3608    {
3609       OGLMesh oglMesh = mesh.data;
3610       if(oglMesh)
3611       {
3612          if(!mesh.flags.vertices)
3613          {
3614             if(oglMesh.vertices)
3615             {
3616                GLDeleteBuffers(1, &oglMesh.vertices);
3617                oglMesh.vertices = 0;
3618             }
3619             delete mesh.vertices;
3620          }
3621          if(!mesh.flags.normals)
3622          {
3623             if(oglMesh.normals)
3624             {
3625                GLDeleteBuffers(1, &oglMesh.normals);
3626                oglMesh.normals = 0;
3627             }
3628             delete mesh.normals;
3629          }
3630          if(!mesh.flags.texCoords1)
3631          {
3632             if(oglMesh.texCoords)
3633             {
3634                GLDeleteBuffers(1, &oglMesh.texCoords);
3635                oglMesh.texCoords = 0;
3636             }
3637             delete mesh.texCoords;
3638          }
3639          if(!mesh.flags.texCoords2)
3640          {
3641             if(oglMesh.texCoords2)
3642             {
3643                GLDeleteBuffers(1, &oglMesh.texCoords2);
3644                oglMesh.texCoords2 = 0;
3645             }
3646             /*
3647             delete mesh.texCoords2;
3648             */
3649          }
3650          if(!mesh.flags.colors)
3651          {
3652             if(oglMesh.colors)
3653             {
3654                GLDeleteBuffers(1, &oglMesh.colors);
3655                oglMesh.colors = 0;
3656             }
3657          }
3658          if(!mesh.flags)
3659          {
3660             delete oglMesh;
3661             mesh.data = null;
3662          }
3663       }
3664    }
3665
3666    bool AllocateMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags, int nVertices)
3667    {
3668       bool result = false;
3669
3670       if(!mesh.data)
3671          mesh.data = OGLMesh { };
3672       if(mesh.data)
3673       {
3674          OGLMesh oglMesh = mesh.data;
3675          if(mesh.nVertices == nVertices)
3676          {
3677             // Same number of vertices, adding features (Leaves the other features pointers alone)
3678             if(mesh.flags != flags)
3679             {
3680                if(!mesh.flags.vertices && flags.vertices)
3681                {
3682                   if(flags.doubleVertices)
3683                   {
3684                      mesh.vertices = (Vector3Df *)new Vector3D[nVertices];
3685                   }
3686                   else
3687                      mesh.vertices = new Vector3Df[nVertices];
3688                   if(!oglMesh.vertices)
3689                      GLGenBuffers(1, &oglMesh.vertices);
3690                }
3691                if(!mesh.flags.normals && flags.normals)
3692                {
3693                   if(flags.doubleNormals)
3694                   {
3695                      mesh.normals = (Vector3Df *)new Vector3D[nVertices];
3696                   }
3697                   else
3698                      mesh.normals = new Vector3Df[nVertices];
3699                   if(!oglMesh.normals)
3700                      GLGenBuffers( 1, &oglMesh.normals);
3701                }
3702                if(!mesh.flags.texCoords1 && flags.texCoords1)
3703                {
3704                   mesh.texCoords = new Pointf[nVertices];
3705                   if(!oglMesh.texCoords)
3706                      GLGenBuffers( 1, &oglMesh.texCoords);
3707                }
3708                if(!mesh.flags.colors && flags.colors)
3709                {
3710                   mesh.colors = new ColorRGBAf[nVertices];
3711                   if(!oglMesh.colors)
3712                      GLGenBuffers( 1, &oglMesh.colors);
3713                }
3714             }
3715          }
3716          else
3717          {
3718             // New number of vertices, reallocate all current and new features
3719             flags |= mesh.flags;
3720             if(flags.vertices)
3721             {
3722                if(flags.doubleVertices)
3723                {
3724                   mesh.vertices = (Vector3Df *)renew mesh.vertices Vector3D[nVertices];
3725                }
3726                else
3727                   mesh.vertices = renew mesh.vertices Vector3Df[nVertices];
3728                if(!oglMesh.vertices)
3729                   GLGenBuffers(1, &oglMesh.vertices);
3730             }
3731             if(flags.normals)
3732             {
3733                if(flags.doubleNormals)
3734                {
3735                   mesh.normals = (Vector3Df *)renew mesh.normals Vector3D[nVertices];
3736                }
3737                else
3738                   mesh.normals = renew mesh.normals Vector3Df[nVertices];
3739                if(!oglMesh.normals)
3740                   GLGenBuffers( 1, &oglMesh.normals);
3741             }
3742             if(flags.texCoords1)
3743             {
3744                mesh.texCoords = renew mesh.texCoords Pointf[nVertices];
3745                if(!oglMesh.texCoords)
3746                   GLGenBuffers( 1, &oglMesh.texCoords);
3747             }
3748             if(flags.colors)
3749             {
3750                mesh.colors = renew mesh.colors ColorRGBAf[nVertices];
3751                if(!oglMesh.colors)
3752                   GLGenBuffers( 1, &oglMesh.colors);
3753             }
3754          }
3755          result = true;
3756       }
3757       return result;
3758    }
3759
3760    void UnlockMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags)
3761    {
3762       OGLMesh oglMesh = mesh.data;
3763       if(!flags) flags = mesh.flags;
3764
3765       if(vboAvailable)
3766       {
3767          if(flags.vertices && oglMesh.vertices)
3768          {
3769             GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.vertices);
3770             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 );
3771          }
3772
3773          if(flags.normals && oglMesh.normals)
3774          {
3775             GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.normals);
3776             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 );
3777          }
3778
3779          if(flags.texCoords1 && oglMesh.texCoords)
3780          {
3781             GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.texCoords);
3782             GLBufferData( GL_FLOAT, GL_ARRAY_BUFFER_ARB, mesh.nVertices * sizeof(Pointf), mesh.texCoords, GL_STATIC_DRAW_ARB );
3783          }
3784
3785          if(flags.colors && oglMesh.colors)
3786          {
3787             GLBindBuffer( GL_ARRAY_BUFFER_ARB, oglMesh.colors);
3788             GLBufferData( GL_FLOAT, GL_ARRAY_BUFFER_ARB, mesh.nVertices * sizeof(ColorRGBAf), mesh.colors, GL_STATIC_DRAW_ARB );
3789          }
3790
3791          GLBindBuffer( GL_ARRAY_BUFFER_ARB, 0);
3792       }
3793    }
3794
3795    bool LockMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags)
3796    {
3797       bool result = true;
3798
3799         return result;
3800    }
3801
3802    void FreeIndices(DisplaySystem displaySystem, OGLIndices oglIndices)
3803    {
3804       if(oglIndices)
3805       {
3806          if(oglIndices.buffer)
3807             GLDeleteBuffers(1, &oglIndices.buffer);
3808          delete oglIndices.indices;
3809          delete oglIndices;
3810       }
3811    }
3812
3813    void * AllocateIndices(DisplaySystem displaySystem, int nIndices, bool indices32bit)
3814    {
3815       OGLIndices oglIndices = OGLIndices { };
3816       if(oglIndices)
3817       {
3818          oglIndices.indices = (void *)(indices32bit ? new uint32[nIndices] : new uint16[nIndices]);
3819          GLGenBuffers( 1, &oglIndices.buffer);
3820          oglIndices.nIndices = nIndices;
3821       }
3822       return oglIndices;
3823    }
3824
3825    void UnlockIndices(DisplaySystem displaySystem, OGLIndices oglIndices, bool indices32bit, int nIndices)
3826    {
3827       if(vboAvailable)
3828       {
3829          GLBindBuffer( GL_ELEMENT_ARRAY_BUFFER_ARB, oglIndices.buffer);
3830          GLBufferData( indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, GL_ELEMENT_ARRAY_BUFFER_ARB, nIndices * (indices32bit ? sizeof(uint32) : sizeof(uint16)),
3831             oglIndices.indices, GL_STATIC_DRAW_ARB);
3832          GLBindBuffer( GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
3833       }
3834    }
3835
3836    uint16 * LockIndices(DisplaySystem displaySystem, OGLIndices oglIndices)
3837    {
3838
3839       return oglIndices.indices;
3840    }
3841
3842    void SelectMesh(Display display, Mesh mesh)
3843    {
3844       //Logf("SelectMesh\n");
3845
3846 #if !defined( __ANDROID__) && !defined(__APPLE__)
3847
3848 #if defined(__WIN32__)
3849       if(glUnlockArraysEXT)
3850 #endif
3851          if(!vboAvailable && display.display3D.mesh)
3852             glUnlockArraysEXT();
3853
3854 #endif
3855       if(mesh)
3856       {
3857          OGLMesh oglMesh = mesh.data;
3858
3859          // *** Vertex Stream ***
3860          glEnableClientState(GL_VERTEX_ARRAY);
3861          if(!display.display3D.collectingHits && oglMesh)
3862          {
3863             GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.vertices );
3864             if(mesh.flags.doubleVertices)
3865                glVertexPointerd(3, 0, (double *)(vboAvailable ? null : mesh.vertices), mesh.nVertices);
3866             else
3867                glVertexPointer(3, GL_FLOAT, 0, vboAvailable ? null : mesh.vertices);
3868
3869             // *** Normals Stream ***
3870             if(mesh.normals || mesh.flags.normals)
3871             {
3872                glEnableClientState(GL_NORMAL_ARRAY);
3873                GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.normals);
3874                glNormalPointer(/*mesh.flags.doubleNormals ? GL_DOUBLE : */GL_FLOAT, 0, vboAvailable ? null : mesh.normals);
3875             }
3876             else
3877                glDisableClientState(GL_NORMAL_ARRAY);
3878
3879             // *** Texture Coordinates Stream ***
3880             if(mesh.texCoords || mesh.flags.texCoords1)
3881             {
3882                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
3883                GLBindBuffer( GL_ARRAY_BUFFER_ARB, oglMesh.texCoords);
3884                glTexCoordPointer(2, GL_FLOAT, 0, vboAvailable ? null : mesh.texCoords);
3885             }
3886             else
3887                glDisableClientState(GL_TEXTURE_COORD_ARRAY);
3888
3889             // *** Color Stream ***
3890             if(mesh.colors || mesh.flags.colors)
3891             {
3892                glEnableClientState(GL_COLOR_ARRAY);
3893                GLBindBuffer( GL_ARRAY_BUFFER_ARB, oglMesh.colors);
3894                glColorPointer(4, GL_FLOAT, 0, vboAvailable ? null : mesh.colors);
3895             }
3896             else
3897                glDisableClientState(GL_COLOR_ARRAY);
3898
3899          }
3900          else
3901          {
3902             GLBindBuffer( GL_ARRAY_BUFFER_ARB, 0);
3903             if(mesh.flags.doubleVertices)
3904                glVertexPointerd(3, 0, (double *)mesh.vertices, mesh.nVertices);
3905             else
3906                glVertexPointer(3, GL_FLOAT, 0, mesh.vertices);
3907             if((mesh.normals || mesh.flags.normals) && !display.display3D.collectingHits)
3908             {
3909                glEnableClientState(GL_NORMAL_ARRAY);
3910                glNormalPointer(/*mesh.flags.doubleNormals ? GL_DOUBLE : */GL_FLOAT, 0, mesh.normals);
3911             }
3912             else
3913                glDisableClientState(GL_NORMAL_ARRAY);
3914             if((mesh.texCoords || mesh.flags.texCoords1) && !display.display3D.collectingHits)
3915             {
3916                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
3917                glTexCoordPointer(2, GL_FLOAT, 0, mesh.texCoords);
3918             }
3919             else
3920                glDisableClientState(GL_TEXTURE_COORD_ARRAY);
3921             if((mesh.colors || mesh.flags.colors) && !display.display3D.collectingHits)
3922             {
3923                glEnableClientState(GL_COLOR_ARRAY);
3924                glColorPointer(4, GL_FLOAT, 0, mesh.colors);
3925             }
3926             else
3927                glDisableClientState(GL_COLOR_ARRAY);
3928          }
3929
3930 #if !defined(__ANDROID__) && !defined(__APPLE__)
3931
3932 #if defined(__WIN32__)
3933          if(glLockArraysEXT)
3934 #endif
3935             if(!vboAvailable)
3936                glLockArraysEXT(0, mesh.nVertices);
3937
3938 #endif
3939       }
3940       else
3941          GLBindBuffer(GL_ARRAY_BUFFER_ARB, 0);
3942    }
3943
3944    void DrawPrimitives(Display display, PrimitiveSingle * primitive, Mesh mesh)
3945    {
3946       //Logf("DrawPrimitives\n");
3947
3948       if(primitive->type.vertexRange)
3949          glDrawArrays(primitiveTypes[primitive->type.primitiveType], primitive->first, primitive->nVertices);
3950       else
3951       {
3952          //    *** Hoping the data won't be uploaded at all (Won't really work if another group of the mesh is using the mesh ) ***
3953          // HACK TO SPEED THINGS UP...
3954 #ifndef __ANDROID__
3955          /*GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
3956          if(primitive->nIndices < (mesh.nVertices >> 2) && !primitive->type.indices32bit)
3957          {
3958             int c;
3959             glBegin(primitiveTypes[primitive->type.primitiveType]);
3960             if(primitive->data)
3961             {
3962                OGLIndices oglIndices = primitive->data;
3963                MeshFeatures flags = mesh.flags;
3964                for(c = 0; c<primitive->nIndices; c++)
3965                {
3966                   uint16 index = ((uint16 *) oglIndices.indices)[c];
3967                   if(flags.normals) glNormal3fv((float *)&mesh.normals[index]);
3968                   if(flags.texCoords1) glTexCoord2fv((float *)&mesh.texCoords[index]);
3969                   if(flags.colors) glColor4fv((float *)&mesh.colors[index]);
3970                   glVertex3fv((float *)&mesh.vertices[index]);
3971                }
3972             }
3973             glEnd();
3974          }
3975          else*/
3976 #endif
3977          {
3978             OGLIndices oglIndices = primitive->data;
3979
3980             if(!display.display3D.collectingHits && vboAvailable && oglIndices)
3981             {
3982                GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, oglIndices.buffer);
3983                if(primitive->type.indices32bit)
3984                   glDrawElementsi(primitiveTypes[primitive->type.primitiveType], primitive->nIndices, 0);
3985                else
3986                   glDrawElements(primitiveTypes[primitive->type.primitiveType], primitive->nIndices, GL_UNSIGNED_SHORT, 0);
3987                GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
3988             }
3989             else
3990             {
3991                if(primitive->type.indices32bit)
3992                   glDrawElementsi(primitiveTypes[primitive->type.primitiveType], primitive->nIndices,
3993                      oglIndices ? oglIndices.indices : primitive->indices);
3994                else
3995                   glDrawElements(primitiveTypes[primitive->type.primitiveType], primitive->nIndices,
3996                      GL_UNSIGNED_SHORT, oglIndices ? oglIndices.indices : primitive->indices);
3997             }
3998          }
3999       }
4000    }
4001
4002    void PushMatrix(Display display)
4003    {
4004       glPushMatrix();
4005    }
4006
4007    void PopMatrix(Display display, bool setMatrix)
4008    {
4009       glPopMatrix();
4010    }
4011
4012    void SetTransform(Display display, Matrix transMatrix, bool viewSpace, bool useCamera)
4013    {
4014       Matrix matrix = transMatrix;
4015       Camera camera = useCamera ? display.display3D.camera : null;
4016
4017       if(viewSpace)
4018       {
4019          glLoadIdentity();
4020          glScaled(1.0/nearPlane, 1.0/nearPlane, -1.0/nearPlane);
4021       }
4022       else if(camera)
4023       {
4024          glTranslated(
4025             matrix.m[3][0] - camera.cPosition.x,
4026             matrix.m[3][1] - camera.cPosition.y,
4027             matrix.m[3][2] - camera.cPosition.z);
4028       }
4029       else
4030          glTranslated(
4031             matrix.m[3][0],
4032             matrix.m[3][1],
4033             matrix.m[3][2]);
4034
4035       matrix.m[3][0] = 0;
4036       matrix.m[3][1] = 0;
4037       matrix.m[3][2] = 0;
4038
4039       glMultMatrixd(matrix.array);
4040    }
4041 #endif
4042 }
4043
4044 public void UseSingleGLContext(bool useSingle)
4045 {
4046    useSingleGLContext = useSingle;
4047 }
4048
4049 default dllexport void *
4050 #if defined(__WIN32__)
4051 __attribute__((stdcall))
4052 #endif
4053 IS_GLGetContext(DisplaySystem displaySystem)
4054 {
4055    if(displaySystem)
4056    {
4057 #if defined(__WIN32__)
4058       OGLSystem system = displaySystem.driverData;
4059       return system.glrc;
4060 #elif !defined(__ANDROID__)
4061       OGLSystem system = displaySystem.driverData;
4062       return system.glContext;
4063 #else
4064       return eglContext;
4065 #endif
4066    }
4067    return null;
4068 }
4069
4070 #endif