ecere/OpenGL ES: Line stipple support for 2D lines & rectangles
[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__)
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__)
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 void (APIENTRY * glBindBufferARB) (GLenum target, GLuint buffer);
960 void (APIENTRY * glGenBuffersARB) (GLsizei n, GLuint *buffers);
961 void (APIENTRY * glDeleteBuffersARB) (GLsizei n, const GLuint *buffers);
962 void (APIENTRY * glBufferDataARB) (GLenum target, int size, const GLvoid *data, GLenum usage);
963
964 #endif
965
966 static int currentVertexBuffer;
967
968 bool GLSelectVBO(uint vbo)
969 {
970    if(currentVertexBuffer != vbo)
971    {
972       GLBindBuffer(GL_ARRAY_BUFFER, vbo);
973       currentVertexBuffer = vbo;
974       return true;
975    }
976    return false;
977 }
978
979 void GLBindBuffer(int target, uint buffer)
980 {
981 #ifdef __ANDROID__
982    glBindBuffer(target, buffer);
983 #else
984    glBindBufferARB(target, buffer);
985 #endif
986 }
987
988 static int displayWidth, displayHeight;
989
990 #define GL_CLAMP_TO_EDGE 0x812F
991
992 static bool useSingleGLContext = false;
993 class OGLDisplay : struct
994 {
995 #if defined(__WIN32__)
996    HDC hdc;
997    HGLRC glrc;
998
999    HBITMAP memBitmap;
1000    HDC memDC;
1001    byte * picture;
1002    uint stride;
1003    void * pBuffer;
1004    /*
1005    int imageBuffers[2];
1006    byte * pboMemory1, * pboMemory2;
1007    */
1008 #else
1009    GLXContext glContext;
1010
1011    Pixmap pixmap;
1012    XShmSegmentInfo shminfo;
1013    XImage * image;
1014    XShmSegmentInfo shminfoShape;
1015    XImage * shapeImage;
1016    byte * picture;
1017    uint stride;
1018    GLXPbuffer pBuffer;
1019    X11Picture windowPicture;
1020    X11Picture pixmapPicture;
1021    Pixmap shapePixmap;
1022    X11Picture shapePicture;
1023 #endif
1024
1025    ColorAlpha * flippingBuffer;
1026    int flipBufH, flipBufW;
1027    bool depthWrite;
1028    int x, y;
1029 };
1030
1031 class OGLSystem : struct
1032 {
1033 #if defined(__WIN32__)
1034    PIXELFORMATDESCRIPTOR pfd;
1035    int format;
1036    HDC hdc;
1037    HGLRC glrc;
1038    HWND hwnd;
1039 #else
1040    XVisualInfo * visualInfo;
1041    GLXContext glContext;
1042    Pixmap dummyPixmap;
1043    GLXPixmap dummyGLXPixmap;
1044 #endif
1045    bool loadingFont;
1046 };
1047
1048 class OGLSurface : struct
1049 {
1050    Font font;
1051    bool opaqueText;
1052    int xOffset;
1053    bool writingText;
1054
1055    float foreground[4], background[4], bitmapMult[4];
1056 } OGLSurface;
1057
1058 class OGLMesh : struct
1059 {
1060    int vertices;
1061    int normals;
1062    int texCoords;
1063    int texCoords2;
1064    int colors;
1065 };
1066
1067 class OGLIndices : struct
1068 {
1069    uint16 * indices;
1070    int buffer;
1071    int nIndices;
1072 };
1073
1074 static int primitiveTypes[RenderPrimitiveType] =
1075 {
1076    GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUADS, GL_QUAD_STRIP, GL_LINE_STRIP
1077 };
1078
1079 int current;
1080 void * previous;
1081
1082 class OpenGLDisplayDriver : DisplayDriver
1083 {
1084    class_property(name) = "OpenGL";
1085
1086    bool LockSystem(DisplaySystem displaySystem)
1087    {
1088       OGLSystem oglSystem = displaySystem.driverData;
1089       if(useSingleGLContext) return true;
1090    #if defined(__WIN32__)
1091       wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1092    #elif defined(__unix__)
1093       //if(previous) return true;
1094       // printf("Making SYSTEM current\n");
1095 /*#if defined(__APPLE__)
1096       //glXMakeCurrent(xGlobalDisplay, displaySystem.window, oglSystem.glContext);
1097 #else*/
1098       #if defined(__ANDROID__)
1099       #else
1100       glXMakeCurrent(xGlobalDisplay, oglSystem.dummyGLXPixmap /*displaySystem.window /-*DefaultRootWindow(xGlobalDisplay)*/, oglSystem.glContext);
1101       #endif
1102 //#endif
1103       //previous = oglSystem.glContext;
1104    #endif
1105       return true;
1106    }
1107
1108    void UnlockSystem(DisplaySystem displaySystem)
1109    {
1110       if(useSingleGLContext) return;
1111    #if defined(__WIN32__)
1112       wglMakeCurrent(null, null);
1113    #elif defined(__unix__)
1114       // printf("Making NULL current\n");
1115       #if defined(__ANDROID__)
1116       #else
1117       glXMakeCurrent(xGlobalDisplay, None, null);
1118       #endif
1119       // previous = null;
1120    #endif
1121    }
1122
1123    bool Lock(Display display)
1124    {
1125       OGLDisplay oglDisplay = display.driverData;
1126       OGLSystem oglSystem = display.displaySystem.driverData;
1127
1128       if(useSingleGLContext) return true;
1129    #if defined(__WIN32__)
1130       wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1131    #elif defined(__unix__)
1132       // if(previous) glXMakeCurrent(xGlobalDisplay, None, null);
1133       // printf("   Making DISPLAY current\n");
1134       #if defined(__ANDROID__)
1135       #else
1136       glXMakeCurrent(xGlobalDisplay, (int)display.window, oglDisplay.glContext);
1137       #endif
1138    #endif
1139       return true;
1140    }
1141
1142    void Unlock(Display display)
1143    {
1144       if(useSingleGLContext) return;
1145       //printf("   Making NULL current\n");
1146       //glXMakeCurrent(xGlobalDisplay, None, null);
1147       // if(previous)
1148          LockSystem(display.displaySystem);
1149    }
1150
1151    void DestroyDisplay(Display display)
1152    {
1153       OGLDisplay oglDisplay = display.driverData;
1154
1155       if(oglDisplay)
1156       {
1157    #if defined(__WIN32__)
1158          wglMakeCurrent( null, null );
1159
1160          if(oglDisplay.glrc) 
1161             wglDeleteContext(oglDisplay.glrc);
1162       
1163          if(oglDisplay.hdc && oglDisplay.pBuffer)
1164             wglReleasePbufferDCARB(oglDisplay.pBuffer, oglDisplay.hdc);
1165
1166          if(oglDisplay.pBuffer)
1167             wglDestroyPbufferARB(oglDisplay.pBuffer);
1168
1169          if(oglDisplay.hdc) 
1170             ReleaseDC(display.window, oglDisplay.hdc);
1171
1172          if(oglDisplay.memDC) DeleteDC(oglDisplay.memDC);
1173          if(oglDisplay.memBitmap) DeleteObject(oglDisplay.memBitmap); 
1174
1175    #elif defined(__unix__)
1176       #if defined(__ANDROID__)
1177       #else
1178          if(oglDisplay.shapePixmap)
1179             XFreePixmap(xGlobalDisplay, oglDisplay.shapePixmap);
1180          if(oglDisplay.pixmap)
1181             XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
1182          if(oglDisplay.image)
1183          {
1184             if(oglDisplay.shminfoShape.shmid != -1)
1185             {
1186                XShmDetach(xGlobalDisplay, &oglDisplay.shminfo);
1187                if(oglDisplay.shminfo.shmaddr != (void *)-1)
1188                   shmdt(oglDisplay.shminfo.shmaddr);
1189                shmctl(oglDisplay.shminfo.shmid, IPC_RMID, 0);
1190             }
1191          }
1192          if(oglDisplay.shapeImage)
1193          {
1194             if(oglDisplay.shminfoShape.shmid != -1)
1195             {
1196                XShmDetach(xGlobalDisplay, &oglDisplay.shminfoShape);
1197                if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
1198                   shmdt(oglDisplay.shminfoShape.shmaddr);
1199                shmctl(oglDisplay.shminfoShape.shmid, IPC_RMID, 0);
1200             }                  
1201             XDestroyImage(oglDisplay.shapeImage);
1202             oglDisplay.shapeImage = None;
1203          }
1204
1205          glXMakeCurrent(xGlobalDisplay, None, null);
1206       
1207          if(oglDisplay.glContext) 
1208             glXDestroyContext(xGlobalDisplay, oglDisplay.glContext);
1209       #endif
1210    #endif
1211          delete oglDisplay.flippingBuffer;
1212          delete oglDisplay;
1213          display.driverData = null;
1214       }
1215    }
1216
1217    bool CreateDisplaySystem(DisplaySystem displaySystem)
1218    {
1219       bool result = false;
1220       OGLSystem oglSystem = displaySystem.driverData = OGLSystem { };
1221
1222    #ifdef __WIN32__
1223       oglSystem.hwnd = CreateWindow("static", null, 0,0,0,0,0,null,null,null,null);
1224
1225       oglSystem.hdc = GetDC(oglSystem.hwnd);
1226       if(oglSystem.hdc)
1227       {
1228            
1229          oglSystem.pfd.nSize = (short)sizeof(oglSystem.pfd);
1230          oglSystem.pfd.nVersion = 1;
1231          oglSystem.pfd.dwFlags = PFD_DRAW_TO_WINDOW /*PFD_DRAW_TO_BITMAP*/ | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
1232          oglSystem.pfd.iPixelType = PFD_TYPE_RGBA;
1233          oglSystem.pfd.cColorBits = 24;
1234          oglSystem.pfd.cAlphaBits = 8;
1235          oglSystem.pfd.cDepthBits = 24;
1236          oglSystem.pfd.iLayerType = PFD_MAIN_PLANE;
1237
1238          oglSystem.format = ChoosePixelFormat(oglSystem.hdc, &oglSystem.pfd);
1239          DescribePixelFormat(oglSystem.hdc, oglSystem.format, sizeof(oglSystem.pfd), &oglSystem.pfd);
1240
1241          if(oglSystem.pfd.cColorBits > 8)
1242          {
1243             SetPixelFormat(oglSystem.hdc, oglSystem.format, &oglSystem.pfd);
1244             oglSystem.glrc = wglCreateContext(oglSystem.hdc);
1245             if(oglSystem.glrc)
1246             {
1247                wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1248
1249                  // Get Pointers To The GL Functions
1250                glActiveTextureARB = (void *) wglGetProcAddress("glActiveTextureARB");
1251                glMultiTexCoord2fARB = (void *) wglGetProcAddress("glMultiTexCoord2fARB");
1252                glClientActiveTextureARB = (void *) wglGetProcAddress("glClientActiveTextureARB");
1253                glLockArraysEXT = (void *) wglGetProcAddress("glLockArraysEXT" );
1254                glUnlockArraysEXT = (void *) wglGetProcAddress("glUnlockArraysEXT");
1255                  glGenBuffersARB = (void *) wglGetProcAddress("glGenBuffersARB");
1256                  glBindBufferARB = (void *) wglGetProcAddress("glBindBufferARB");
1257                  glBufferDataARB = (void *) wglGetProcAddress("glBufferDataARB");
1258                glMapBufferARB  = (void *) wglGetProcAddress("glMapBufferARB");
1259                glUnmapBufferARB  = (void *) wglGetProcAddress("glUnmapBufferARB");
1260                  glDeleteBuffersARB = (void *) wglGetProcAddress("glDeleteBuffersARB");
1261                glBlendFuncSeparate = (void *) wglGetProcAddress("glBlendFuncSeparate");
1262
1263                wglChoosePixelFormatARB = (void *) wglGetProcAddress("wglChoosePixelFormatARB");
1264                wglGetExtensionsStringARB = (void *)wglGetProcAddress("wglGetExtensionsStringARB");
1265                wglCreatePbufferARB = (void *)wglGetProcAddress("wglCreatePbufferARB");
1266                wglGetPbufferDCARB = (void *)wglGetProcAddress("wglGetPbufferDCARB");
1267                wglQueryPbufferARB = (void *)wglGetProcAddress("wglQueryPbufferARB");
1268                wglDestroyPbufferARB = (void *)wglGetProcAddress("wglDestroyPbufferARB");
1269                wglReleasePbufferDCARB = (void *)wglGetProcAddress("wglReleasePbufferDCARB");
1270                wglBindTexImageARB = (void *)wglGetProcAddress("wglBindTexImageARB");
1271                wglReleaseTexImageARB = (void *)wglGetProcAddress("wglReleaseTexImageARB");
1272
1273                wglSwapIntervalEXT = (void *)wglGetProcAddress("wglSwapIntervalEXT");
1274
1275                // eSystem_LoggingMode(LOG_MSGBOX, null);
1276
1277                if(wglChoosePixelFormatARB)
1278                {
1279                     int pixelFormat;
1280                     int valid;
1281                     int numFormats;
1282                     float fAttributes[] = {0,0};
1283                     int iAttributes[] =
1284                   { 
1285                      WGL_DRAW_TO_WINDOW_ARB,GL_TRUE,
1286                             WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
1287                             WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
1288                             WGL_COLOR_BITS_ARB,24,
1289                             WGL_ALPHA_BITS_ARB,8,
1290                             WGL_DEPTH_BITS_ARB,16,
1291                             WGL_STENCIL_BITS_ARB,0,
1292                             WGL_DOUBLE_BUFFER_ARB,GL_TRUE,
1293                             WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
1294                             WGL_SAMPLES_ARB, 4,                                         // Check For 4x Multisampling
1295                             0,0
1296                   };
1297
1298                   //Log("Found wglChoosePixelFormatARB\n");
1299
1300                     valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1301                     if(!valid || !numFormats)
1302                     {
1303                      //Log("Can't find 4x multi sampling\n");
1304                        iAttributes[19] = 2;
1305                        valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1306                      if(!valid || !numFormats)
1307                      {
1308                         // Log("Can't find 2x multi sampling\n");
1309                         iAttributes[16] = 0;
1310                         iAttributes[17] = 0;
1311                         valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1312                      }
1313                     }
1314                   if(valid && numFormats)
1315                   {
1316                      oglSystem.format = pixelFormat;
1317                      wglMakeCurrent(null, null);
1318                      wglDeleteContext(oglSystem.glrc);
1319
1320                      // *** DescribePixelFormat does not support WGL pixel formats! ***
1321                      //DescribePixelFormat(oglSystem.hdc, oglSystem.format, sizeof(oglSystem.pfd), &oglSystem.pfd);
1322                      SetPixelFormat(oglSystem.hdc, oglSystem.format, &oglSystem.pfd);
1323                      //Log("Successfully set pixel format\n");
1324
1325                      oglSystem.glrc = wglCreateContext(oglSystem.hdc);
1326                      wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1327                   }
1328                }
1329                /*else
1330                   eSystem_Logf("Can't find wglChoosePixelFormatARB\n");*/
1331
1332                result = true;
1333
1334                wglMakeCurrent(null, null);
1335
1336                //eSystem_DumpErrors(true);
1337             }
1338          }
1339       }
1340    #elif defined(__unix__)
1341       #if defined(__ANDROID__)
1342          egl_init_display(guiApp.desktop.windowHandle);
1343          result = true;
1344       #else
1345       int attrList[] = 
1346       {
1347    #ifndef ECERE_MINIGLX
1348          GLX_USE_GL, GLX_DEPTH_SIZE, 1,
1349    #endif
1350          GLX_RGBA, 
1351          GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
1352          GLX_DOUBLEBUFFER, 
1353          None
1354       };
1355       oglSystem.visualInfo = glXChooseVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrList);
1356       if(oglSystem.visualInfo)
1357       {
1358          //printf("glXChooseVisual returnded a visual info\n");
1359          oglSystem.dummyPixmap = XCreatePixmap(xGlobalDisplay, (uint)displaySystem.window, 1, 1, oglSystem.visualInfo->depth);
1360          oglSystem.dummyGLXPixmap = glXCreateGLXPixmap(xGlobalDisplay, oglSystem.visualInfo, oglSystem.dummyPixmap);
1361          
1362          oglSystem.glContext = glXCreateContext(xGlobalDisplay, oglSystem.visualInfo, null, True);
1363          // printf("Creating system Context (%x)!\n", oglSystem.glContext);
1364          if(oglSystem.glContext)
1365          {
1366             //printf("Got a Context\n");
1367             glXMakeCurrent(xGlobalDisplay, oglSystem.dummyGLXPixmap /*displaySystem.window /-*DefaultRootWindow(xGlobalDisplay)*/, oglSystem.glContext);
1368
1369             // Setup Extensions
1370
1371             glXMakeCurrent(xGlobalDisplay, None, null);
1372
1373             result = true;
1374          }
1375       }
1376       #endif
1377    #endif
1378
1379       displaySystem.flags.alpha = true;
1380       displaySystem.flags.flipping = true;
1381       displaySystem.pixelFormat = pixelFormat888;
1382       return result;
1383    }
1384
1385    void DestroyDisplaySystem(DisplaySystem displaySystem)
1386    {
1387       OGLSystem oglSystem = displaySystem.driverData;
1388
1389    #if defined(__WIN32__)
1390       wglMakeCurrent( null, null );
1391
1392       if(oglSystem.glrc) 
1393          wglDeleteContext(oglSystem.glrc);
1394       
1395       if(oglSystem.hdc) 
1396          ReleaseDC(oglSystem.hwnd, oglSystem.hdc);
1397       DestroyWindow(oglSystem.hwnd);
1398
1399    #elif defined(__unix__)
1400       #if defined(__ANDROID__)
1401          egl_term_display();
1402       #else
1403       if(oglSystem.visualInfo)
1404       {
1405    #ifdef   ECERE_MINIGLX
1406          __miniglx_XFree(oglSystem.visualInfo);
1407    #else
1408          XFree(oglSystem.visualInfo);
1409    #endif
1410       }
1411
1412       if(oglSystem.dummyGLXPixmap)
1413          glXDestroyGLXPixmap(xGlobalDisplay, oglSystem.dummyGLXPixmap);
1414       if(oglSystem.dummyPixmap);
1415          XFreePixmap(xGlobalDisplay, oglSystem.dummyPixmap);
1416       #endif
1417    #endif
1418       delete oglSystem;
1419    }
1420
1421    bool CreateDisplay(Display display)
1422    {
1423       bool result = false;
1424       OGLDisplay oglDisplay = display.driverData;
1425       OGLSystem oglSystem = display.displaySystem.driverData;
1426       if(!oglDisplay)
1427          oglDisplay = display.driverData = OGLDisplay { };
1428       //printf("Inside CreateDisplay\n");
1429
1430 #if defined(__WIN32__) || defined(USEPBUFFER)
1431       if(!display.alphaBlend)
1432 #endif
1433       {
1434    #if defined(__WIN32__)
1435          oglDisplay.hdc = GetDC(display.window);
1436          SetPixelFormat(oglDisplay.hdc, oglSystem.format, &oglSystem.pfd);
1437          if((oglDisplay.glrc = wglCreateContext(oglDisplay.hdc)))
1438          {
1439             wglShareLists(oglSystem.glrc, oglDisplay.glrc);
1440             wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1441             result = true;
1442          }
1443          else
1444             ReleaseDC(display.window, oglDisplay.hdc);
1445    #elif defined(__unix__)
1446       #if defined(__ANDROID__)
1447       #else
1448          XVisualInfo * visualInfo = null;
1449          /*
1450          int attrib[] =
1451          {
1452             GLX_RENDER_TYPE, GLX_RGBA_BIT,
1453             GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
1454             GLX_RED_SIZE, 1,
1455             GLX_GREEN_SIZE, 1,
1456             GLX_BLUE_SIZE, 1,
1457             GLX_DOUBLEBUFFER, True,
1458             GLX_DEPTH_SIZE, 24,
1459             None
1460          };
1461          */
1462          //visualInfo = glXChooseVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib);
1463          visualInfo = ((XWindowData)display.windowDriverData).visual;
1464
1465          /*
1466          GLXFBConfig *fbconfigs, fbconfig;
1467          int numfbconfigs;
1468          fbconfigs = glXChooseFBConfig(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib, &numfbconfigs);
1469          if(fbconfigs)
1470          {
1471             int i;
1472             for (i = 0; i < numfbconfigs; i++)
1473             {
1474                XRenderPictFormat * format;
1475                visualInfo = glXGetVisualFromFBConfig(xGlobalDisplay, fbconfigs[i]);
1476                if (!visualInfo) continue;
1477                format = XRenderFindVisualFormat(xGlobalDisplay, visualInfo->visual);
1478                if (!format) continue;
1479
1480                if(format->direct.alphaMask > 0)
1481                {
1482                   fbconfig = fbconfigs[i];
1483                   break;
1484                }
1485                //XFree(visualInfo);
1486             }
1487
1488             if (i == numfbconfigs)
1489             {
1490                fbconfig = fbconfigs[0];
1491                visualInfo = glXGetVisualFromFBConfig(xGlobalDisplay, fbconfig);
1492             }
1493             XFree(fbconfigs);
1494          }
1495          */
1496          if(visualInfo)
1497          {
1498             //printf("visualInfo is not null\n");
1499             // printf("Creating Display Context, sharing with %x!\n", oglSystem.glContext);
1500             oglDisplay.glContext = glXCreateContext(xGlobalDisplay, visualInfo, oglSystem.glContext, True);
1501             //XFree(visualInfo);
1502          }
1503
1504          // oglDisplay.glContext = glXCreateContext(xGlobalDisplay, oglSystem.visualInfo, oglSystem.glContext, True);
1505          if(oglDisplay.glContext)
1506          {
1507             //printf("CreateDisplay Got a Context\n");
1508             glXMakeCurrent(xGlobalDisplay, (int)display.window, oglDisplay.glContext);
1509             result = true;
1510          }
1511       #endif
1512    #endif
1513       }
1514 #if defined(__WIN32__) || defined(USEPBUFFER)
1515       else
1516          result = true;
1517 #endif
1518       if(result)
1519       {
1520 #if !defined(__OLDX__)
1521          if(glBlendFuncSeparate)
1522             glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
1523          else
1524 #endif
1525             glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1526          glEnable(GL_BLEND);
1527
1528          glMatrixMode(GL_MODELVIEW);
1529          glScalef(1.0f, 1.0f, -1.0f);
1530          // glTranslatef(0.375f, 0.375f, 0.0f);
1531          // glTranslatef(-0.625f, -0.625f, 0.0f);
1532          glMatrixMode(GL_PROJECTION);
1533          glShadeModel(GL_FLAT);
1534
1535          // glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, true);
1536          glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1537          glFogi(GL_FOG_MODE, GL_EXP);
1538          glFogf(GL_FOG_DENSITY, 0);
1539          glEnable(GL_NORMALIZE);
1540          glDepthFunc(GL_LESS);
1541          glClearDepth(1.0);
1542          glDisable(GL_MULTISAMPLE_ARB);
1543       }
1544       display.ambient = Color { 50,50,50 };
1545
1546    if(!useSingleGLContext)
1547    #if defined(__WIN32__)
1548       wglMakeCurrent(null, null);
1549    #elif defined(__unix__)
1550       #if defined(__ANDROID__)
1551       result = true;
1552       #else
1553       glXMakeCurrent(xGlobalDisplay, None, null);
1554       #endif
1555    #endif
1556
1557       return result;
1558    }
1559
1560    bool DisplaySize(Display display, int width, int height)
1561    {
1562       OGLDisplay oglDisplay = display.driverData;
1563       OGLSystem oglSystem = display.displaySystem.driverData;
1564
1565       bool result = false;
1566
1567       //printf("Inside DisplaySize\n");
1568 #if defined(__WIN32__) || defined(USEPBUFFER)
1569       if(display.alphaBlend)
1570       {
1571 #if defined(__WIN32__)
1572          const int attributes[]=
1573          {
1574             /*WGL_TEXTURE_FORMAT_ARB, WGL_TEXTURE_RGBA_ARB,
1575             WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB, */0
1576          }; 
1577          int pixelFormat = 0;
1578          if(wglChoosePixelFormatARB)
1579          {
1580             int valid;
1581             int numFormats;
1582             float fAttributes[] = {0,0};
1583             int iAttributes[] =
1584             { 
1585                //WGL_DRAW_TO_BITMAP_ARB, GL_TRUE,
1586                WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
1587                     WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
1588                     WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
1589                     WGL_COLOR_BITS_ARB,24,
1590                     WGL_ALPHA_BITS_ARB,8,
1591                     WGL_DEPTH_BITS_ARB,16,
1592                     WGL_STENCIL_BITS_ARB,0,
1593                     WGL_DOUBLE_BUFFER_ARB,GL_FALSE,
1594                     WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
1595                     WGL_SAMPLES_ARB, 4,                                         // Check For 4x Multisampling
1596                     0,0
1597             };
1598             
1599             //Log("Found wglChoosePixelFormatARB\n");
1600
1601             valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1602             if(!valid || !numFormats)
1603             {
1604                //Log("Can't find 4x multi sampling\n");
1605                iAttributes[19] = 2;
1606                valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1607                if(!valid || !numFormats)
1608                {
1609                   // Log("Can't find 2x multi sampling\n");
1610                   iAttributes[16] = 0;
1611                   iAttributes[17] = 0;
1612                   valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1613                   if(!valid || !numFormats)
1614                   {
1615                      int iAttributes[] =
1616                      {
1617                         WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
1618                         //WGL_DRAW_TO_BITMAP_ARB,GL_TRUE,
1619                         WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
1620                         WGL_COLOR_BITS_ARB,24,
1621                         WGL_ALPHA_BITS_ARB,8,
1622                         WGL_DEPTH_BITS_ARB,16,
1623                         0,0
1624                      };
1625                      valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1626                   }
1627                }
1628             }
1629             if(valid && numFormats)
1630             {
1631                wglMakeCurrent(null, null);
1632             }
1633          }  
1634
1635          wglMakeCurrent( null, null );
1636          wglMakeCurrent( oglDisplay.hdc, oglDisplay.glrc );
1637          if(oglDisplay.hdc && oglDisplay.pBuffer)
1638             wglReleasePbufferDCARB(oglDisplay.pBuffer, oglDisplay.hdc);
1639
1640          wglDestroyPbufferARB(oglDisplay.pBuffer);
1641
1642          if(!useSingleGLContext)
1643             wglMakeCurrent( null, null );
1644            
1645          if(oglDisplay.glrc) 
1646             wglDeleteContext(oglDisplay.glrc);
1647
1648          oglDisplay.pBuffer = wglCreatePbufferARB(oglSystem.hdc, pixelFormat, width, height, attributes);
1649          oglDisplay.hdc = wglGetPbufferDCARB(oglDisplay.pBuffer);
1650          if((oglDisplay.glrc = wglCreateContext(oglDisplay.hdc)))
1651          {
1652             BITMAPINFO * info;
1653             HDC hdc = GetDC(display.window);
1654
1655             wglShareLists(oglSystem.glrc, oglDisplay.glrc);
1656             wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1657
1658             //wglQueryPbufferARB(pBuffer, WGL_PBUFFER_WIDTH_ARB, &width);
1659             //wglQueryPbufferARB(pBuffer, WGL_PBUFFER_HEIGHT_ARB, &height); 
1660             
1661             // glDeleteBuffersARB(2, oglDisplay.imageBuffers);
1662
1663             if((info = (BITMAPINFO *)new0 byte[sizeof(BITMAPINFOHEADER)+sizeof(RGBQUAD)*256]))
1664             {
1665                HBITMAP newBitmap;
1666
1667                if(oglDisplay.memDC) DeleteDC(oglDisplay.memDC);
1668                oglDisplay.memDC = CreateCompatibleDC(hdc);
1669                SetMapMode(oglDisplay.memDC, MM_TEXT);
1670                info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1671                info->bmiHeader.biPlanes = 1;
1672                info->bmiHeader.biCompression = BI_RGB;
1673                info->bmiHeader.biBitCount = 32; //(uint16)GetDeviceCaps(hdc, BITSPIXEL);
1674                info->bmiHeader.biWidth = width;
1675                info->bmiHeader.biHeight = height;
1676                newBitmap = CreateDIBSection(hdc, info, DIB_RGB_COLORS, &oglDisplay.picture, null, 0);
1677                if(newBitmap)
1678                {
1679                   SelectObject(oglDisplay.memDC, newBitmap);
1680                   if(oglDisplay.memBitmap) DeleteObject(oglDisplay.memBitmap);
1681                   /*
1682                   {
1683                      PIXELFORMATDESCRIPTOR pfd = { 0 };
1684                      pfd.nSize = (short)sizeof(pfd);
1685                      pfd.nVersion = 1;
1686                      pfd.dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_OPENGL;
1687                      pfd.iPixelType = PFD_TYPE_RGBA;
1688                      pfd.cColorBits = 32;
1689                      //pfd.cAlphaBits = 8;
1690                      pfd.cDepthBits = 24;
1691                      pfd.iLayerType = PFD_MAIN_PLANE;
1692
1693                      oglDisplay.hdc = oglDisplay.memDC;
1694
1695                      pixelFormat = ChoosePixelFormat(oglSystem.hdc, &pfd);
1696                      DescribePixelFormat(oglDisplay.hdc, pixelFormat, sizeof(pfd), &pfd);
1697                      SetPixelFormat(oglDisplay.hdc, pixelFormat, &pfd);
1698
1699                      oglDisplay.glrc = wglCreateContext(oglDisplay.hdc);
1700                      wglShareLists(oglSystem.glrc, oglDisplay.glrc);
1701                      wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1702                   }
1703                   */
1704                   /*
1705                   {
1706                      const int imageSize = width * height * 4;
1707
1708                      glGenBuffersARB(2, oglDisplay.imageBuffers);
1709
1710                      glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
1711                      glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, imageSize, null, GL_STREAM_READ);
1712                      // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
1713                      // glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, imageSize / 2, null, GL_STREAM_READ);
1714                   }
1715                   */
1716                   oglDisplay.memBitmap = newBitmap;
1717                   oglDisplay.stride = width;
1718
1719                   result = true;
1720                }
1721                delete info;
1722             }
1723             ReleaseDC(display.window, hdc);
1724          }
1725 #elif defined(__unix__)
1726       #if defined(__ANDROID__)
1727          result = true;
1728       #else
1729         int attrib[] =
1730         {
1731                 GLX_DOUBLEBUFFER,  True,
1732             GLX_DEPTH_SIZE,    1,
1733                 GLX_RED_SIZE,      8,
1734                 GLX_GREEN_SIZE,    8,
1735                 GLX_BLUE_SIZE,     8,
1736                 GLX_ALPHA_SIZE,    8,
1737                 GLX_STENCIL_SIZE,  1,
1738                 //GLX_DEPTH_SIZE,    24,
1739                 GLX_RENDER_TYPE,   GLX_RGBA_BIT,
1740                 GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
1741                 None
1742         };
1743
1744         int PBattrib[] =
1745         {
1746                 GLX_PBUFFER_WIDTH,   width,
1747                 GLX_PBUFFER_HEIGHT,  height,
1748                 GLX_LARGEST_PBUFFER, False,
1749             None
1750         };
1751
1752         // choose a pixel format that meets our minimum requirements
1753         int count = 0;
1754
1755         GLXFBConfig *config = glXChooseFBConfig(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib, &count);
1756          if(config)
1757          {
1758             if(oglDisplay.pixmap)
1759             {
1760                XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
1761                oglDisplay.pixmap = None;
1762             }
1763             if(oglDisplay.shapePixmap)
1764             {
1765                XFreePixmap(xGlobalDisplay, oglDisplay.shapePixmap);
1766                oglDisplay.shapePixmap = None;
1767             }
1768
1769             // Free Shared Memory Pixmap
1770             if(oglDisplay.image)
1771             {
1772                if(oglDisplay.shminfoShape.shmid != -1)
1773                {
1774                   XShmDetach(xGlobalDisplay, &oglDisplay.shminfo);
1775                   if(oglDisplay.shminfo.shmaddr != (void *)-1)
1776                      shmdt(oglDisplay.shminfo.shmaddr);
1777                   shmctl(oglDisplay.shminfo.shmid, IPC_RMID, 0);
1778                }
1779                XDestroyImage(oglDisplay.image);
1780                oglDisplay.image = None;
1781             }
1782             if(oglDisplay.shapeImage)
1783             {
1784                if(oglDisplay.shminfoShape.shmid != -1)
1785                {
1786                   XShmDetach(xGlobalDisplay, &oglDisplay.shminfoShape);
1787                   if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
1788                      shmdt(oglDisplay.shminfoShape.shmaddr);
1789                   shmctl(oglDisplay.shminfoShape.shmid, IPC_RMID, 0);
1790                }                  
1791                XDestroyImage(oglDisplay.shapeImage);
1792                oglDisplay.shapeImage = None;
1793             }
1794
1795             if(oglDisplay.windowPicture)
1796                XRenderFreePicture(xGlobalDisplay, oglDisplay.windowPicture);
1797             if(oglDisplay.pixmapPicture)
1798                XRenderFreePicture(xGlobalDisplay, oglDisplay.pixmapPicture);
1799
1800             if(oglDisplay.pixmap)
1801                XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
1802
1803             if(oglDisplay.glContext)
1804                   glXDestroyContext(xGlobalDisplay, oglDisplay.glContext);
1805             if(oglDisplay.pBuffer)
1806                glXDestroyPbuffer(xGlobalDisplay, oglDisplay.pBuffer);
1807
1808                 oglDisplay.pBuffer = glXCreatePbuffer(xGlobalDisplay, config[0], PBattrib);
1809             if(oglDisplay.pBuffer)
1810             {
1811                    oglDisplay.glContext = glXCreateNewContext(xGlobalDisplay, config[0], GLX_RGBA_TYPE, oglSystem.glContext, True);
1812                if(oglDisplay.glContext)
1813                {
1814                   glXMakeCurrent(xGlobalDisplay, None, null);
1815                   glXMakeCurrent(xGlobalDisplay, (int)display.window, oglDisplay.glContext);
1816
1817                   // Initialize Shared Memory Pixmap
1818                   oglDisplay.image = XShmCreateImage(xGlobalDisplay, DefaultVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 32, 
1819                      ZPixmap, null, &oglDisplay.shminfo, width, height);
1820                   if(oglDisplay.image)
1821                   {
1822                      oglDisplay.shminfo.shmid = shmget(IPC_PRIVATE, 
1823                         oglDisplay.image->bytes_per_line * oglDisplay.image->height, IPC_CREAT|0777);
1824                      if(oglDisplay.shminfo.shmid != -1)
1825                      {
1826                         oglDisplay.shminfo.shmaddr = shmat(oglDisplay.shminfo.shmid, 0, 0);
1827                         if(oglDisplay.shminfo.shmaddr != (void *)-1)
1828                         {
1829                            oglDisplay.shminfo.readOnly = False;
1830                            if(XShmAttach(xGlobalDisplay, &oglDisplay.shminfo))
1831                            {
1832                               oglDisplay.pixmap = XShmCreatePixmap(xGlobalDisplay, (X11Window)display.window, oglDisplay.shminfo.shmaddr, 
1833                                  &oglDisplay.shminfo, width, height, 32);
1834
1835                               // Initialize Shared Memory Shape Pixmap
1836                               oglDisplay.shapeImage = XShmCreateImage(xGlobalDisplay, DefaultVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 1, 
1837                                  ZPixmap, null, &oglDisplay.shminfoShape, width, height);
1838                               if(oglDisplay.shapeImage)
1839                               {
1840                                  oglDisplay.shminfoShape.shmid = shmget(IPC_PRIVATE, 
1841                                     oglDisplay.shapeImage->bytes_per_line * oglDisplay.shapeImage->height, IPC_CREAT|0777);
1842                                  if(oglDisplay.shminfoShape.shmid != -1)
1843                                  {
1844                                     oglDisplay.shminfoShape.shmaddr = shmat(oglDisplay.shminfoShape.shmid, 0, 0);
1845                                     if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
1846                                     {
1847                                        oglDisplay.shminfoShape.readOnly = False;
1848                                        if(XShmAttach(xGlobalDisplay, &oglDisplay.shminfoShape))
1849                                        {
1850                                           oglDisplay.shapePixmap = XShmCreatePixmap(xGlobalDisplay, (X11Window)display.window, oglDisplay.shminfoShape.shmaddr, 
1851                                              &oglDisplay.shminfoShape, width, height, 1);
1852                                           //oglDisplay.shapePixmap = XCreatePixmap(xGlobalDisplay, (X11Window)display.window, width, height, 1);
1853
1854                                           {
1855                                              XRenderPictureAttributes attributes = { 0 };
1856                                              XRenderPictFormat * format = XRenderFindStandardFormat(xGlobalDisplay, /*PictStandardRGB24*/ PictStandardARGB32);
1857                                              #if !defined(__APPLE__) && !defined(__OLDX__)
1858                                              attributes.repeat = RepeatNormal;
1859                                              #else
1860                                              attributes.repeat = 1;
1861                                              #endif
1862                                              oglDisplay.pixmapPicture = XRenderCreatePicture(xGlobalDisplay, oglDisplay.pixmap, format, CPRepeat, &attributes);
1863                                              oglDisplay.windowPicture = XRenderCreatePicture(xGlobalDisplay, (X11Window)display.window, format, 0, &attributes);
1864                                              oglDisplay.shapePicture = XRenderCreatePicture(xGlobalDisplay, oglDisplay.shapePixmap, 
1865                                                 XRenderFindStandardFormat(xGlobalDisplay, PictStandardA1), 0, &attributes);
1866                                           }  
1867
1868                                           oglDisplay.picture = oglDisplay.shminfo.shmaddr;
1869                                           oglDisplay.stride = oglDisplay.image->bytes_per_line / 4;
1870
1871                                           result = true;
1872                                        }
1873                                     }
1874                                  }
1875                               }
1876                            }
1877                         }
1878                      }
1879                   }
1880                }
1881             }
1882             XFree(config);
1883          }
1884      #endif
1885 #endif
1886          CreateDisplay(display);
1887 #if defined(__WIN32__)
1888          wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1889 #elif defined(__unix__)
1890       #if defined(__ANDROID__)
1891          width = eglWidth;
1892          height = eglHeight;
1893       #else
1894          glXMakeCurrent(xGlobalDisplay, (int)display.window, oglDisplay.glContext);
1895       #endif
1896 #endif
1897       }
1898       else
1899 #endif
1900          result = true;
1901       if(!result && display.alphaBlend)
1902       {
1903          printf("Alpha blending windows not supported on this display\n");
1904       }
1905       if(!result)
1906          return false;
1907          
1908       result = false;           
1909
1910       glViewport(0,0,width,height);
1911       glLoadIdentity();
1912       glOrtho(0,width,height,0,0.0,1.0);
1913       displayWidth = display.width = width;
1914       displayHeight = display.height = height;
1915
1916       if(!oglDisplay.flippingBuffer || oglDisplay.flipBufW < width || oglDisplay.flipBufH < height)
1917       {
1918          oglDisplay.flipBufW = width;
1919          oglDisplay.flipBufH = height;
1920          oglDisplay.flippingBuffer = renew oglDisplay.flippingBuffer ColorAlpha [width * height];
1921       }
1922       if(oglDisplay.flippingBuffer || !width || !height)
1923          result = true;
1924          
1925       return result;
1926    }
1927
1928    void DisplayPosition(Display display, int x, int y)
1929    {
1930       OGLDisplay oglDisplay = display.driverData;
1931
1932       oglDisplay.x = x;
1933       oglDisplay.y = y;
1934    }
1935
1936    void SetPalette(Display display, ColorAlpha * palette, bool colorMatch)
1937    {
1938    }
1939
1940    void RestorePalette(Display display)
1941    {
1942    }
1943
1944    void StartUpdate(Display display)
1945    {
1946    }
1947
1948    void EndUpdate(Display display)
1949    {
1950    }
1951
1952    void Scroll(Display display, Box scroll, int x, int y, Extent dirty)
1953    {
1954    }
1955
1956    void Update(Display display, Box updateBox)
1957    {
1958       OGLDisplay oglDisplay = display.driverData;
1959       //Logf("DisplayScreen\n");
1960
1961       glFlush();
1962       glFinish();
1963 #if defined(__WIN32__) || defined(USEPBUFFER)
1964       if(display.alphaBlend)
1965       {
1966          glPixelStorei(GL_PACK_ALIGNMENT, 4);
1967          glPixelStorei(GL_PACK_ROW_LENGTH, oglDisplay.stride);
1968          glPixelStorei(GL_PACK_SKIP_ROWS, 0);
1969          glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
1970          glReadPixels(0,0,display.width,display.height,GL_BGRA_EXT,GL_UNSIGNED_BYTE, oglDisplay.picture);
1971
1972          {
1973 #if defined(__WIN32__)
1974             HDC hdc = GetDC(0);
1975             POINT point = { oglDisplay.x, oglDisplay.y};
1976             POINT srcPoint = { 0, 0 };
1977             BLENDFUNCTION blend = { 0 };
1978             SIZE size;
1979             size.cx = display.width;
1980             size.cy = display.height;
1981             blend.BlendOp = AC_SRC_OVER;
1982             blend.BlendFlags = 0;
1983             blend.SourceConstantAlpha = 255;
1984             blend.AlphaFormat = AC_SRC_ALPHA;
1985
1986             /*
1987             // Process partial images.  Mapping the buffer waits for
1988             // outstanding DMA transfers into the buffer to finish.
1989             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
1990             oglDisplay.pboMemory1 = (byte *)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY);
1991            
1992             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
1993             // oglDisplay.pboMemory2 = (byte *)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB,GL_READ_ONLY);
1994
1995            
1996             memcpy(oglDisplay.picture, oglDisplay.pboMemory1, display.width * display.height * 4);
1997             //memcpy(oglDisplay.picture + display.width * display.height * 4 / 2, oglDisplay.pboMemory2, display.width * display.height * 4/ 2);
1998             */
1999             
2000             UpdateLayeredWindow(display.window, hdc, &point, &size, oglDisplay.memDC, &srcPoint, 0, &blend, ULW_ALPHA);
2001             /*
2002
2003             // Unmap the image buffers
2004             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2005             glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);
2006
2007             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2008             // glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);
2009            
2010             // Bind two different buffer objects and start the glReadPixels
2011             // asynchronously. Each call will return directly after
2012             // starting the DMA transfer.
2013             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2014             glReadPixels(0, 0, display.width, display.height, GL_BGRA, GL_UNSIGNED_BYTE, 0);
2015
2016             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2017             // glReadPixels(0, display.height/2, display.width, display.height/2, GL_BGRA, GL_UNSIGNED_BYTE, 0);
2018             */
2019
2020             ReleaseDC(0, hdc);
2021 #elif defined(__unix__)
2022       #if defined(__ANDROID__)
2023       #else
2024             XTransform transform = 
2025             {
2026                {
2027                   { (int)(1.0f * (1<<16)), (int)(0.0f * (1<<16)),  (int)(0 * (1 << 16)) },
2028                   { (int)(0.0f),           (int)(-1.0f * (1<<16)), (int)(0 * (1<<16)) },
2029                   { (int)(0.0f * (1<<16)), (int)(0.0f * (1<<16)),  (int)(1.0f * (1<<16)) }
2030                }
2031             };
2032             XRenderSetPictureTransform(xGlobalDisplay, oglDisplay.pixmapPicture, &transform);
2033             XRenderComposite(xGlobalDisplay, PictOpSrc, oglDisplay.pixmapPicture, None, oglDisplay.shapePicture, 0, 0, 0, 0, 0, 0, display.width, display.height);
2034             XRenderComposite(xGlobalDisplay, PictOpSrc, oglDisplay.pixmapPicture, None, oglDisplay.windowPicture, 0, 0, 0, 0, 0, 0, display.width, display.height);
2035             #if !defined(__APPLE__) && !defined(__OLDX__)
2036             XShapeCombineMask(xGlobalDisplay, (uint)display.window, ShapeInput, 0, 0, oglDisplay.shapePixmap, ShapeSet);
2037             #else
2038             XShapeCombineMask(xGlobalDisplay, display.window, 2, 0, 0, oglDisplay.shapePixmap, ShapeSet);
2039             #endif
2040             XFlush(xGlobalDisplay);
2041      #endif
2042 #endif
2043          }
2044       } 
2045       else
2046 #endif
2047       {
2048 #if defined(__WIN32__)
2049          //wglSwapLayerBuffers(oglDisplay.hdc,WGL_SWAP_MAIN_PLANE); 
2050          SwapBuffers(oglDisplay.hdc);
2051 #elif defined(__unix__)
2052       #if defined(__ANDROID__)
2053          eglSwapBuffers(eglDisplay, eglSurface);
2054       #else
2055          glXSwapBuffers(xGlobalDisplay, (int)display.window);
2056       #endif
2057 #endif
2058       }
2059       //Logf("Out of DisplayScreen\n");
2060    }
2061
2062    void FreeBitmap(DisplaySystem displaySystem, Bitmap bitmap)
2063    {
2064       glDeleteTextures(1, (int *)&bitmap.driverData);
2065       bitmap.driverData = 0;
2066
2067       bitmap.driver = ((subclass(DisplayDriver))class(LFBDisplayDriver));
2068    }
2069
2070    bool AllocateBitmap(DisplaySystem displaySystem, Bitmap bitmap, int width, int height, int stride, PixelFormat format, bool allocatePalette)
2071    {
2072       bool result = false;
2073       Bitmap mipMap { };
2074       int glBitmap = -1;
2075       
2076       uint w = pow2i(Min(width, 1024)), h = pow2i(Min(height, 1024));
2077       //uint w = pow2i(Min(width, 2048)), h = pow2i(Min(height, 2048));
2078       //uint w = pow2i(Min(width, 512)), h = pow2i(Min(height, 512));
2079
2080       glGenTextures(1, &glBitmap);
2081       glBindTexture(GL_TEXTURE_2D, glBitmap);
2082
2083       glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
2084
2085       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2086       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2087
2088       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2089       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2090
2091       glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
2092
2093       mipMap.Allocate(null, w, h, w, pixelFormatRGBA, false);
2094
2095       // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2096       glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2097
2098       delete mipMap;
2099
2100       bitmap.driverData = (void *)glBitmap;
2101       bitmap.driver = displaySystem.driver;
2102       bitmap.width = w;
2103       bitmap.height = h;
2104
2105       result = true;
2106       return result;
2107    }
2108
2109    bool MakeDDBitmap(DisplaySystem displaySystem, Bitmap bitmap, bool mipMaps)
2110    {
2111       bool result = false;
2112       OGLSystem oglSystem = displaySystem.driverData;
2113
2114       // Pre process the bitmap... First make it 32 bit
2115       if(/*bitmap.pixelFormat == pixelFormatRGBA || */bitmap.Convert(null, pixelFormat888, null))
2116       {
2117          int c, level;
2118          uint w = pow2i(Min(bitmap.width, 1024)), h = pow2i(Min(bitmap.height, 1024));
2119          //uint w = pow2i(Min(bitmap.width, 512)), h = pow2i(Min(bitmap.height, 512));
2120          int glBitmap = -1;
2121
2122          // Switch ARGB to RGBA
2123          //if(bitmap.format != pixelFormatRGBA)
2124          {
2125             for(c=0; c<bitmap.size; c++)
2126             {
2127                // ((ColorRGBA *)bitmap.picture)[c] = ((ColorAlpha *)bitmap.picture)[c];
2128                // TODO: 
2129                ColorAlpha color = ((ColorAlpha *)bitmap.picture)[c];
2130                ((ColorRGBA *)bitmap.picture)[c] = ColorRGBA { color.color.r, color.color.g, color.color.b, color.a };
2131             }
2132          }
2133          bitmap.pixelFormat = pixelFormat888;
2134
2135          glGetError();
2136          glGenTextures(1, &glBitmap);
2137          if(glBitmap == -1)
2138          {
2139             int error = glGetError();
2140             return false;
2141             //Print("");
2142          }
2143
2144          glBindTexture(GL_TEXTURE_2D, glBitmap);
2145          glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
2146
2147          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2148          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mipMaps ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
2149          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2150
2151          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
2152          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
2153
2154          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2155          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2156
2157          glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
2158
2159          result = true;
2160
2161          for(level = 0; result && (w > 1 || h > 1); level++, w >>= 1, h >>= 1)
2162          {
2163             Bitmap mipMap;
2164             if(bitmap.width != w || bitmap.height != h)
2165             {
2166                mipMap = Bitmap { };
2167                if(mipMap.Allocate(null, w, h, w, bitmap.pixelFormat, false))
2168                {
2169                   Surface mipSurface = mipMap.GetSurface(0,0,null);
2170                   mipSurface.Filter(bitmap, 0,0,0,0, w, h, bitmap.width, bitmap.height);
2171                   delete mipSurface;
2172                }
2173                else
2174                {
2175                   result = false;
2176                   delete mipMap;
2177                }
2178             }
2179             else 
2180                mipMap = bitmap;
2181
2182             if(result)
2183             {
2184                int error;
2185                //int width = 0;
2186                glGetError();
2187                // glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2188                glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2189                //printf("Calling glTexImage2D\n");
2190                //glGetTexLevelParameteriv(GL_TEXTURE_2D, level, GL_TEXTURE_WIDTH, &width);
2191                //printf("width = %d (Should be %d, %d)\n", width, w, h);
2192                if((error = glGetError()))
2193                {
2194                   //Logf("OpenGL Bitmap MakeDD error: %d...\n", error);
2195                   //printf("OpenGL Bitmap MakeDD error: %d...\n", error);
2196                   result = false;
2197                }
2198             }
2199             if(mipMap != bitmap) 
2200                delete mipMap;
2201             if(!mipMaps) break;
2202          }
2203
2204          if(!bitmap.keepData)
2205             bitmap.driver.FreeBitmap(bitmap.displaySystem, bitmap);
2206          bitmap.driverData = (void *)glBitmap;
2207          bitmap.driver = displaySystem.driver;
2208
2209          if(!result)
2210             FreeBitmap(displaySystem, bitmap);
2211          else if(oglSystem.loadingFont)
2212          {
2213             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2214             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2215             oglSystem.loadingFont = false;
2216          }
2217       }
2218       return result;
2219    }
2220
2221    void ReleaseSurface(Display display, Surface surface)
2222    {
2223       glDisable(GL_SCISSOR_TEST);
2224       delete surface.driverData;
2225       surface.driverData = null;
2226    }
2227
2228    bool GetBitmapSurface(DisplaySystem displaySystem, Surface surface, Bitmap bitmap, int x, int y, Box clip)
2229    {
2230       return false;
2231    }
2232
2233    bool GetSurface(Display display, Surface surface, int x,int y, Box clip)
2234    {
2235       bool result = false;
2236       OGLSurface oglSurface = surface.driverData = OGLSurface { };
2237
2238       //Logf("GetSurface\n");
2239
2240       if(oglSurface)
2241       {
2242          if(displayWidth != display.width || displayHeight != display.height)
2243          {
2244             displayWidth = display.width;
2245             displayHeight = display.height;
2246
2247             glViewport(0,0,display.width,display.height);
2248             glLoadIdentity();
2249             glOrtho(0,display.width,display.height,0,0.0,1.0);
2250          }
2251
2252          surface.offset.x = x;
2253          surface.offset.y = y;
2254          surface.unclippedBox = surface.box = clip;
2255          oglSurface.bitmapMult[0] = 1;
2256          oglSurface.bitmapMult[1] = 1;
2257          oglSurface.bitmapMult[2] = 1;
2258          oglSurface.bitmapMult[3] = 1;
2259
2260          glEnable(GL_SCISSOR_TEST);
2261          glScissor(
2262             x+clip.left,
2263             (display.height) -(y+clip.bottom)-1,
2264             clip.right-clip.left+1,
2265             clip.bottom-clip.top+1);
2266          result = true;
2267       }
2268       return result;
2269    }
2270
2271    void Clip(Display display, Surface surface, Box clip)
2272    {
2273       Box box;
2274
2275       //Logf("Clip\n");
2276
2277       if(clip != null)
2278       {
2279          box = clip;
2280          box.Clip(surface.unclippedBox);
2281          surface.box = box;
2282       }
2283       else
2284          box = surface.box = surface.unclippedBox;
2285       box.left += surface.offset.x;
2286       box.top  += surface.offset.y;
2287       box.right+= surface.offset.x;
2288       box.bottom += surface.offset.y;
2289
2290       glScissor(
2291          box.left,display.height - box.bottom - 1,
2292          box.right-box.left+1, box.bottom-box.top+1);
2293    }
2294
2295    bool GrabScreen(Display display, Bitmap bitmap, int x, int y, unsigned int w, unsigned int h)
2296    {
2297       bool result = false;
2298       OGLDisplay oglDisplay = display.driverData;
2299       ColorAlpha * flippingBuffer = oglDisplay.flippingBuffer;
2300       
2301       if(oglDisplay.flippingBuffer)
2302       {
2303          if(bitmap.pixelFormat != pixelFormat888 || bitmap.width < w || bitmap.height < h)
2304          {
2305             bitmap.Free();
2306             bitmap.Allocate(null, w,h,w, pixelFormat888, false);
2307          }
2308          if(bitmap)
2309          {
2310             uint row;
2311
2312             glPixelStorei(GL_PACK_ALIGNMENT, 4);
2313             glPixelStorei(GL_PACK_ROW_LENGTH, bitmap.stride);
2314             glPixelStorei(GL_PACK_SKIP_ROWS, 0);
2315             glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
2316             glReadPixels(x,display.height-h-y,w,h,GL_BGRA_EXT,GL_UNSIGNED_BYTE, flippingBuffer);
2317
2318             // Need a flip...
2319             for(row = 0; row<h; row++)
2320                CopyBytesBy4(((ColorAlpha *)bitmap.picture) + row * w, ((ColorAlpha *)flippingBuffer) + (h-row-1) * w, w);
2321             result = true;
2322          }
2323       }
2324       return result;
2325    }
2326
2327    void SetForeground(Display display, Surface surface, ColorAlpha color)
2328    {
2329       OGLSurface oglSurface = surface.driverData;
2330
2331       //Logf("SetForeground\n");
2332
2333       oglSurface.foreground[0] = color.color.r/255.0f;
2334       oglSurface.foreground[1] = color.color.g/255.0f;
2335       oglSurface.foreground[2] = color.color.b/255.0f;
2336       //oglSurface.foreground[3] = 1.0f;
2337       oglSurface.foreground[3] = color.a/255.0f;
2338
2339       //if(!oglSurface.foreground[3])printf("bug");
2340    }
2341
2342    void SetBackground(Display display, Surface surface, ColorAlpha color)
2343    {
2344       OGLSurface oglSurface = surface.driverData;
2345
2346       //Logf("SetBackground\n");
2347
2348       oglSurface.background[0] = color.color.r/255.0f;
2349       oglSurface.background[1] = color.color.g/255.0f;
2350       oglSurface.background[2] = color.color.b/255.0f;
2351       //oglSurface.background[3] = 1.0;
2352       oglSurface.background[3] = color.a/255.0f;
2353    }
2354
2355    void SetBlitTint(Display display, Surface surface, ColorAlpha color)
2356    {
2357       OGLSurface oglSurface = surface.driverData;
2358
2359       oglSurface.bitmapMult[0] = color.color.r/255.0f;
2360       oglSurface.bitmapMult[1] = color.color.g/255.0f;
2361       oglSurface.bitmapMult[2] = color.color.b/255.0f;
2362       oglSurface.bitmapMult[3] = color.a/255.0f;
2363    }
2364
2365    ColorAlpha GetPixel(Display display, Surface surface,int x,int y)
2366    {
2367       return 0;
2368    }
2369
2370    void PutPixel(Display display, Surface surface,int x,int y)
2371    {
2372       OGLSurface oglSurface = surface.driverData;
2373
2374       //Logf("PutPixel\n");
2375
2376       glColor4fv(oglSurface.foreground);
2377       glBegin(GL_POINTS);
2378       // glVertex2i(x+surface.offset.x, y+surface.offset.y);
2379       glVertex2f(x+surface.offset.x + 0.5f, y+surface.offset.y + 0.5f);
2380        
2381       glEnd();
2382    }
2383
2384    void DrawLine(Display display, Surface surface, int x1, int y1, int x2, int y2)
2385    {
2386       OGLSurface oglSurface = surface.driverData;
2387       if(x1 == x2) { y2++; y1--; }
2388       else if(y1 == y2) { x2++; x1--; }
2389       x1 += surface.offset.x;
2390       y1 += surface.offset.y;
2391       x2 += surface.offset.x;
2392       y2 += surface.offset.y;
2393
2394       //Logf("Line\n");
2395
2396       glColor4fv(oglSurface.foreground);
2397       glBegin(GL_LINES);
2398 #ifdef __ANDROID__
2399       if(stippleEnabled)
2400       {
2401          glTexCoord2f(0.5f, 0);
2402          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2403          glTexCoord2f(Max(x2-x1, y2-y1) + 0.5f, 0);
2404          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2405       }
2406       else
2407 #endif
2408       {
2409          /*
2410          glVertex2i(x1, y1);
2411          glVertex2i(x2, y2);
2412          */
2413          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2414          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2415       }
2416       
2417       glEnd();
2418    }
2419
2420    void Rectangle(Display display, Surface surface,int x1,int y1,int x2,int y2)
2421    {
2422       OGLSurface oglSurface = surface.driverData;
2423       x1 += surface.offset.x;
2424       y1 += surface.offset.y;
2425       x2 += surface.offset.x;
2426       y2 += surface.offset.y;
2427
2428       //Logf("Rectangle\n");
2429
2430       glColor4fv(oglSurface.foreground);
2431 #ifdef __ANDROID__
2432       if(stippleEnabled)
2433       {
2434          glBegin(GL_LINES);
2435
2436          glTexCoord2f(0.5f, 0);
2437          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2438          glTexCoord2f(y2-y1 + 0.5f, 0);
2439          glVertex2f(x1 + 0.5f, y2 + 0.5f);
2440
2441          glTexCoord2f(0.5f, 0);
2442          glVertex2f(x1 + 0.5f, y2 + 0.5f);
2443          glTexCoord2f(x2 - x1 + 0.5f, 0);
2444          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2445
2446          glTexCoord2f(0.5f, 0);
2447          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2448          glTexCoord2f(y1 - y2 + 0.5f, 0);
2449          glVertex2f(x2 + 0.5f, y1 + 0.5f);
2450
2451          glTexCoord2f(0.5f, 0);
2452          glVertex2f(x2 + 0.5f, y1 + 0.5f);
2453          glTexCoord2f(x1 - x2 + 0.5f, 0);
2454          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2455       }
2456       else
2457 #endif
2458       {
2459          glBegin(GL_LINE_LOOP);
2460          /*
2461          glVertex2i(x1, y1);
2462          glVertex2i(x1, y2);
2463          glVertex2i(x2, y2);
2464          glVertex2i(x2, y1);
2465          */
2466          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2467          glVertex2f(x1 + 0.5f, y2 + 0.5f);
2468          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2469          glVertex2f(x2 + 0.5f, y1 + 0.5f);
2470       }
2471       glEnd();
2472    }
2473
2474    void Area(Display display, Surface surface,int x1,int y1,int x2,int y2)
2475    {
2476       OGLSurface oglSurface = surface.driverData;
2477       //Logf("Area\n");
2478
2479       glColor4fv(oglSurface.background);
2480       glRecti(x1+surface.offset.x, y1+surface.offset.y,
2481               x2+surface.offset.x + 1, y2+surface.offset.y + 1);
2482               
2483       /*
2484       glRectf(x1+surface.offset.x, y1+surface.offset.y,
2485               x2+surface.offset.x + 1, y2+surface.offset.y + 1);
2486       */
2487    }
2488
2489    void Clear(Display display, Surface surface, ClearType type)
2490    {
2491       OGLDisplay oglDisplay = display.driverData;
2492       OGLSurface oglSurface = surface.driverData;
2493
2494       //Logf("Clear\n");
2495       if(type != depthBuffer)
2496          glClearColor(oglSurface.background[0], oglSurface.background[1], oglSurface.background[2], oglSurface.background[3]);
2497       if(type != colorBuffer && !oglDisplay.depthWrite)
2498       {
2499          glDepthMask((byte)bool::true);
2500       }
2501       glClear(((type != depthBuffer) ? GL_COLOR_BUFFER_BIT : 0) |
2502               ((type != colorBuffer) ? GL_DEPTH_BUFFER_BIT : 0));
2503       if(type != colorBuffer && !oglDisplay.depthWrite)
2504       {
2505          glDepthMask((byte)bool::false);
2506       }
2507    }
2508
2509    bool ConvertBitmap(DisplaySystem displaySystem, Bitmap bitmap, PixelFormat format, ColorAlpha * palette)
2510    {
2511       return true;
2512    }
2513
2514    void Blit(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h)
2515    {
2516       OGLSurface oglSurface = surface.driverData;
2517
2518 #if !defined(__OLDX__)
2519          // WHY DO WE HAVE GL_ONE HERE ?
2520          /*if(glBlendFuncSeparate && !oglSurface.writingText)
2521             glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2522 #endif
2523
2524       if(!oglSurface.writingText)
2525       {
2526          // glTranslatef(-0.375f, -0.375f, 0.0f);
2527          glEnable(GL_TEXTURE_2D);
2528          glColor4fv(oglSurface.bitmapMult);
2529       }
2530       else if(oglSurface.xOffset)
2531          glTranslatef(oglSurface.xOffset / 64.0f/*-0.375f*/, 0.0f, 0.0f);
2532          
2533       glBindTexture(GL_TEXTURE_2D, (uint)bitmap.driverData);
2534       glBegin(GL_QUADS);
2535
2536       if(h < 0)
2537       {
2538          glTexCoord2f((float)sx/ bitmap.width, (float)(sy-h)/ bitmap.height);
2539          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2540          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy-h)/ bitmap.height);
2541          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2542          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
2543          glVertex2i(dx+w+surface.offset.x, dy-h+surface.offset.y);
2544          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
2545          glVertex2i(dx+surface.offset.x, dy-h+surface.offset.y);
2546       }
2547       else
2548       {
2549          /*
2550          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
2551          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2552          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
2553          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2554          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy+h)/ bitmap.height);
2555          glVertex2i(dx+w+surface.offset.x, dy+h+surface.offset.y);
2556          glTexCoord2f((float)sx/ bitmap.width, (float)(sy+h)/ bitmap.height);
2557          glVertex2i(dx+surface.offset.x, dy+h+surface.offset.y);
2558          */
2559
2560          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
2561          glVertex2f((float)dx+surface.offset.x, (float)dy+surface.offset.y);
2562          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
2563          glVertex2f((float)dx+w+surface.offset.x, (float)dy+surface.offset.y);
2564          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy+h)/ bitmap.height);
2565          glVertex2f((float)dx+w+surface.offset.x, (float)dy+h+surface.offset.y);
2566          glTexCoord2f((float)sx/ bitmap.width, (float)(sy+h)/ bitmap.height);
2567          glVertex2f((float)dx+surface.offset.x, (float)dy+h+surface.offset.y);
2568       }
2569       glEnd();
2570
2571       if(!oglSurface.writingText)
2572       {
2573          glDisable(GL_TEXTURE_2D);
2574
2575          //glTranslatef(0.375f, 0.375f, 0.0f);
2576       }
2577       else if(oglSurface.xOffset)
2578          glTranslatef(-oglSurface.xOffset / 64.0f/*+0.375f*/, 0.0f, 0.0f);
2579
2580 #if !defined(__OLDX__)
2581          /*if(glBlendFuncSeparate && !oglSurface.writingText)
2582             glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2583 #endif
2584    }
2585
2586    void Stretch(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
2587    {
2588       OGLSurface oglSurface = surface.driverData;
2589
2590       //glTranslatef(-0.375f, -0.375f, 0.0f);
2591
2592       //Logf("Stretch\n");
2593
2594 #if !defined(__OLDX__)
2595       /*if(glBlendFuncSeparate)
2596          glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2597 #endif
2598
2599       glEnable(GL_TEXTURE_2D);
2600       glBindTexture(GL_TEXTURE_2D, (uint)bitmap.driverData);
2601
2602       glColor4fv(oglSurface.bitmapMult);
2603
2604       glBegin(GL_QUADS);
2605
2606       if(h < 0)
2607       {
2608          glTexCoord2f((float)(sx)/ bitmap.width, (float)(sy+sh)/ bitmap.height);
2609          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2610       
2611          glTexCoord2f((float)(sx+sw) / bitmap.width, (float)(sy+sh)/ bitmap.height);
2612          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2613       
2614          glTexCoord2f((float)(sx+sw)/ bitmap.width, (float)(sy)/ bitmap.height);
2615          glVertex2i(dx+w+surface.offset.x, dy-h+surface.offset.y);
2616       
2617          glTexCoord2f((float)(sx) / bitmap.width, (float)(sy)/ bitmap.height);
2618          glVertex2i(dx+surface.offset.x, dy-h+surface.offset.y);
2619       }
2620       else
2621       {
2622          glTexCoord2f((float)(sx) / bitmap.width, (float)(sy)/ bitmap.height);
2623          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2624       
2625          glTexCoord2f((float)(sx+sw)/ bitmap.width, (float)(sy)/ bitmap.height);
2626          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2627       
2628          glTexCoord2f((float)(sx+sw) / bitmap.width, (float)(sy+sh)/ bitmap.height);
2629          glVertex2i(dx+w+surface.offset.x, dy+h+surface.offset.y);
2630       
2631          glTexCoord2f((float)(sx)/ bitmap.width, (float)(sy+sh)/ bitmap.height);
2632          glVertex2i(dx+surface.offset.x, dy+h+surface.offset.y);
2633       }
2634
2635       glEnd();
2636
2637       glDisable(GL_TEXTURE_2D);
2638
2639       //glTranslatef(0.375f, 0.375f, 0.0f);
2640 #if !defined(__OLDX__)
2641       /*if(glBlendFuncSeparate)
2642          glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2643 #endif
2644
2645    }
2646
2647    void Filter(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
2648    {
2649       Stretch(display, surface, bitmap, dx, dy, sx, sy, w, h, sw, sh);
2650    }
2651
2652    void StretchDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
2653    {
2654       float s2dw,s2dh,d2sw,d2sh;
2655       bool flipX = false, flipY = false;
2656
2657       //Logf("StretchDI\n");
2658
2659       if(Sgn(w) != Sgn(sw))
2660       {
2661          w = Abs(w);
2662          sw = Abs(sw);
2663          flipX = true; 
2664       }
2665       if(Sgn(h) != Sgn(sh))
2666       {
2667          h = Abs(h);
2668          sh = Abs(sh);
2669          flipY = true; 
2670       }
2671
2672       s2dw=(float)w / sw;
2673       s2dh=(float)h / sh;
2674       d2sw=(float)sw / w;
2675       d2sh=(float)sh / h;
2676
2677       //Clip against the edges of the source
2678       if(sx<0)
2679       {
2680          dx+=(int)((0-sx) * s2dw);
2681          w-=(int)((0-sx) * s2dw);
2682          sw-=0-sx;
2683          sx=0;
2684       }
2685       if(sy<0)
2686       {
2687          dy+=(int)((0-sy) * s2dh);
2688          h-=(int)((0-sy) * s2dh);
2689
2690          sh-=0-sy;
2691          sy=0;
2692       }
2693       if(sx+sw>bitmap.width-1)
2694       {
2695          w-=(int)((sx+sw-(bitmap.width-1)-1)*s2dw);
2696          sw-=sx+sw-(bitmap.width-1)-1;
2697       }
2698       if(sy+sh>(bitmap.height-1))
2699       {
2700          h-=(int)((sy+sh-(bitmap.height-1)-1)*s2dh);
2701          sh-=sy+sh-(bitmap.height-1)-1;
2702       }
2703       //Clip against the edges of the surfaceination
2704       if(dx<surface.box.left)
2705       {
2706          //if(!flip) 
2707          sx+=(int)((surface.box.left-dx)*d2sw);
2708          sw-=(int)((surface.box.left-dx)*d2sw);
2709          w-=surface.box.left-dx;
2710          dx=surface.box.left;
2711       }
2712       if(dy<surface.box.top)
2713       {
2714          sy+=(int)((surface.box.top-dy)*d2sh);
2715          sh-=(int)((surface.box.top-dy)*d2sh);
2716          h-=surface.box.top-dy;
2717          dy=surface.box.top;
2718       }
2719       if(dx+w>surface.box.right)
2720       {
2721          //if(flip) sx+=(int)((dx+w-surface.box.right-1)*d2sw);
2722          sw-=(int)((dx+w-surface.box.right-1)*d2sw);
2723          w-=dx+w-surface.box.right-1;
2724       }
2725       if(dy+h>surface.box.bottom)
2726       {
2727          sh-=(int)((dy+h-surface.box.bottom-1)*d2sh);
2728          h-=dy+h-surface.box.bottom-1;
2729       }
2730       if((w<=0)||(h<=0)||(sw<=0)||(sh<=0)) return;
2731
2732       dx += surface.offset.x;
2733       dy += surface.offset.y;
2734
2735       if(bitmap.pixelFormat == pixelFormat888 && !bitmap.paletteShades)
2736       {
2737          glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
2738          glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.stride);
2739          glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
2740          glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
2741          glRasterPos2d(dx,dy);
2742          //glPixelZoom(flipX ? -s2dw : s2dw, flipY ? s2dh : -s2dh);
2743          glPixelZoom(s2dw, -s2dh);
2744          glDrawPixels(sw,sh,GL_BGRA_EXT,GL_UNSIGNED_BYTE, bitmap.picture);
2745          glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
2746          glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
2747       }
2748    }
2749
2750    void BlitDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h)
2751    {
2752       //Logf("BlitDI\n");
2753
2754       //Clip against the edges of the source
2755       if(sx<0)
2756       {
2757          dx+=-sx;
2758          w-=-sx;
2759          sx=0;
2760       }
2761       if(sy<0)
2762       {
2763          dy+=0-sy;
2764          h-=0-sy;
2765          sy=0;
2766       }
2767       if(sx+w>bitmap.width-1)
2768          w-=sx+w-(bitmap.width-1)-1;
2769       if(sy+h>bitmap.height-1)
2770          h-=sy+h-(bitmap.height-1)-1;
2771       //Clip against the edges of the surfaceination
2772       if(dx<surface.box.left)
2773       {
2774          //if(!flip) 
2775          sx+=surface.box.left-dx;
2776          w-=surface.box.left-dx;
2777          dx=surface.box.left;
2778       }
2779       if(dy<surface.box.top)
2780       {
2781          sy+=surface.box.top-dy;
2782          h-=surface.box.top-dy;
2783          dy=surface.box.top;
2784       }
2785       if(dx+w>surface.box.right)
2786       {
2787          //if(flip) sx+=dx+w-surface.box.right-1;
2788          w-=dx+w-surface.box.right-1;
2789       }
2790       if(dy+h>surface.box.bottom)
2791          h-=dy+h-surface.box.bottom-1;
2792       if((w<=0)||(h<=0))
2793          return;
2794
2795       dx += surface.offset.x;
2796       dy += surface.offset.y;
2797
2798       if(bitmap.pixelFormat == pixelFormat888 && !bitmap.paletteShades)
2799       {
2800          glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
2801          glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.stride);
2802          glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
2803          glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
2804          glRasterPos2d(dx,dy);
2805          glPixelZoom(1,-1);
2806          glDrawPixels(w,h,GL_BGRA_EXT,GL_UNSIGNED_BYTE, bitmap.picture);
2807          glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
2808          glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
2809       }
2810    }
2811
2812    void FilterDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
2813    {
2814       StretchDI(display, surface, bitmap, dx, dy, sx, sy, w, h, sw, sh);
2815    }
2816
2817    void UnloadFont(DisplaySystem displaySystem, Font font)
2818    {
2819       ((subclass(DisplayDriver))class(LFBDisplayDriver)).UnloadFont(displaySystem, font);
2820    }
2821
2822    Font LoadFont(DisplaySystem displaySystem, char * faceName, float size, FontFlags flags)
2823    {
2824       Font font;
2825       OGLSystem oglSystem = displaySystem.driverData;
2826       oglSystem.loadingFont = true;
2827       font = ((subclass(DisplayDriver))class(LFBDisplayDriver)).LoadFont(displaySystem, faceName, size, flags);
2828       return font;
2829    }
2830
2831    void FontExtent(DisplaySystem displaySystem, Font font, char * text, int len, int * width, int * height)
2832    {
2833       ((subclass(DisplayDriver))class(LFBDisplayDriver)).FontExtent(displaySystem, font, text, len, width, height);
2834    }
2835
2836    void WriteText(Display display, Surface surface, int x, int y, char * text, int len)
2837    {
2838       OGLSurface oglSurface = surface.driverData;
2839       OGLSystem oglSystem = display.displaySystem.driverData;
2840       oglSystem.loadingFont = true;
2841
2842       //glTranslatef(-0.375f, -0.375f, 0.0f);
2843
2844       //Logf("Blit\n");
2845
2846       if(surface.textOpacity)
2847       {
2848          int w, h;
2849          FontExtent(display.displaySystem, surface.font, text, len, &w, &h);
2850          display.displaySystem.driver.Area(display, surface,x,y,x+w-1,y+h-1);
2851       }
2852
2853       oglSurface.writingText = true;
2854
2855       glEnable(GL_TEXTURE_2D);
2856       glColor4fv(oglSurface.foreground);
2857
2858       ((subclass(DisplayDriver))class(LFBDisplayDriver)).WriteText(display, surface, x, y, text, len);
2859       oglSurface.writingText = false;
2860       oglSystem.loadingFont = false;
2861
2862       glDisable(GL_TEXTURE_2D);
2863
2864       //glTranslatef(0.375f, 0.375f, 0.0f);
2865    }
2866
2867    void TextFont(Display display, Surface surface, Font font)
2868    {
2869       ((subclass(DisplayDriver))class(LFBDisplayDriver)).TextFont(display, surface, font);
2870    }
2871
2872    void TextOpacity(Display display, Surface surface, bool opaque)
2873    {
2874       OGLSurface oglSurface = surface.driverData;
2875       oglSurface.opaqueText = opaque;
2876    }
2877
2878    void TextExtent(Display display, Surface surface, char * text, int len, int * width, int * height)
2879    {
2880       OGLSurface oglSurface = surface.driverData;
2881       OGLSystem oglSystem = display.displaySystem.driverData;
2882       oglSystem.loadingFont = true;
2883       FontExtent(display.displaySystem, oglSurface.font, text, len, width, height);
2884       oglSystem.loadingFont = false;
2885    }
2886
2887    void DrawingChar(Display display, Surface surface, char character)
2888    {
2889
2890    }
2891
2892    void LineStipple(Display display, Surface surface, uint32 stipple)
2893    {
2894       //Logf("Stipple\n");
2895
2896       if(stipple)
2897       {
2898 #if defined(__ANDROID__)
2899          stippleEnabled = true;
2900          glesLineStipple(1, (uint16)stipple);
2901 #else
2902          glLineStipple(1, (uint16)stipple);
2903          glEnable(GL_LINE_STIPPLE);
2904 #endif
2905       }
2906       else
2907       {
2908 #if defined(__ANDROID__)
2909          stippleEnabled = false;
2910          glMatrixMode(GL_TEXTURE);
2911          glLoadIdentity();
2912          glMatrixMode(GL_PROJECTION);
2913          glDisable(GL_TEXTURE_2D);
2914 #else
2915          glDisable(GL_LINE_STIPPLE);
2916 #endif
2917       }
2918    }
2919
2920    void SetRenderState(Display display, RenderState state, uint value)
2921    {
2922       OGLDisplay oglDisplay = display.driverData;
2923       //Logf("RenderState\n");
2924
2925       switch(state)
2926       {
2927          case antiAlias:
2928             if(value)
2929                glEnable(GL_MULTISAMPLE_ARB);
2930             else
2931                glDisable(GL_MULTISAMPLE_ARB);
2932             break;
2933          case fillMode:
2934             glPolygonMode(GL_FRONT_AND_BACK, ((FillModeValue)value == solid) ? GL_FILL : GL_LINE);
2935             break;
2936          case depthTest:
2937             if(value) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
2938             break;
2939          case depthWrite:
2940             if(value) glDepthMask((byte)bool::true); else glDepthMask((byte)bool::false);
2941             oglDisplay.depthWrite = value;
2942             break;
2943          case fogColor:
2944          {
2945             float color[4] = { ((Color)value).r/255.0f, ((Color)value).g/255.0f, ((Color)value).b/255.0f, 1.0f };
2946             glFogfv(GL_FOG_COLOR, (float *)&color);
2947             break;
2948          }
2949          case fogDensity:
2950             glFogf(GL_FOG_DENSITY, *(float *)(void *)&value);
2951             break;
2952          case blend:
2953             if(value) glEnable(GL_BLEND); else glDisable(GL_BLEND);
2954             break;
2955          case ambient:
2956          {
2957             float ambient[4] = { ((Color)value).r/255.0f, ((Color)value).g/255.0f, ((Color)value).b/255.0f, 1.0f };
2958             glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
2959             break;
2960          }
2961          case alphaWrite:
2962          {
2963             if(value) glColorMask(1,1,1,1); else glColorMask(1,1,1,0);
2964             break;
2965          }
2966          case vSync:
2967          {
2968 #if defined(__WIN32__)
2969             wglSwapIntervalEXT(value ? 1 : 0);
2970 #endif
2971             break;
2972          }
2973       }
2974    }
2975
2976    void SetLight(Display display, int id, Light light)
2977    {
2978       //Logf("SetLight\n");
2979
2980       if(light != null)
2981       {
2982          Object lightObject = light.lightObject;
2983          float position[4] = { 0, 0, 0, 0 };
2984          float color[4] = { 0, 0, 0, 1 };
2985
2986          glEnable(GL_LIGHT0 + id);
2987          /*
2988          glLightfv(GL_LIGHT0 + id, GL_DIFFUSE, (float *)&light.diffuse);
2989          glLightfv(GL_LIGHT0 + id, GL_AMBIENT, (float *)&light.ambient);
2990          glLightfv(GL_LIGHT0 + id, GL_SPECULAR,(float *)&light.specular);
2991          */
2992
2993          if(!light.multiplier) light.multiplier = 1.0f;
2994
2995          color[0] = light.diffuse.r * light.multiplier;
2996          color[1] = light.diffuse.g * light.multiplier;
2997          color[2] = light.diffuse.b * light.multiplier;
2998          glLightfv(GL_LIGHT0 + id, GL_DIFFUSE, color);
2999          
3000          color[0] = light.ambient.r * light.multiplier;
3001          color[1] = light.ambient.g * light.multiplier;
3002          color[2] = light.ambient.b * light.multiplier;
3003          glLightfv(GL_LIGHT0 + id, GL_AMBIENT, color);
3004          color[0] = light.specular.r * light.multiplier;
3005          color[1] = light.specular.g * light.multiplier;
3006          color[2] = light.specular.b * light.multiplier;
3007          glLightfv(GL_LIGHT0 + id, GL_SPECULAR,color);
3008          
3009          if(lightObject)
3010          {
3011             Vector3D positionVector;
3012             if(light.flags.spot)
3013             {
3014                if(lightObject.flags.root || !lightObject.parent)
3015                {
3016                   positionVector = lightObject.transform.position;
3017                   positionVector.Subtract(positionVector, display.display3D.camera.cPosition);
3018                }
3019                else
3020                {
3021                   positionVector.MultMatrix(lightObject.transform.position, lightObject.parent.matrix);
3022                   if(display.display3D.camera)
3023                      positionVector.Subtract(positionVector, display.display3D.camera.cPosition);
3024                }
3025                position[3] = 1;
3026             }
3027             else
3028             {
3029                if(!light.direction.x && !light.direction.y && !light.direction.z)
3030                {
3031                   Vector3Df vector { 0,0,-1 };
3032                   Matrix mat;
3033                   mat.RotationQuaternion(light.orientation);
3034                   positionVector.MultMatrixf(vector, mat);
3035                }
3036                else
3037                {
3038                   positionVector = light.direction;
3039                   position[3] = 1;
3040                }
3041             }
3042
3043             position[0] = (float)positionVector.x;
3044             position[1] = (float)positionVector.y;
3045             position[2] = (float)positionVector.z;
3046             
3047             glLightfv(GL_LIGHT0 + id, GL_POSITION, position);
3048
3049             /*
3050             // Display Light Position
3051             glDisable(GL_LIGHTING);
3052             glDisable(GL_DEPTH_TEST);
3053             glColor3f(1,1,1);
3054             glPointSize(10);
3055             glBegin(GL_POINTS);
3056             glVertex3fv(position);
3057             glEnd();
3058             glEnable(GL_DEPTH_TEST);
3059             glEnable(GL_LIGHTING);
3060                      
3061
3062             // Display Target
3063             if(lightObject.flags.root || !lightObject.parent)
3064             {
3065                positionVector = light.target.transform.position;
3066                positionVector.Subtract(positionVector, display.camera.cPosition);
3067             }
3068             else
3069             {
3070                positionVector.MultMatrix(light.target.transform.position, 
3071                   lightObject.light.target.parent.matrix);
3072                positionVector.Subtract(positionVector, display.camera.cPosition);
3073             }
3074
3075             position[0] = positionVector.x;
3076             position[1] = positionVector.y;
3077             position[2] = positionVector.z;
3078
3079             glDisable(GL_LIGHTING);
3080             glDisable(GL_DEPTH_TEST);
3081             glColor3f(1,1,0);
3082             glPointSize(10);
3083             glBegin(GL_POINTS);
3084             glVertex3fv(position);
3085             glEnd();
3086             glEnable(GL_DEPTH_TEST);
3087             glEnable(GL_LIGHTING);
3088             */
3089
3090             if(light.flags.attenuation)
3091             {
3092                glLightf(GL_LIGHT0 + id, GL_CONSTANT_ATTENUATION, light.Kc);
3093                glLightf(GL_LIGHT0 + id, GL_LINEAR_ATTENUATION, light.Kl);
3094                glLightf(GL_LIGHT0 + id, GL_QUADRATIC_ATTENUATION, light.Kq);
3095             }
3096
3097             if(light.flags.spot)
3098             {
3099                float exponent = 0;
3100                #define MAXLIGHT  0.9
3101                float direction[4] = { (float)light.direction.x, (float)light.direction.y, (float)light.direction.z, 1 };
3102                // Figure out exponent out of the hot spot
3103                exponent = (float)(log(MAXLIGHT) / log(cos((light.hotSpot / 2))));
3104
3105                glLightfv(GL_LIGHT0 + id, GL_SPOT_DIRECTION, direction);
3106                glLightf(GL_LIGHT0 + id, GL_SPOT_CUTOFF, (float)(light.fallOff / 2));
3107                glLightf(GL_LIGHT0 + id, GL_SPOT_EXPONENT, exponent);
3108             }
3109          }
3110          else
3111          {
3112             
3113             Vector3Df vector { 0,0,-1 };
3114             Vector3Df direction;
3115             Matrix mat;
3116
3117             mat.RotationQuaternion(light.orientation);
3118             direction.MultMatrix(vector, mat);
3119
3120             position[0] = direction.x;
3121             position[1] = direction.y;
3122             position[2] = direction.z;
3123
3124             glLightfv(GL_LIGHT0 + id, GL_POSITION, position);
3125          }
3126       }
3127       else
3128          glDisable(GL_LIGHT0 + id);
3129    }
3130
3131    void SetCamera(Display display, Surface surface, Camera camera)
3132    {
3133       OGLDisplay oglDisplay = display.driverData;
3134       //Logf("SetCamera\n");
3135
3136       if(camera)
3137       {
3138          int left = surface.box.left + surface.offset.x;
3139          int top = surface.box.top  + surface.offset.y;
3140          int right = surface.box.right + surface.offset.x;
3141          int bottom = surface.box.bottom + surface.offset.y;
3142          float origX = surface.offset.x + camera.origin.x;
3143          float origY = surface.offset.y + camera.origin.y;
3144          int x = left;
3145          int y = display.height - bottom - 1;
3146          int w = right - left + 1;
3147          int h = bottom - top + 1;
3148
3149          // *** ViewPort ***
3150          glViewport(x, y, w, h);
3151
3152          // *** Projection Matrix ***
3153          if(!display.display3D.camera)
3154             glPushMatrix();
3155          else
3156             glMatrixMode(GL_PROJECTION);
3157          if(display.display3D.collectingHits)
3158          {
3159             float pickX = display.display3D.pickX + surface.offset.x;
3160             float pickY = display.height - (display.display3D.pickY + surface.offset.y) - 1;
3161             Matrix pickMatrix = 
3162             {
3163                {
3164                   w / display.display3D.pickWidth, 0, 0, 0,
3165                   0, h / display.display3D.pickHeight, 0, 0,
3166                   0, 0, 1, 0,
3167                   (w + 2.0f * (x - pickX)) / display.display3D.pickWidth,
3168                   (h + 2.0f * (y - pickY)) / display.display3D.pickHeight, 0, 1
3169                }
3170             };
3171             glLoadMatrixd(pickMatrix.array);
3172          }
3173          else
3174             glLoadIdentity();
3175          glFrustum(
3176             (left   - origX) * camera.zMin / camera.focalX,
3177             (right  - origX) * camera.zMin / camera.focalX,
3178             (bottom - origY) * camera.zMin / camera.focalY,
3179             (top    - origY) * camera.zMin / camera.focalY,
3180             camera.zMin, camera.zMax);
3181
3182          glDisable(GL_BLEND);
3183
3184          // *** Z Inverted Identity Matrix ***
3185          glMatrixMode(GL_MODELVIEW);
3186          if(!display.display3D.camera)
3187             glPushMatrix();
3188
3189          glLoadIdentity();
3190          glScalef(1.0f, 1.0f, -1.0f);
3191
3192          // *** View Matrix ***
3193          glMultMatrixd(camera.viewMatrix.array);
3194
3195          // *** Lights ***
3196          // ...
3197
3198          glEnable(GL_DEPTH_TEST);
3199          glEnable(GL_LIGHTING);
3200          glShadeModel(GL_SMOOTH);
3201          glDepthMask((byte)bool::true);
3202          oglDisplay.depthWrite = true;
3203
3204          glEnable(GL_MULTISAMPLE_ARB);
3205       }
3206       else if(display.display3D.camera)
3207       {
3208          oglDisplay.depthWrite = false;
3209          glViewport(0,0,display.width,display.height);
3210
3211          glDisable(GL_CULL_FACE);
3212          glDisable(GL_DEPTH_TEST);
3213          glDisable(GL_LIGHTING);
3214          glDisable(GL_FOG);
3215          glDisable(GL_TEXTURE_2D);
3216          glShadeModel(GL_FLAT);
3217          glEnable(GL_BLEND);
3218          glDisable(GL_MULTISAMPLE_ARB);
3219
3220          // *** Restore 2D MODELVIEW Matrix ***
3221          glPopMatrix();
3222
3223          // *** Restore 2D PROJECTION Matrix ***
3224          glMatrixMode(GL_PROJECTION);
3225          glPopMatrix();
3226       }
3227
3228       if(glBindBufferARB)
3229          glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
3230    }
3231
3232    void ApplyMaterial(Display display, Material material, Mesh mesh)
3233    {
3234       //Logf("ApplyMaterial\n");
3235
3236       // Basic Properties
3237       if(material.flags.doubleSided)
3238       {
3239          glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, !material.flags.singleSideLight);
3240          glDisable(GL_CULL_FACE);
3241       }
3242       else
3243       {
3244          glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, bool::false);
3245          glEnable(GL_CULL_FACE);
3246       }
3247
3248       // Fog
3249       if(material.flags.noFog)
3250          glDisable(GL_FOG);
3251       else
3252          glEnable(GL_FOG);
3253
3254       // Maps
3255       if(material.baseMap && mesh.texCoords)
3256       {
3257          Bitmap map = material.baseMap;
3258          glEnable(GL_TEXTURE_2D);
3259          glBindTexture(GL_TEXTURE_2D, (uint)map.driverData);
3260
3261          if(material.flags.tile)
3262          {
3263             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
3264             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
3265          }
3266          else
3267          {
3268             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
3269             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
3270          }
3271       }
3272       else
3273          glDisable(GL_TEXTURE_2D);
3274
3275       if(mesh.flags.colors)
3276       {
3277          glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
3278          glEnable(GL_COLOR_MATERIAL);
3279       }
3280       else
3281       {
3282          glDisable(GL_COLOR_MATERIAL);
3283          {
3284             float color[4] = { material.diffuse.r, material.diffuse.g, material.diffuse.b, material.opacity };
3285             glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color);
3286          }
3287          {
3288             float color[4] = { material.ambient.r, material.ambient.g, material.ambient.b, 0 };
3289             glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color);
3290          }
3291       }
3292       {   
3293          float color[4] = { material.specular.r, material.specular.g, material.specular.b, 0 };
3294          glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, color);
3295       }
3296       {
3297          float color[4] = { material.emissive.r, material.emissive.g, material.emissive.b, 0 };
3298          glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, color);
3299       }
3300       
3301       glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &material.power);
3302    }
3303
3304    void FreeMesh(DisplaySystem displaySystem, Mesh mesh)
3305    {
3306       OGLMesh oglMesh = mesh.data;
3307       if(oglMesh)
3308       {
3309          if(!mesh.flags.vertices)
3310          {
3311             if(oglMesh.vertices)
3312             {
3313                glDeleteBuffersARB(1, &oglMesh.vertices);
3314                oglMesh.vertices = 0;
3315             }
3316             delete mesh.vertices;
3317          }
3318          if(!mesh.flags.normals)
3319          {
3320             if(oglMesh.normals)
3321             {
3322                glDeleteBuffersARB(1, &oglMesh.normals);
3323                oglMesh.normals = 0;
3324             }
3325             delete mesh.normals;
3326          }
3327          if(!mesh.flags.texCoords1)
3328          {
3329             if(oglMesh.texCoords)
3330             {
3331                glDeleteBuffersARB(1, &oglMesh.texCoords);
3332                oglMesh.texCoords = 0;
3333             }
3334             delete mesh.texCoords;
3335          }
3336          if(!mesh.flags.texCoords2)
3337          {
3338             if(oglMesh.texCoords2)
3339             {
3340                glDeleteBuffersARB(1, &oglMesh.texCoords2);
3341                oglMesh.texCoords2 = 0;
3342             }
3343             /*
3344             delete mesh.texCoords2;
3345             */
3346          }
3347          if(!mesh.flags.colors)
3348          {
3349             if(oglMesh.colors)
3350             {
3351                glDeleteBuffersARB(1, &oglMesh.colors);
3352                oglMesh.colors = 0;
3353             }
3354          }
3355          if(!mesh.flags)
3356          {
3357             delete oglMesh;
3358             mesh.data = null;
3359          }
3360       }
3361    }
3362
3363    bool AllocateMesh(DisplaySystem displaySystem, Mesh mesh)
3364    {
3365       bool result = false;
3366
3367       if(!mesh.data)
3368          mesh.data = OGLMesh { };
3369       if(mesh.data)
3370       {
3371          OGLMesh oglMesh = mesh.data;
3372
3373          if(mesh.flags.vertices && !oglMesh.vertices && !mesh.vertices)
3374          {
3375             mesh.vertices = mesh.flags.doubleVertices ? (Vector3Df *)new Vector3D[mesh.nVertices] : new Vector3Df[mesh.nVertices];
3376             if(glGenBuffersARB)
3377                glGenBuffersARB(1, &oglMesh.vertices);
3378          }
3379          if(mesh.flags.normals && !oglMesh.normals && !mesh.normals)
3380          {
3381             if(glGenBuffersARB)
3382                glGenBuffersARB( 1, &oglMesh.normals);
3383             mesh.normals = mesh.flags.doubleNormals ? (Vector3Df *)new Vector3D[mesh.nVertices] : new Vector3Df[mesh.nVertices];
3384          }
3385          if(mesh.flags.texCoords1 && !oglMesh.texCoords && !mesh.texCoords)
3386          {
3387             if(glGenBuffersARB)
3388                glGenBuffersARB( 1, &oglMesh.texCoords);
3389             mesh.texCoords = new Pointf[mesh.nVertices];
3390          }
3391          if(mesh.flags.colors && !oglMesh.colors && !mesh.colors)
3392          {
3393             if(glGenBuffersARB)
3394                glGenBuffersARB( 1, &oglMesh.colors);
3395             mesh.colors = new ColorRGBAf[mesh.nVertices];
3396          }
3397          result = true;
3398       }
3399       return result;
3400    }
3401
3402    void UnlockMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags)
3403    {
3404       OGLMesh oglMesh = mesh.data;
3405       if(!flags) flags = mesh.flags;
3406       
3407       if(glGenBuffersARB)
3408       {
3409          if(!(flags.vertices) || oglMesh.vertices)
3410          {
3411             glBindBufferARB( GL_ARRAY_BUFFER_ARB, oglMesh.vertices);
3412             glBufferDataARB( GL_ARRAY_BUFFER_ARB, mesh.nVertices * (mesh.flags.doubleVertices ? sizeof(Vector3D) : sizeof(Vector3Df)), mesh.vertices, GL_STATIC_DRAW_ARB );
3413          }
3414
3415          if(!(flags.normals) || oglMesh.normals)
3416          {
3417             glBindBufferARB( GL_ARRAY_BUFFER_ARB, oglMesh.normals);
3418             glBufferDataARB( GL_ARRAY_BUFFER_ARB, mesh.nVertices * (mesh.flags.doubleNormals ? sizeof(Vector3D) : sizeof(Vector3Df)), mesh.normals, GL_STATIC_DRAW_ARB );
3419          }
3420
3421          if(!(flags.texCoords1) || oglMesh.texCoords)
3422          {
3423             glBindBufferARB( GL_ARRAY_BUFFER_ARB, oglMesh.texCoords);
3424             glBufferDataARB( GL_ARRAY_BUFFER_ARB, mesh.nVertices * sizeof(Pointf), mesh.texCoords, GL_STATIC_DRAW_ARB );
3425          }
3426
3427          if(!(flags.colors) || oglMesh.colors)
3428          {
3429             glBindBufferARB( GL_ARRAY_BUFFER_ARB, oglMesh.colors);
3430             glBufferDataARB( GL_ARRAY_BUFFER_ARB, mesh.nVertices * sizeof(ColorRGBAf), mesh.colors, GL_STATIC_DRAW_ARB );
3431          }
3432
3433          glBindBufferARB( GL_ARRAY_BUFFER_ARB, 0);
3434       }
3435    }
3436
3437    bool LockMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags)
3438    {
3439       bool result = true;
3440
3441         return result;
3442    }
3443
3444    void FreeIndices(DisplaySystem displaySystem, OGLIndices oglIndices)
3445    {
3446       if(oglIndices)
3447       {
3448          if(oglIndices.buffer) 
3449             glDeleteBuffersARB(1, &oglIndices.buffer);
3450          delete oglIndices.indices;
3451          delete oglIndices;
3452       }
3453    }
3454
3455    void * AllocateIndices(DisplaySystem displaySystem, int nIndices, bool indices32bit)
3456    {
3457       OGLIndices oglIndices = OGLIndices { };
3458       if(oglIndices)
3459       {
3460          oglIndices.indices = (void *)(indices32bit ? new uint32[nIndices] : new uint16[nIndices]);
3461          if(glGenBuffersARB)
3462             glGenBuffersARB( 1, &oglIndices.buffer);
3463          oglIndices.nIndices = nIndices;
3464       }
3465       return oglIndices;
3466    }
3467
3468    void UnlockIndices(DisplaySystem displaySystem, OGLIndices oglIndices, bool indices32bit, int nIndices)
3469    {
3470       if(glGenBuffersARB)
3471       {
3472          glBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, oglIndices.buffer);
3473          glBufferDataARB( GL_ELEMENT_ARRAY_BUFFER_ARB, nIndices * (indices32bit ? sizeof(uint32) : sizeof(uint16)), 
3474             oglIndices.indices, GL_STATIC_DRAW_ARB);
3475          glBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
3476       }
3477    }
3478
3479    uint16 * LockIndices(DisplaySystem displaySystem, OGLIndices oglIndices)
3480    {
3481       
3482       return oglIndices.indices;
3483    }
3484
3485    void SelectMesh(Display display, Mesh mesh)
3486    {
3487       //Logf("SelectMesh\n");
3488
3489 #ifndef __ANDROID__
3490       if(display.display3D.mesh && glUnlockArraysEXT)   
3491          glUnlockArraysEXT();
3492 #endif
3493       if(mesh)
3494       {
3495          OGLDisplay oglDisplay = display.driverData;
3496          OGLMesh oglMesh = mesh.data;
3497
3498          // *** Vertex Stream ***
3499          glEnableClientState(GL_VERTEX_ARRAY);
3500          if(!display.display3D.collectingHits && oglMesh)
3501          {
3502             if(glBindBufferARB)
3503                glBindBufferARB(GL_ARRAY_BUFFER_ARB, oglMesh.vertices );
3504             glVertexPointer(3, mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT, 0, glBindBufferARB ? null : mesh.vertices);
3505
3506             // *** Normals Stream ***
3507             if(mesh.normals)
3508             {
3509                glEnableClientState(GL_NORMAL_ARRAY);
3510                if(glBindBufferARB)
3511                   glBindBufferARB(GL_ARRAY_BUFFER_ARB, oglMesh.normals);
3512                glNormalPointer(mesh.flags.doubleNormals ? GL_DOUBLE : GL_FLOAT, 0, glBindBufferARB ? null : mesh.normals);
3513             }
3514             else
3515                glDisableClientState(GL_NORMAL_ARRAY);
3516
3517             // *** Texture Coordinates Stream ***
3518             if(mesh.texCoords)
3519             {
3520                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
3521                if(glBindBufferARB)
3522                   glBindBufferARB( GL_ARRAY_BUFFER_ARB, oglMesh.texCoords);
3523                glTexCoordPointer(2, GL_FLOAT, 0, glBindBufferARB ? null : mesh.texCoords);
3524             }
3525             else
3526                glDisableClientState(GL_TEXTURE_COORD_ARRAY);
3527
3528             // *** Color Stream ***
3529             if(mesh.colors)
3530             {
3531                glEnableClientState(GL_COLOR_ARRAY);
3532                if(glBindBufferARB)
3533                   glBindBufferARB( GL_ARRAY_BUFFER_ARB, oglMesh.colors);
3534                glColorPointer(4, GL_FLOAT, 0, glBindBufferARB ? null : mesh.colors);
3535             }
3536             else
3537                glDisableClientState(GL_COLOR_ARRAY);
3538
3539          }
3540          else
3541          {
3542             if(glBindBufferARB)
3543                glBindBufferARB( GL_ARRAY_BUFFER_ARB, 0);
3544             glVertexPointer(3,mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT,0,mesh.vertices);
3545             if(mesh.normals && !display.display3D.collectingHits)
3546             {
3547                glEnableClientState(GL_NORMAL_ARRAY);
3548                glNormalPointer(mesh.flags.doubleNormals ? GL_DOUBLE : GL_FLOAT, 0, mesh.normals);
3549             }
3550             else
3551                glDisableClientState(GL_NORMAL_ARRAY);
3552             if(mesh.texCoords && !display.display3D.collectingHits)
3553             {
3554                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
3555                glTexCoordPointer(2, GL_FLOAT, 0, mesh.texCoords);
3556             }
3557             else
3558                glDisableClientState(GL_TEXTURE_COORD_ARRAY);
3559             if(mesh.colors && !display.display3D.collectingHits)
3560             {
3561                glEnableClientState(GL_COLOR_ARRAY);
3562                glColorPointer(4, GL_FLOAT, 0, mesh.colors);
3563             }
3564             else
3565                glDisableClientState(GL_COLOR_ARRAY);
3566          }
3567
3568 #ifndef __ANDROID__
3569          if(glLockArraysEXT) glLockArraysEXT(0, mesh.nVertices);
3570 #endif
3571       }
3572       else if(glBindBufferARB)
3573          glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
3574    }
3575
3576    void DrawPrimitives(Display display, PrimitiveSingle * primitive, Mesh mesh)
3577    {
3578       OGLDisplay oglDisplay = display.driverData;
3579       //Logf("DrawPrimitives\n");
3580
3581       if(primitive->type.vertexRange)
3582          glDrawArrays(primitiveTypes[primitive->type.primitiveType], primitive->first, primitive->nVertices);
3583       else
3584       {
3585          //    *** Hoping the data won't be uploaded at all (Won't really work if another group of the mesh is using the mesh ) *** 
3586          // HACK TO SPEED THINGS UP...
3587          if(primitive->nIndices < (mesh.nVertices >> 2) && !primitive->type.indices32bit)
3588          {
3589             int c;
3590             glBegin(primitiveTypes[primitive->type.primitiveType]);
3591             if(primitive->data)
3592             {
3593                OGLIndices oglIndices = primitive->data;
3594                MeshFeatures flags = mesh.flags;
3595                for(c = 0; c<primitive->nIndices; c++)
3596                {
3597                   short index = ((short *) oglIndices.indices)[c];
3598                   if(flags.normals) glNormal3fv((float *)&mesh.normals[index]);
3599                   if(flags.texCoords1) glTexCoord2fv((float *)&mesh.texCoords[index]);
3600                   if(flags.colors) glColor4fv((float *)&mesh.colors[index]);
3601                   glVertex3fv((float *)&mesh.vertices[index]);
3602                }
3603             }
3604             glEnd();
3605          }
3606          else
3607          {
3608             OGLIndices oglIndices = primitive->data;
3609
3610             if(!display.display3D.collectingHits && glBindBufferARB && oglIndices)
3611             {
3612                glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, oglIndices.buffer);
3613                glDrawElements(primitiveTypes[primitive->type.primitiveType], primitive->nIndices, 
3614                   primitive->type.indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0);
3615                glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
3616             }
3617             else if(oglIndices)
3618                glDrawElements(primitiveTypes[primitive->type.primitiveType], primitive->nIndices, 
3619                   primitive->type.indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, oglIndices.indices);
3620             else
3621                glDrawElements(primitiveTypes[primitive->type.primitiveType], primitive->nIndices, 
3622                   primitive->type.indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, primitive->indices);
3623          }
3624       }
3625    }
3626
3627    void PushMatrix(Display display)
3628    {
3629       glPushMatrix();
3630    }
3631
3632    void PopMatrix(Display display, bool setMatrix)
3633    {
3634       glPopMatrix();
3635    }
3636
3637    void SetTransform(Display display, Matrix transMatrix, bool viewSpace, bool useCamera)
3638    {
3639       Matrix matrix = transMatrix;
3640       Camera camera = useCamera ? display.display3D.camera : null;
3641
3642       if(viewSpace)
3643       {
3644          glLoadIdentity();
3645          glScalef(1.0f, 1.0f, -1.0f);
3646       }
3647       else if(camera)
3648       {
3649          glTranslated(
3650             matrix.m[3][0] - camera.cPosition.x,
3651             matrix.m[3][1] - camera.cPosition.y,
3652             matrix.m[3][2] - camera.cPosition.z);
3653       }
3654       else
3655          glTranslated(
3656             matrix.m[3][0],
3657             matrix.m[3][1],
3658             matrix.m[3][2]);
3659
3660       matrix.m[3][0] = 0;
3661       matrix.m[3][1] = 0;
3662       matrix.m[3][2] = 0;
3663
3664       glMultMatrixd(matrix.array);
3665    }
3666 }
3667
3668 public void UseSingleGLContext(bool useSingle)
3669 {
3670    useSingleGLContext = useSingle;
3671 }
3672
3673 #endif