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