ecere/gfx/newFonts: Warning Fixes
[sdk] / ecere / src / gfx / newFonts / drawManager.ec
1 import "OpenGLDisplayDriver"
2
3 #include <stdio.h>
4 #include <math.h>
5 #include <stdlib.h>
6
7 #if defined(_GLES)
8    #define ES1_1
9 #else
10    #define SHADERS
11 #endif
12
13 #if !defined(__ANDROID__) && !defined(__EMSCRIPTEN__) && !defined(__ODROID__)
14 #  if defined(SHADERS)
15 //#     include "gl_core_3_3.h"
16 #     include "gl_compat_4_4.h"     // FIXME: no glPushAttrib() in core profile
17 #  else
18 #     include "gl_compat_4_4.h"
19 #  endif
20 #endif
21
22 #ifdef SHADERS
23
24 #undef glEnableClientState
25 #undef glDisableClientState
26 #undef GL_VERTEX_ARRAY
27 #undef GL_NORMAL_ARRAY
28 #undef GL_TEXTURE_COORD_ARRAY
29 #undef GL_COLOR_ARRAY
30 #undef glVertexPointer
31 #undef glTexCoordPointer
32 #undef glColorPointer
33
34 #define glEnableClientState      glEnableVertexAttribArray
35 #define glDisableClientState     glDisableVertexAttribArray
36 #define GL_VERTEX_ARRAY          GLBufferContents::vertex
37 #define GL_NORMAL_ARRAY          GLBufferContents::normal
38 #define GL_TEXTURE_COORD_ARRAY   GLBufferContents::texCoord
39 #define GL_COLOR_ARRAY           GLBufferContents::color
40 #define glVertexPointer(n, t, s, p)    glVertexAttribPointer(GLBufferContents::vertex,   n, t, GL_FALSE, s, p)
41 #define glTexCoordPointer(n, t, s, p)  glVertexAttribPointer(GLBufferContents::texCoord, n, t, GL_FALSE, s, p)
42 #define glColorPointer(n, t, s, p)     glVertexAttribPointer(GLBufferContents::color,    n, t, GL_FALSE, s, p)
43
44 #endif
45
46 #if defined(ES1_1) || defined(ES2) || defined(SHADERS)
47
48    #undef glRecti
49    #undef glBegin
50    #undef glTexCoord2i
51    #undef glVertex2i
52    #undef glTexCoord2d
53    #undef glVertex2d
54    #undef glTexCoord2f
55    #undef glVertex2f
56    #undef glEnd
57    #undef glColor3f
58    #undef glColor4ub
59    #undef glColor4fv
60    #undef glNormal3fv
61    #undef glNormal3f
62    #undef glTexCoord2fv
63    #undef glVertex3d
64    #undef glVertex3dv
65    #undef glVertex3f
66    #undef glVertex3fv
67
68    #undef glLoadMatrixd
69    #undef glMultMatrixd
70    #undef glFrustum
71    #undef glOrtho
72    #undef glScaled
73    #undef glScalef
74    #undef glTranslated
75    #undef glRotated
76    #undef glMatrixMode
77    #undef glLoadIdentity
78    #undef glPushMatrix
79    #undef glPopMatrix
80
81    #undef glLineStipple
82    #undef glColorMaterial
83    #undef glLightModeli
84
85    #define glRecti               glimtkRecti
86    #define glBegin               glimtkBegin
87    #define glTexCoord2i          glimtkTexCoord2i
88    #define glVertex2i            glimtkVertex2i
89    #define glTexCoord2d          glimtkTexCoord2d
90    #define glVertex2d            glimtkVertex2d
91    #define glTexCoord2f          glimtkTexCoord2f
92    #define glVertex2f            glimtkVertex2f
93    #define glEnd                 glimtkEnd
94    #define glColor3f             glimtkColor3f
95    #define glColor4ub            glimtkColor4ub
96    #define glColor4fv            glimtkColor4fv
97    #define glNormal3fv           glimtkNormal3fv
98    #define glNormal3f            glimtkNormal3f
99    #define glTexCoord2fv         glimtkTexCoord2fv
100    #define glVertex3d            glimtkVertex3d
101    #define glVertex3dv           glimtkVertex3dv
102    #define glVertex3f            glimtkVertex3f
103    #define glVertex3fv           glimtkVertex3fv
104
105    #define glLoadMatrixd         glmsLoadMatrixd
106    #define glMultMatrixd         glmsMultMatrixd
107    #define glFrustum             glmsFrustum
108    #define glOrtho               glmsOrtho
109    #define glScaled              glmsScaled
110    #define glScalef              glmsScaled
111    #define glTranslated          glmsTranslated
112    #define glRotated             glmsRotated
113    #define glMatrixMode          glmsMatrixMode
114    #define glLoadIdentity        glmsLoadIdentity
115    #define glPushMatrix          glmsPushMatrix
116    #define glPopMatrix           glmsPopMatrix
117
118    #define glLineStipple         glesLineStipple
119    #define glColorMaterial       glesColorMaterial
120    #define glLightModeli         glesLightModeli
121
122 #endif
123
124 #include "cc.h"
125
126 #define OFFSET(s, m) ((uint)(uintptr) (&((s *) 0)->m))
127
128 import "textureManager"
129
130
131 #define DM_ENABLE_IMAGE_ROTATION (1)
132 #define DM_ENABLE_EXT_COLOR (1)
133
134 ////
135
136 static struct DMDrawVertexFlat
137 {
138   float vertex[2];
139   float texcoord0[2];
140   uint32 color;
141 #if DM_ENABLE_EXT_COLOR
142   uint32 extcolor;
143 #endif
144 } __attribute__((aligned(16)));
145
146 static struct DMDrawVertex
147 {
148   short vertex[2];
149   short texcoord0[2];
150   uint32 color;
151 #if DM_ENABLE_EXT_COLOR
152   uint32 extcolor;
153 #endif
154 } __attribute__((aligned(16)));
155
156 struct DMDrawBuffer
157 {
158    GLuint vbo;
159    int glType;
160    int vertexCount;
161    int vertexAlloc;
162    void *vertexBuffer;
163 };
164
165 class DMProgramFlags : uint { bool valid:1; }
166
167 struct DMProgram
168 {
169   GLuint glProgram;
170   GLuint vertexShader;
171   GLuint fragmentShader;
172   GLint matrixloc;
173   GLint vertexloc;
174   GLint texcoord0loc;
175   GLint texcoord1loc;
176   GLint colorloc;
177 #if DM_ENABLE_EXT_COLOR
178   GLint extcolorloc;
179 #endif
180   GLint texbaseloc;
181   DMProgramFlags flags;
182   int64 lastUpdateCount;
183 };
184
185 class DMImageFlags : uint16
186 {
187    bool empty:1;     // Image is empty, do not draw
188    bool blending:1;  // Must draw image with blending
189 }
190
191 public struct DMImage
192 {
193 private:
194    Texture texture;
195    DMImageFlags flags;
196    short programIndex;
197    short srcx, srcy;
198    short sizex, sizey;
199
200    // Computed order for sorted rendering, in defineImage()
201    uint32 orderMask;
202
203 public:
204    void clear()
205    {
206       this = { flags = { empty = true } };
207    }
208
209    void defineImage( Texture texture, int offsetx, int offsety, int sizex, int sizey, bool blending, int programIndex, int layerindex )
210    {
211       int ordx = offsetx >> 6;
212       int ordy = offsety >> 6;
213       uint32 orderimage = ccMortonNumber32( ordx, ordy ) & ( ( 1 << DM_IMAGE_ORDER_BITS ) - 1 );
214       this =
215       {
216          texture = texture;
217          srcx = (short)offsetx;
218          srcy = (short)offsety;
219          sizex = (short)sizex;
220          sizey = (short)sizey;
221          programIndex = (short)programIndex;
222          flags = { blending = blending };
223          orderMask = (orderimage << DM_IMAGE_ORDER_SHIFT) |
224                      (( blending == true ) << DM_BLEND_ORDER_SHIFT) |
225                      (programIndex << DM_PROGRAM_ORDER_SHIFT) |
226                      texture.orderMask |
227                      (layerindex << DM_LAYER_ORDER_SHIFT);
228       };
229    }
230 };
231
232 struct DMImageBuffer
233 {
234   DMImage *image;
235   short offsetx;
236   short offsety;
237   short sizex;
238   short sizey;
239 #if DM_ENABLE_IMAGE_ROTATION
240   short angcos;
241   short angsin;
242 #endif
243 #if DM_ENABLE_EXT_COLOR
244   uint32 extcolor;
245 #endif
246   uint32 color;
247   uint32 orderindex;
248 };
249
250
251 ////
252
253
254 define DM_IMAGE_ORDER_BITS = 8;
255 define DM_BLEND_ORDER_BITS = 1;
256 define DM_PROGRAM_ORDER_BITS = 4;
257 define DM_TEXTURE_ORDER_BITS = 10;
258 define DM_LAYER_ORDER_BITS = 4;
259 define DM_BARRIER_ORDER_BITS = 5;
260
261 define DM_IMAGE_ORDER_SHIFT = 0;
262 define DM_BLEND_ORDER_SHIFT = DM_IMAGE_ORDER_BITS;
263 define DM_PROGRAM_ORDER_SHIFT = DM_IMAGE_ORDER_BITS+DM_BLEND_ORDER_BITS;
264 define DM_TEXTURE_ORDER_SHIFT = DM_IMAGE_ORDER_BITS+DM_BLEND_ORDER_BITS+DM_PROGRAM_ORDER_BITS;
265 define DM_LAYER_ORDER_SHIFT = DM_IMAGE_ORDER_BITS+DM_BLEND_ORDER_BITS+DM_PROGRAM_ORDER_BITS+DM_TEXTURE_ORDER_BITS;
266 define DM_BARRIER_ORDER_SHIFT = DM_IMAGE_ORDER_BITS+DM_BLEND_ORDER_BITS+DM_PROGRAM_ORDER_BITS+DM_TEXTURE_ORDER_BITS+DM_LAYER_ORDER_BITS;
267
268 define DM_LAYER_COUNT = 1<<DM_LAYER_ORDER_BITS;
269 define DM_PROGRAM_COUNT = 1<<DM_PROGRAM_ORDER_BITS;
270
271 define DM_CONTEXT_DRAW_BUFFER_COUNT = 64;
272 define DM_CONTEXT_DRAW_BUFFER_VERTEX_ALLOC = 1024;
273
274
275 /* Range is from zero to DM_LAYER_COUNT */
276 enum DMLayer
277 {
278   DM_LAYER_0_BOTTOM,
279   DM_LAYER_1_BOTTOM,
280   DM_LAYER_2_BELOW,
281   DM_LAYER_3_BELOW,
282   DM_LAYER_4_BELOW,
283   DM_LAYER_5_NORMAL,
284   DM_LAYER_6_NORMAL,
285   DM_LAYER_7_NORMAL,
286   DM_LAYER_8_ABOVE,
287   DM_LAYER_9_ABOVE,
288   DM_LAYER_10_ABOVE,
289   DM_LAYER_11_OVERLAY,
290   DM_LAYER_12_OVERLAY,
291   DM_LAYER_13_OVERLAY,
292   DM_LAYER_14_TOP,
293   DM_LAYER_15_TOP,
294 };
295
296 define DM_LAYER_BOTTOM = DMLayer::DM_LAYER_0_BOTTOM;
297 define DM_LAYER_BELOW = DMLayer::DM_LAYER_3_BELOW;
298 define DM_LAYER_NORMAL = DMLayer::DM_LAYER_6_NORMAL;
299 define DM_LAYER_ABOVE = DMLayer::DM_LAYER_9_ABOVE;
300 define DM_LAYER_TOP = DMLayer::DM_LAYER_15_TOP;
301
302 define DM_PROGRAM_NORMAL = 0;
303 define DM_PROGRAM_ALPHABLEND = 1;
304 define DM_PROGRAM_ALPHABLEND_INTENSITY = 2;
305 define DM_PROGRAM_ALPHABLEND_INTENSITY_EXTCOLOR = 3;
306
307 #ifdef _DEBUG
308 static inline void OpenGLErrorCheck( const char *file, int line )
309 {
310    int error = glGetError();
311    if( error != GL_NO_ERROR )
312       printf( "ERROR %d at %s:%d\n", error, file, line );
313 }
314
315 #define ERRORCHECK() OpenGLErrorCheck(__FILE__,__LINE__)
316 #else
317 #define ERRORCHECK()
318 #endif
319
320 // Not using 32767.0 ; overflow when converting to int16 due to floating point crud causes problems
321 #define DM_IMAGE_ROTATION_NORMFACTOR (24576.0f)
322
323 #define DM_VERTEX_NORMSHIFT (2)
324 #define DM_VERTEX_NORMFACTOR (4.0f)
325
326 #define DM_TEXCOORD_NORMSHIFT (13)
327 #define DM_TEXCOORD_NORMFACTOR (8192.0f)
328
329 static GLuint dmCreateShader( GLenum type, const char *shadersource, const char *optionstring )
330 {
331   GLuint shader;
332   GLint status;
333   GLsizei loglength;
334   char infolog[8192];
335   const GLchar *sourcearray[2];
336
337   shader = glCreateShader( type );
338   if( !( shader ) )
339     return 0;
340
341   if( !( optionstring ) )
342     optionstring = "";
343   sourcearray[0] = optionstring;
344   sourcearray[1] = shadersource;
345   glShaderSource( shader, 2, sourcearray, NULL );
346   glCompileShader( shader );
347   glGetShaderiv( shader, GL_COMPILE_STATUS, &status );
348   if( status != GL_TRUE )
349   {
350     fprintf( stderr, "ERROR: Failed to compile shader\n" );
351     glGetShaderInfoLog( shader, 8192, &loglength,infolog );
352     fprintf( stderr, "ERROR: \n%s\n\n", infolog );
353     glDeleteShader( shader );
354     return 0;
355   }
356   return shader;
357 }
358
359
360 static bool dmCreateProgram( DMProgram program, const char *vertexsource, const char *fragmentsource, char *optionstring )
361 {
362   GLint status;
363   GLsizei loglength;
364   char infolog[8192];
365
366   program.glProgram = 0;
367   program.vertexShader = 0;
368   program.fragmentShader = 0;
369
370   program.vertexShader = dmCreateShader( GL_VERTEX_SHADER, vertexsource, optionstring );
371   if( !( program.vertexShader ) )
372   {
373     fprintf(stderr, "ERROR: Unable to load vertex shader\n");
374     goto error;
375   }
376   program.fragmentShader = dmCreateShader( GL_FRAGMENT_SHADER, fragmentsource, optionstring );
377   if( !( program.fragmentShader ) )
378   {
379     fprintf(stderr, "ERROR: Unable to load fragment shader\n");
380     goto error;
381   }
382   program.glProgram = glCreateProgram();
383   if( !( program.glProgram ) )
384   {
385     fprintf(stderr, "ERROR: Unable to create program\n");
386     goto error;
387   }
388
389   glAttachShader( program.glProgram, program.vertexShader );
390   glAttachShader( program.glProgram, program.fragmentShader );
391
392    glBindAttribLocation(program.glProgram, GLBufferContents::vertex, "vertex");
393    glBindAttribLocation(program.glProgram, GLBufferContents::texCoord, "texCoord");
394    glBindAttribLocation(program.glProgram, GLBufferContents::color, "color");
395    glBindAttribLocation(program.glProgram, GLBufferContents::normal, "normal");
396
397   glLinkProgram( program.glProgram );
398   glGetProgramiv( program.glProgram, GL_LINK_STATUS, &status );
399   if( status != GL_TRUE )
400   {
401     fprintf( stderr, "ERROR, failed to link shader program\n" );
402     glGetProgramInfoLog( program.glProgram, 8192, &loglength, infolog );
403     fprintf( stderr, "ERROR: \n%s\n\n", infolog );
404     goto error;
405   }
406
407   // glUseProgram( program.glProgram );
408
409   program.matrixloc = glGetUniformLocation( program.glProgram, "uniMatrix" );
410   program.vertexloc = glGetAttribLocation( program.glProgram, "inVertex" );
411   program.texcoord0loc = glGetAttribLocation( program.glProgram, "inTexcoord0" );
412   program.texcoord1loc = glGetAttribLocation( program.glProgram, "inTexcoord1" );
413   program.colorloc = glGetAttribLocation( program.glProgram, "inColor" );
414 #if DM_ENABLE_EXT_COLOR
415   program.extcolorloc = glGetAttribLocation( program.glProgram, "inExtColor" );
416 #endif
417   program.texbaseloc = glGetUniformLocation( program.glProgram, "texBase" );
418   program.flags.valid = true;
419
420   return true;
421
422   error:
423   if( program.fragmentShader )
424     glDeleteShader( program.fragmentShader );
425   if( program.vertexShader )
426     glDeleteShader( program.vertexShader );
427   if( program.glProgram )
428     glDeleteProgram( program.glProgram );
429   return false;
430 }
431
432
433 ////
434
435
436 const char *dmVertexShaderNormal =
437 "#version 130\n"
438 "uniform mat4 uniMatrix;\n"
439 "in vec2 inVertex;\n"
440 "in vec2 inTexcoord0;\n"
441 "in vec4 inColor;\n"
442 "out vec2 varTexcoord0;\n"
443 "out vec4 varColor;\n"
444 "void main()\n"
445 "{\n"
446 " \n"
447 "  varTexcoord0 = inTexcoord0 * (1.0/" CC_STRINGIFY(DM_TEXCOORD_NORMFACTOR) ");\n"
448 "  varColor = inColor;\n"
449 "  gl_Position = uniMatrix * vec4( inVertex, 0.0, 1.0 );\n"
450 "  return;\n"
451 "}\n"
452 ;
453
454
455 const char *dmFragmentShaderNormal =
456 "#version 130\n"
457 "uniform sampler2D texBase;\n"
458 "in vec2 varTexcoord0;\n"
459 "in vec4 varColor;\n"
460 "void main()\n"
461 "{\n"
462 "  gl_FragColor = varColor * texture2D( texBase, varTexcoord0 );\n"
463 "  return;\n"
464 "}\n"
465 ;
466
467
468 const char *dmVertexShaderAlpha =
469 "#version 130\n"
470 "uniform mat4 uniMatrix;\n"
471 "in vec2 inVertex;\n"
472 "in vec2 inTexcoord0;\n"
473 "in vec4 inColor;\n"
474 "out vec2 varTexcoord0;\n"
475 "out vec4 varColor;\n"
476 "void main()\n"
477 "{\n"
478 " \n"
479 "  varTexcoord0 = inTexcoord0 * (1.0/" CC_STRINGIFY(DM_TEXCOORD_NORMFACTOR) ");\n"
480 "  varColor = inColor;\n"
481 "  gl_Position = uniMatrix * vec4( inVertex, 0.0, 1.0 );\n"
482 "  return;\n"
483 "}\n"
484 ;
485
486
487 const char *dmFragmentShaderAlpha =
488 "#version 130\n"
489 "uniform sampler2D texBase;\n"
490 "in vec2 varTexcoord0;\n"
491 "in vec4 varColor;\n"
492 "void main()\n"
493 "{\n"
494 "  gl_FragColor = vec4( varColor.rgb, varColor.a * texture2D( texBase, varTexcoord0 ).r );\n"
495 "  return;\n"
496 "}\n"
497 ;
498
499 const char *dmVertexShaderAlphaIntensity =
500 "#version 130\n"
501 "uniform mat4 uniMatrix;\n"
502 "in vec2 inVertex;\n"
503 "in vec2 inTexcoord0;\n"
504 "in vec4 inColor;\n"
505 "out vec2 varTexcoord0;\n"
506 "out vec4 varColor;\n"
507 "void main()\n"
508 "{\n"
509 " \n"
510 "  varTexcoord0 = inTexcoord0 * (1.0/" CC_STRINGIFY(DM_TEXCOORD_NORMFACTOR) ");\n"
511 "  varColor = inColor;\n"
512 "  gl_Position = uniMatrix * vec4( inVertex, 0.0, 1.0 );\n"
513 "  return;\n"
514 "}\n"
515 ;
516
517
518 const char *dmFragmentShaderAlphaIntensity =
519 "#version 130\n"
520 "uniform sampler2D texBase;\n"
521 "in vec2 varTexcoord0;\n"
522 "in vec4 varColor;\n"
523 "void main()\n"
524 "{\n"
525 "  vec2 tex;\n"
526 "  tex = texture2D( texBase, varTexcoord0 ).rg;\n"
527 "  gl_FragColor = vec4( varColor.rgb * tex.g, varColor.a * tex.r );\n"
528 "  return;\n"
529 "}\n"
530 ;
531
532 const char *dmVertexShaderAlphaIntensityExtColor =
533 "#version 130\n"
534 "uniform mat4 uniMatrix;\n"
535 "in vec2 inVertex;\n"
536 "in vec2 inTexcoord0;\n"
537 "in vec4 inColor;\n"
538 "in vec4 inExtColor;\n"
539 "out vec2 varTexcoord0;\n"
540 "out vec4 varColor;\n"
541 "out vec4 varExtColor;\n"
542 "void main()\n"
543 "{\n"
544 " \n"
545 "  varTexcoord0 = inTexcoord0 * (1.0/" CC_STRINGIFY(DM_TEXCOORD_NORMFACTOR) ");\n"
546 "  varColor = inColor;\n"
547 "  varExtColor = inExtColor;\n"
548 "  gl_Position = uniMatrix * vec4( inVertex, 0.0, 1.0 );\n"
549 "  return;\n"
550 "}\n"
551 ;
552
553
554 const char *dmFragmentShaderAlphaIntensityExtColor =
555 "#version 130\n"
556 "uniform sampler2D texBase;\n"
557 "in vec2 varTexcoord0;\n"
558 "in vec4 varColor;\n"
559 "in vec4 varExtColor;\n"
560 "void main()\n"
561 "{\n"
562 "  vec2 tex;\n"
563 "  tex = texture2D( texBase, varTexcoord0 ).rg;\n"
564 "  gl_FragColor = vec4( mix( varExtColor.rgb, varColor.rgb, tex.g ), mix( varExtColor.a, varColor.a, tex.g ) * tex.r );\n"
565 "  return;\n"
566 "}\n"
567 ;
568
569 ////
570
571
572 static void matrixOrtho( float *m, float left, float right, float bottom, float top, float nearval, float farval )
573 {
574   float x = 2.0f / ( right - left );
575   float y = 2.0f / ( top - bottom );
576   float z = -2.0f / ( farval - nearval );
577   float tx = -( right + left ) / ( right - left );
578   float ty = -( top + bottom ) / ( top - bottom );
579   float tz = -( farval + nearval ) / ( farval - nearval );
580
581 #define M(row,col)  m[col*4+row]
582   M(0,0) = x;    M(0,1) = 0.0;  M(0,2) = 0.0;  M(0,3) = tx;
583   M(1,0) = 0.0;  M(1,1) = y;     M(1,2) = 0.0;  M(1,3) = ty;
584   M(2,0) = 0.0;  M(2,1) = 0.0;  M(2,2) = z;     M(2,3) = tz;
585   M(3,0) = 0.0;  M(3,1) = 0.0;  M(3,2) = 0.0;  M(3,3) = 1.0;
586 #undef M
587 }
588
589 ////
590
591
592 /* FIXME: Radix sort, not hybrid sort! */
593
594 static inline int dmSortImagesCmp( DMImageBuffer *draw0, DMImageBuffer *draw1 )
595 {
596   return ( ( draw0->orderindex < draw1->orderindex ) ? 0 : 1 );
597 }
598
599 #define HSORT_MAIN dmSortImages
600 #define HSORT_CMP dmSortImagesCmp
601 #define HSORT_TYPE DMImageBuffer
602 #include "cchybridsort.h"
603 #undef HSORT_MAIN
604 #undef HSORT_CMP
605 #undef HSORT_TYPE
606
607
608 ////
609
610 // TOFIX: Make this private, have a property
611 public class DrawManagerFlags : uint32 { public: bool prehistoricOpenGL:1; }
612
613 public class DrawManager
614 {
615    DrawManagerFlags flags;
616    DMProgram shaderPrograms[DM_PROGRAM_COUNT];
617
618    // Matrix
619    float matrix[16];
620
621    int imageBufferCount;
622    int imageBufferSize;
623    DMImageBuffer *imageBuffer;
624    DMImageBuffer *imageBufferTmp;
625
626    // Buffers for drawimages() batching
627    DMDrawBuffer drawBuffer[DM_CONTEXT_DRAW_BUFFER_COUNT];
628    int drawBufferIndex;
629    int drawBarrierIndex;
630    uint32 orderBarrierMask;
631
632    // Counter to track program uniforms and such
633    int64 updateCount;
634
635    GLuint prevProgram;
636
637    static DMProgram *flushUseProgram( int programIndex )
638    {
639       DMProgram *program = &shaderPrograms[ programIndex ];
640       if( !program->flags.valid)
641       {
642          glUseProgram( 0 );
643          return 0;
644       }
645
646       glUseProgram( program->glProgram );
647       if( program->lastUpdateCount != this.updateCount )
648       {
649          glUniformMatrix4fv( program->matrixloc, 1, GL_FALSE, this.matrix );
650          glUniform1i( program->texbaseloc, 0 );
651          program->lastUpdateCount = this.updateCount;
652       }
653
654       return program;
655    }
656
657    static void flushRenderDrawBufferArchaic( DMDrawBuffer drawBuffer, DMProgram program, int vertexCount )
658    {
659       glEnable( GL_TEXTURE_2D );
660       glBindBuffer( GL_ARRAY_BUFFER, drawBuffer.vbo );
661       glColor3f( 1.0, 1.0, 1.0 );
662
663       glEnableClientState( GL_VERTEX_ARRAY );
664       glEnableClientState( GL_TEXTURE_COORD_ARRAY );
665       glEnableClientState( GL_COLOR_ARRAY );
666
667       glVertexPointer( 2, GL_FLOAT, sizeof(DMDrawVertexFlat), (void *)OFFSET(DMDrawVertexFlat,vertex) );
668       glTexCoordPointer( 2, GL_FLOAT, sizeof(DMDrawVertexFlat), (void *)OFFSET(DMDrawVertexFlat,texcoord0) );
669       glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof(DMDrawVertexFlat), (void *)OFFSET(DMDrawVertexFlat,color) );
670
671       glDrawArrays( GL_TRIANGLES, 0, vertexCount );
672
673       glDisableClientState( GL_VERTEX_ARRAY );
674       glDisableClientState( GL_TEXTURE_COORD_ARRAY );
675       glDisableClientState( GL_COLOR_ARRAY );
676       glDisable( GL_TEXTURE_2D );
677
678    #if DM_FLUSH_EACH_RENDER_DRAW_BUFFER
679       glFlush();
680    #endif
681    }
682
683    void flushDrawImagesArchaic( )
684    {
685      bool flushflag, stateBlend;
686      int index, vertexCount, programIndex;
687      float vx0, vx1, vx2, vx3, vy0, vy1, vy2, vy3;
688    #if DM_ENABLE_IMAGE_ROTATION
689      float angsin, angcos, sizex, sizey;
690    #endif
691      float tx0, tx1, ty0, ty1;
692      DMImageBuffer *imageBuffer;
693      DMImage *image, *bindimage;
694      Texture texture, bindTexture;
695      DMDrawBuffer *drawBuffer;
696      DMDrawVertexFlat *vboVertex;
697      DMProgram *program;
698
699      ERRORCHECK();
700
701      drawBarrierIndex = 0;
702      orderBarrierMask = drawBarrierIndex << DM_BARRIER_ORDER_SHIFT;
703      if(imageBufferCount)
704      {
705         // Sort by image type and texture, minimize state changes
706         dmSortImages( this.imageBuffer, imageBufferTmp, imageBufferCount, (uint32)( (intptr_t)this.imageBuffer >> 4 ) );
707
708         // Fill a drawBuffer, write vertex and texcoords
709         drawBuffer = &this.drawBuffer[drawBufferIndex];
710         drawBufferIndex = ( drawBufferIndex + 1 ) % DM_CONTEXT_DRAW_BUFFER_COUNT;
711         glBindBuffer( GL_ARRAY_BUFFER, drawBuffer->vbo );
712         vboVertex = glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY );
713         vertexCount = 0;
714
715         glActiveTexture( GL_TEXTURE0 );
716         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
717         glDisable( GL_BLEND );
718
719       #if DM_RENDER_IMAGE_DEBUG
720       printf( " Flush %d images\n", (int)imageBufferCount );
721       #endif
722
723         bindimage = 0;
724         bindTexture = 0;
725         stateBlend = 0;
726         programIndex = -1;
727         program = 0;
728         imageBuffer = this.imageBuffer;
729         for( index = 0 ; index < imageBufferCount ; index++, imageBuffer++ )
730         {
731           image = imageBuffer->image;
732           texture = image->texture;
733
734           flushflag = 0;
735           if( image != bindimage )
736           {
737             if( stateBlend != image->flags.blending )
738               flushflag = 1;
739             if( texture != bindTexture )
740               flushflag = 1;
741           }
742           if( vertexCount >= ( drawBuffer->vertexAlloc - 6 ) )
743             flushflag = 1;
744
745           if( flushflag )
746           {
747             if( vertexCount )
748             {
749               glUnmapBuffer( GL_ARRAY_BUFFER );
750               // Flush font manager texture updates
751               flush( );
752               // Render buffered images
753               flushRenderDrawBufferArchaic( drawBuffer, program, vertexCount );
754               drawBuffer = &this.drawBuffer[drawBufferIndex];
755               drawBufferIndex = ( drawBufferIndex + 1 ) % DM_CONTEXT_DRAW_BUFFER_COUNT;
756               glBindBuffer( GL_ARRAY_BUFFER, drawBuffer->vbo );
757               vboVertex = glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY );
758               vertexCount = 0;
759             }
760
761             if( stateBlend != ( image->flags.blending ) )
762             {
763               stateBlend = image->flags.blending;
764               ( stateBlend ? glEnable : glDisable )( GL_BLEND );
765       #if DM_RENDER_IMAGE_DEBUG
766       printf( "  Switch blending %d\n", stateBlend != false );
767       #endif
768             }
769             if( programIndex != image->programIndex )
770             {
771               programIndex = image->programIndex;
772               program = flushUseProgram( programIndex );
773             }
774             if( texture != bindTexture )
775             {
776               bindTexture = texture;
777               glBindTexture( GL_TEXTURE_2D, bindTexture.glTex );
778       #if DM_RENDER_IMAGE_DEBUG
779       printf( "  Switch to texture 0x%x\n", (int)texture.orderMask );
780       #endif
781             }
782             bindimage = image;
783           }
784
785       #if DM_RENDER_IMAGE_DEBUG
786       printf( "   Render image at %d %d, order 0x%x, texture %p\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex, texture );
787       #endif
788
789       #if DM_ENABLE_IMAGE_ROTATION
790           angsin = (float)imageBuffer->angsin * (1.0f/DM_IMAGE_ROTATION_NORMFACTOR);
791           angcos = (float)imageBuffer->angcos * (1.0f/DM_IMAGE_ROTATION_NORMFACTOR);
792           sizex = (float)imageBuffer->sizex;
793           sizey = (float)imageBuffer->sizey;
794           vx0 = (float)imageBuffer->offsetx * (1.0f/DM_VERTEX_NORMFACTOR);
795           vy0 = (float)imageBuffer->offsety * (1.0f/DM_VERTEX_NORMFACTOR);
796           vx1 = vx0 + ( angcos * sizex );
797           vy1 = vy0 + ( angsin * sizex );
798           vx2 = vx0 - ( angsin * sizey );
799           vy2 = vy0 + ( angcos * sizey );
800           vx3 = vx0 + ( angcos * sizex ) - ( angsin * sizey );
801           vy3 = vy0 + ( angsin * sizex ) + ( angcos * sizey );
802       #else
803           vx0 = (float)imageBuffer->offsetx * (1.0f/DM_VERTEX_NORMFACTOR);
804           vy0 = (float)imageBuffer->offsety * (1.0f/DM_VERTEX_NORMFACTOR);
805           vx3 = vx0 + (float)( imageBuffer->sizex );
806           vy3 = vy0 + (float)( imageBuffer->sizey );
807           vx1 = vx3;
808           vy1 = vy0;
809           vx2 = vx0;
810           vy2 = vy3;
811       #endif
812
813           tx0 = (float)( image->srcx ) * texture.widthinv;
814           ty0 = (float)( image->srcy ) * texture.heightinv;
815           tx1 = (float)( image->srcx + image->sizex ) * texture.widthinv;
816           ty1 = (float)( image->srcy + image->sizey ) * texture.heightinv;
817
818           // Write data to VBO
819           vboVertex[0].vertex[0] = vx3;
820           vboVertex[0].vertex[1] = vy3;
821           vboVertex[0].texcoord0[0] = tx1;
822           vboVertex[0].texcoord0[1] = ty1;
823           vboVertex[0].color = imageBuffer->color;
824       #if DM_ENABLE_EXT_COLOR
825           vboVertex[0].extcolor = imageBuffer->extcolor;
826       #endif
827           vboVertex[1].vertex[0] = vx1;
828           vboVertex[1].vertex[1] = vy1;
829           vboVertex[1].texcoord0[0] = tx1;
830           vboVertex[1].texcoord0[1] = ty0;
831           vboVertex[1].color = imageBuffer->color;
832       #if DM_ENABLE_EXT_COLOR
833           vboVertex[1].extcolor = imageBuffer->extcolor;
834       #endif
835           vboVertex[2].vertex[0] = vx2;
836           vboVertex[2].vertex[1] = vy2;
837           vboVertex[2].texcoord0[0] = tx0;
838           vboVertex[2].texcoord0[1] = ty1;
839           vboVertex[2].color = imageBuffer->color;
840       #if DM_ENABLE_EXT_COLOR
841           vboVertex[2].extcolor = imageBuffer->extcolor;
842       #endif
843           vboVertex[3].vertex[0] = vx0;
844           vboVertex[3].vertex[1] = vy0;
845           vboVertex[3].texcoord0[0] = tx0;
846           vboVertex[3].texcoord0[1] = ty0;
847           vboVertex[3].color = imageBuffer->color;
848       #if DM_ENABLE_EXT_COLOR
849           vboVertex[3].extcolor = imageBuffer->extcolor;
850       #endif
851           vboVertex[4].vertex[0] = vx2;
852           vboVertex[4].vertex[1] = vy2;
853           vboVertex[4].texcoord0[0] = tx0;
854           vboVertex[4].texcoord0[1] = ty1;
855           vboVertex[4].color = imageBuffer->color;
856       #if DM_ENABLE_EXT_COLOR
857           vboVertex[4].extcolor = imageBuffer->extcolor;
858       #endif
859           vboVertex[5].vertex[0] = vx1;
860           vboVertex[5].vertex[1] = vy1;
861           vboVertex[5].texcoord0[0] = tx1;
862           vboVertex[5].texcoord0[1] = ty0;
863           vboVertex[5].color = imageBuffer->color;
864       #if DM_ENABLE_EXT_COLOR
865           vboVertex[5].extcolor = imageBuffer->extcolor;
866       #endif
867
868           vboVertex += 6;
869           vertexCount += 6;
870         }
871
872         glUnmapBuffer( GL_ARRAY_BUFFER );
873
874         // Flush font manager texture updates
875         flush();
876
877         // Render buffered images
878         flushRenderDrawBufferArchaic( drawBuffer, program, vertexCount );
879         imageBufferCount = 0;
880
881         ERRORCHECK();
882
883      }
884    }
885
886    void flushRenderDrawBuffer( DMDrawBuffer drawBuffer, DMProgram program, int vertexCount )
887    {
888       glBindBuffer( GL_ARRAY_BUFFER, drawBuffer.vbo );
889       if( program.vertexloc != -1 )
890       {
891          glEnableVertexAttribArray( program.vertexloc );
892          glVertexAttribPointer( program.vertexloc, 2, GL_SHORT, GL_FALSE, sizeof(DMDrawVertex), (void *)OFFSET(DMDrawVertex,vertex) );
893       }
894       if( program.texcoord0loc != -1 )
895       {
896          glEnableVertexAttribArray( program.texcoord0loc );
897          glVertexAttribPointer( program.texcoord0loc, 2, GL_SHORT, GL_FALSE, sizeof(DMDrawVertex), (void *)OFFSET(DMDrawVertex,texcoord0) );
898       }
899       if( program.colorloc != -1 )
900       {
901          glEnableVertexAttribArray( program.colorloc );
902          glVertexAttribPointer( program.colorloc, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(DMDrawVertex), (void *)OFFSET(DMDrawVertex,color) );
903       }
904
905    #if DM_ENABLE_EXT_COLOR
906       if( program.extcolorloc != -1 )
907       {
908          glEnableVertexAttribArray( program.extcolorloc );
909          glVertexAttribPointer( program.extcolorloc, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(DMDrawVertex), (void *)OFFSET(DMDrawVertex,extcolor) );
910       }
911    #endif
912
913       glDrawArrays( GL_TRIANGLES, 0, vertexCount );
914
915       if( program.vertexloc != -1 )
916          glDisableVertexAttribArray( program.vertexloc );
917       if( program.texcoord0loc != -1 )
918          glDisableVertexAttribArray( program.texcoord0loc );
919       if( program.colorloc != -1 )
920          glDisableVertexAttribArray( program.colorloc );
921
922    #if DM_FLUSH_EACH_RENDER_DRAW_BUFFER
923       glFlush();
924    #endif
925    }
926
927    void flushDrawImages( )
928    {
929       int index, stateblend, vertexcount, flushflag, programIndex;
930       float vx0, vx1, vx2, vx3, vy0, vy1, vy2, vy3;
931       #if DM_ENABLE_IMAGE_ROTATION
932       float angsin, angcos, sizex, sizey;
933       #endif
934       float tx0, tx1, ty0, ty1;
935       DMImageBuffer *imageBuffer;
936       DMImage *image, *bindimage;
937       Texture texture, bindtexture;
938       DMDrawBuffer *drawBuffer;
939       DMDrawVertex *vboVertex;
940       DMProgram *program;
941
942       ERRORCHECK();
943
944       this.drawBarrierIndex = 0;
945       orderBarrierMask = drawBarrierIndex << DM_BARRIER_ORDER_SHIFT;
946       if( imageBufferCount )
947       {
948          /* Sort by image type and texture, minimize state changes */
949          dmSortImages( this.imageBuffer, this.imageBufferTmp, imageBufferCount, (uint32)( (uintptr)this.imageBuffer >> 4 ) );
950
951          /* Fill a drawBuffer, write vertex and texcoords */
952          drawBuffer = &this.drawBuffer[this.drawBufferIndex];
953          this.drawBufferIndex = ( this.drawBufferIndex + 1 ) % DM_CONTEXT_DRAW_BUFFER_COUNT;
954          glBindBuffer( GL_ARRAY_BUFFER, drawBuffer->vbo );
955          vboVertex = glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY );
956          vertexcount = 0;
957
958          glActiveTexture( GL_TEXTURE0 );
959          glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
960          glDisable( GL_BLEND );
961
962          #if DM_RENDER_IMAGE_DEBUG
963          printf( " Flush %d images\n", (int)imageBufferCount );
964          #endif
965
966          bindimage = 0;
967          bindtexture = 0;
968          stateblend = 0;
969          programIndex = -1;
970          program = 0;
971          imageBuffer = this.imageBuffer;
972          for( index = 0 ; index < imageBufferCount ; index++, imageBuffer++ )
973          {
974           image = imageBuffer->image;
975           texture = image->texture;
976
977           flushflag = 0;
978           if( image != bindimage )
979           {
980             if( stateblend != ( image->flags.blending ) )
981               flushflag = 1;
982             if( texture != bindtexture )
983               flushflag = 1;
984           }
985           if( vertexcount >= ( drawBuffer->vertexAlloc - 6 ) )
986             flushflag = 1;
987
988           if( flushflag )
989           {
990             if( vertexcount )
991             {
992               glUnmapBuffer( GL_ARRAY_BUFFER );
993               // Flush font manager texture updates
994               flush();
995
996               // Render buffered images
997               flushRenderDrawBuffer( drawBuffer, program, vertexcount );
998               drawBuffer = &this.drawBuffer[this.drawBufferIndex];
999               this.drawBufferIndex = ( this.drawBufferIndex + 1 ) % DM_CONTEXT_DRAW_BUFFER_COUNT;
1000               glBindBuffer( GL_ARRAY_BUFFER, drawBuffer->vbo );
1001               vboVertex = glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY );
1002               vertexcount = 0;
1003             }
1004
1005             if( stateblend != ( image->flags.blending ) )
1006             {
1007               stateblend = image->flags.blending;
1008               ( stateblend ? glEnable : glDisable )( GL_BLEND );
1009             #if DM_RENDER_IMAGE_DEBUG
1010                printf( "  Switch blending %d\n", ( stateblend != 0 ) );
1011             #endif
1012             }
1013             if( programIndex != image->programIndex )
1014             {
1015               programIndex = image->programIndex;
1016               program = flushUseProgram( programIndex );
1017             }
1018             if( texture != bindtexture )
1019             {
1020               bindtexture = texture;
1021               glBindTexture( GL_TEXTURE_2D, bindtexture.glTex );
1022       #if DM_RENDER_IMAGE_DEBUG
1023               printf( "  Switch to texture 0x%x\n", (int)texture.orderMask );
1024       #endif
1025             }
1026             bindimage = image;
1027           }
1028
1029          #if DM_RENDER_IMAGE_DEBUG
1030          printf( "   Render image at %d %d, order 0x%x, texture %p\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex, texture );
1031          #endif
1032
1033       #if DM_ENABLE_IMAGE_ROTATION
1034           /* FIXME TODO: Don't go through float, compute texcoord integers directly */
1035           angsin = (float)imageBuffer->angsin * (1.0f/DM_IMAGE_ROTATION_NORMFACTOR);
1036           angcos = (float)imageBuffer->angcos * (1.0f/DM_IMAGE_ROTATION_NORMFACTOR);
1037           sizex = (float)imageBuffer->sizex;
1038           sizey = (float)imageBuffer->sizey;
1039           vx0 = (float)imageBuffer->offsetx * (1.0f/DM_VERTEX_NORMFACTOR);
1040           vy0 = (float)imageBuffer->offsety * (1.0f/DM_VERTEX_NORMFACTOR);
1041           vx1 = vx0 + ( angcos * sizex );
1042           vy1 = vy0 + ( angsin * sizex );
1043           vx2 = vx0 - ( angsin * sizey );
1044           vy2 = vy0 + ( angcos * sizey );
1045           vx3 = vx0 + ( angcos * sizex ) - ( angsin * sizey );
1046           vy3 = vy0 + ( angsin * sizex ) + ( angcos * sizey );
1047       #else
1048           /* FIXME TODO: Don't go through float, compute texcoord integers directly */
1049           vx0 = (float)imageBuffer->offsetx * (1.0f/DM_VERTEX_NORMFACTOR);
1050           vy0 = (float)imageBuffer->offsety * (1.0f/DM_VERTEX_NORMFACTOR);
1051           vx3 = vx0 + (float)( imageBuffer->sizex );
1052           vy3 = vy0 + (float)( imageBuffer->sizey );
1053           vx1 = vx3;
1054           vy1 = vy0;
1055           vx2 = vx0;
1056           vy2 = vy3;
1057       #endif
1058
1059           /* FIXME TODO: Don't go through float, compute texcoord integers directly */
1060           tx0 = (float)( image->srcx ) * texture.widthinv;
1061           ty0 = (float)( image->srcy ) * texture.heightinv;
1062           tx1 = (float)( image->srcx + image->sizex ) * texture.widthinv;
1063           ty1 = (float)( image->srcy + image->sizey ) * texture.heightinv;
1064
1065           /* Write data to VBO */
1066           /* TODO: write vertex/texcoord all at once with SSE */
1067           vboVertex[0].vertex[0] = (short)( vx3 * DM_VERTEX_NORMFACTOR );
1068           vboVertex[0].vertex[1] = (short)( vy3 * DM_VERTEX_NORMFACTOR );
1069           vboVertex[0].texcoord0[0] = (short)( tx1 * DM_TEXCOORD_NORMFACTOR );
1070           vboVertex[0].texcoord0[1] = (short)( ty1 * DM_TEXCOORD_NORMFACTOR );
1071           vboVertex[0].color = imageBuffer->color;
1072           vboVertex[0].extcolor = imageBuffer->extcolor;
1073           vboVertex[1].vertex[0] = (short)( vx1 * DM_VERTEX_NORMFACTOR );
1074           vboVertex[1].vertex[1] = (short)( vy1 * DM_VERTEX_NORMFACTOR );
1075           vboVertex[1].texcoord0[0] = (short)( tx1 * DM_TEXCOORD_NORMFACTOR );
1076           vboVertex[1].texcoord0[1] = (short)( ty0 * DM_TEXCOORD_NORMFACTOR );
1077           vboVertex[1].color = imageBuffer->color;
1078           vboVertex[1].extcolor = imageBuffer->extcolor;
1079           vboVertex[2].vertex[0] = (short)( vx2 * DM_VERTEX_NORMFACTOR );
1080           vboVertex[2].vertex[1] = (short)( vy2 * DM_VERTEX_NORMFACTOR );
1081           vboVertex[2].texcoord0[0] = (short)( tx0 * DM_TEXCOORD_NORMFACTOR );
1082           vboVertex[2].texcoord0[1] = (short)( ty1 * DM_TEXCOORD_NORMFACTOR );
1083           vboVertex[2].color = imageBuffer->color;
1084           vboVertex[2].extcolor = imageBuffer->extcolor;
1085           vboVertex[3].vertex[0] = (short)( vx0 * DM_VERTEX_NORMFACTOR );
1086           vboVertex[3].vertex[1] = (short)( vy0 * DM_VERTEX_NORMFACTOR );
1087           vboVertex[3].texcoord0[0] = (short)( tx0 * DM_TEXCOORD_NORMFACTOR );
1088           vboVertex[3].texcoord0[1] = (short)( ty0 * DM_TEXCOORD_NORMFACTOR );
1089           vboVertex[3].color = imageBuffer->color;
1090           vboVertex[3].extcolor = imageBuffer->extcolor;
1091           vboVertex[4].vertex[0] = (short)( vx2 * DM_VERTEX_NORMFACTOR );
1092           vboVertex[4].vertex[1] = (short)( vy2 * DM_VERTEX_NORMFACTOR );
1093           vboVertex[4].texcoord0[0] = (short)( tx0 * DM_TEXCOORD_NORMFACTOR );
1094           vboVertex[4].texcoord0[1] = (short)( ty1 * DM_TEXCOORD_NORMFACTOR );
1095           vboVertex[4].color = imageBuffer->color;
1096           vboVertex[4].extcolor = imageBuffer->extcolor;
1097           vboVertex[5].vertex[0] = (short)( vx1 * DM_VERTEX_NORMFACTOR );
1098           vboVertex[5].vertex[1] = (short)( vy1 * DM_VERTEX_NORMFACTOR );
1099           vboVertex[5].texcoord0[0] = (short)( tx1 * DM_TEXCOORD_NORMFACTOR );
1100           vboVertex[5].texcoord0[1] = (short)( ty0 * DM_TEXCOORD_NORMFACTOR );
1101           vboVertex[5].color = imageBuffer->color;
1102           vboVertex[5].extcolor = imageBuffer->extcolor;
1103
1104           vboVertex += 6;
1105           vertexcount += 6;
1106         }
1107
1108         glUnmapBuffer( GL_ARRAY_BUFFER );
1109         // Flush font manager texture updates
1110         flush();
1111         // Render buffered images
1112         flushRenderDrawBuffer( drawBuffer, program, vertexcount );
1113         imageBufferCount = 0;
1114
1115         ERRORCHECK();
1116       }
1117    }
1118
1119 public:
1120
1121    virtual void flush();
1122
1123    bool init( DrawManagerFlags flags )
1124    {
1125       int drawBufferIndex, programIndex;
1126       DMDrawBuffer *drawBuffer;
1127       uint vertexSize;
1128
1129       imageBufferCount = 0;
1130       imageBufferSize = 4096;
1131       imageBuffer = new DMImageBuffer[imageBufferSize];
1132       imageBufferTmp = new DMImageBuffer[imageBufferSize];
1133
1134       this.flags = flags;
1135
1136       if( flags.prehistoricOpenGL )
1137          vertexSize = sizeof(DMDrawVertexFlat);
1138       else
1139       {
1140          DMProgram *program;
1141          for( programIndex = 0 ; programIndex < DM_PROGRAM_COUNT ; programIndex++ )
1142          {
1143             program = &shaderPrograms[ programIndex ];
1144             program->flags = 0;
1145             program->lastUpdateCount = -1;
1146          }
1147          program = &shaderPrograms[ DM_PROGRAM_NORMAL ];
1148          if( !( dmCreateProgram( program, dmVertexShaderNormal, dmFragmentShaderNormal, 0 ) ) )
1149             return false;
1150          program = &shaderPrograms[ DM_PROGRAM_ALPHABLEND ];
1151          if( !( dmCreateProgram( program, dmVertexShaderAlpha, dmFragmentShaderAlpha, 0 ) ) )
1152             return false;
1153          program = &shaderPrograms[ DM_PROGRAM_ALPHABLEND_INTENSITY ];
1154          if( !( dmCreateProgram( program, dmVertexShaderAlphaIntensity, dmFragmentShaderAlphaIntensity, 0 ) ) )
1155             return false;
1156         program = &shaderPrograms[ DM_PROGRAM_ALPHABLEND_INTENSITY_EXTCOLOR ];
1157         if( !( dmCreateProgram( program, dmVertexShaderAlphaIntensityExtColor, dmFragmentShaderAlphaIntensityExtColor, 0 ) ) )
1158             return false;
1159          // glUseProgram( 0 );
1160          vertexSize = sizeof(DMDrawVertex);
1161       }
1162
1163       for( drawBufferIndex = 0 ; drawBufferIndex < DM_CONTEXT_DRAW_BUFFER_COUNT ; drawBufferIndex++ )
1164       {
1165          drawBuffer = &this.drawBuffer[drawBufferIndex];
1166          drawBuffer->glType = GL_FLOAT;
1167          drawBuffer->vertexCount = 0;
1168          drawBuffer->vertexAlloc = DM_CONTEXT_DRAW_BUFFER_VERTEX_ALLOC;
1169          if(vboAvailable)
1170          {
1171             glGenBuffers( 1, &drawBuffer->vbo );
1172             glBindBuffer( GL_ARRAY_BUFFER, drawBuffer->vbo );
1173             glBufferData( GL_ARRAY_BUFFER, drawBuffer->vertexAlloc * vertexSize, 0, GL_DYNAMIC_DRAW );
1174          }
1175          drawBuffer->vertexBuffer = new byte[drawBuffer->vertexAlloc * vertexSize];
1176       }
1177
1178       updateCount = 0;
1179
1180       return true;
1181    }
1182
1183
1184    void end( )
1185    {
1186       int i;
1187
1188       for( i = 0 ; i < DM_CONTEXT_DRAW_BUFFER_COUNT ; i++ )
1189       {
1190          DMDrawBuffer *db = &drawBuffer[i];
1191          if(db->vbo)
1192             glDeleteBuffers( 1, &db->vbo );
1193          delete db->vertexBuffer;
1194       }
1195
1196       // TODO: Destroy the shaders!
1197       delete imageBuffer;
1198       delete imageBufferTmp;
1199    }
1200
1201    void ready( int viewportwidth, int viewportheight )
1202    {
1203       int mindex;
1204       float norminv;
1205       if(!prevProgram)
1206          glGetIntegerv(GL_CURRENT_PROGRAM, (GLint *)&prevProgram);
1207       // while(glGetError());
1208
1209       // ERRORCHECK();
1210
1211       // Save OpenGL state
1212       // FIXME: no glPushAttrib() in core profile
1213 //#ifndef SHADERS
1214       glPushClientAttrib( GL_CLIENT_ALL_ATTRIB_BITS );
1215       glPushAttrib( GL_ALL_ATTRIB_BITS );
1216 //#endif
1217
1218       // Prepare rendering pass
1219       matrixOrtho( matrix, 0.0, (float)viewportwidth, (float)viewportheight, 0.0, -1.0f, 1.0 );
1220       norminv = 1.0f / DM_VERTEX_NORMFACTOR;
1221       for( mindex = 0 ; mindex < 12 ; mindex += 4 )
1222       {
1223         matrix[mindex+0] *= norminv;
1224         matrix[mindex+1] *= norminv;
1225         matrix[mindex+2] *= norminv;
1226       }
1227       drawBarrierIndex = 0;
1228       orderBarrierMask = drawBarrierIndex << DM_BARRIER_ORDER_SHIFT;
1229       orderBarrierMask = 0;
1230
1231       updateCount++;
1232    }
1233
1234    void drawImage( DMImage image, int offsetx, int offsety, int sizex, int sizey, uint32 color )
1235    {
1236      DMImageBuffer *imageBuffer;
1237
1238      if( image.flags.empty || ( sizex <= 0 ) || ( sizey <= 0 ) )
1239        return;
1240
1241      if( imageBufferCount >= imageBufferSize )
1242      {
1243        imageBufferSize <<= 1;
1244        this.imageBuffer = renew this.imageBuffer DMImageBuffer[imageBufferSize];
1245        imageBufferTmp = renew imageBufferTmp DMImageBuffer[imageBufferSize];
1246      }
1247
1248      imageBuffer = &this.imageBuffer[ imageBufferCount ];
1249      imageBuffer->image = image;
1250      imageBuffer->offsetx = (short)(offsetx << DM_VERTEX_NORMSHIFT);
1251      imageBuffer->offsety = (short)(offsety << DM_VERTEX_NORMSHIFT);
1252      imageBuffer->sizex = (short)sizex;
1253      imageBuffer->sizey = (short)sizey;
1254    #if DM_ENABLE_IMAGE_ROTATION
1255      imageBuffer->angsin = 0;
1256      imageBuffer->angcos = (short)DM_IMAGE_ROTATION_NORMFACTOR;
1257    #endif
1258      imageBuffer->color = color;
1259      imageBuffer->orderindex = image.orderMask | orderBarrierMask;
1260
1261    #if DM_RENDER_IMAGE_DEBUG
1262    printf( "  Queue image at %d %d, order 0x%x\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex );
1263    #endif
1264
1265      imageBufferCount++;
1266    }
1267
1268    void drawImageExtColor( DMImage image, int offsetx, int offsety, int sizex, int sizey, uint32 color, uint32 extcolor )
1269    {
1270      DMImageBuffer *imageBuffer;
1271
1272      if( ( image.flags.empty ) || ( sizex <= 0 ) || ( sizey <= 0 ) )
1273        return;
1274
1275      if( imageBufferCount >= imageBufferSize )
1276      {
1277        imageBufferSize <<= 1;
1278        this.imageBuffer = renew this.imageBuffer DMImageBuffer[imageBufferSize];
1279        imageBufferTmp = renew imageBufferTmp DMImageBuffer[imageBufferSize];
1280      }
1281
1282      imageBuffer = &this.imageBuffer[ imageBufferCount ];
1283      imageBuffer->image = image;
1284      imageBuffer->offsetx = (short)(offsetx << DM_VERTEX_NORMSHIFT);
1285      imageBuffer->offsety = (short)(offsety << DM_VERTEX_NORMSHIFT);
1286      imageBuffer->sizex = (short)sizex;
1287      imageBuffer->sizey = (short)sizey;
1288    #if DM_ENABLE_IMAGE_ROTATION
1289      imageBuffer->angsin = 0;
1290      imageBuffer->angcos = (short)DM_IMAGE_ROTATION_NORMFACTOR;
1291    #endif
1292      imageBuffer->color = color;
1293    #if DM_ENABLE_EXT_COLOR
1294      imageBuffer->extcolor = extcolor;
1295    #endif
1296      imageBuffer->orderindex = image.orderMask | orderBarrierMask;
1297
1298    #if DM_RENDER_IMAGE_DEBUG
1299    printf( "  Queue image at %d %d, order 0x%x\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex );
1300    #endif
1301
1302      this.imageBufferCount++;
1303    }
1304
1305    void drawImageFloat( DMImage image, float offsetx, float offsety, float sizex, float sizey, float angsin, float angcos, uint32 color )
1306    {
1307      DMImageBuffer *imageBuffer;
1308
1309      if( image.flags.empty || sizex <= 0 || sizey <= 0 )
1310        return;
1311
1312      if( imageBufferCount >= imageBufferSize )
1313      {
1314        imageBufferSize <<= 1;
1315        this.imageBuffer = renew this.imageBuffer DMImageBuffer[imageBufferSize];
1316        imageBufferTmp = renew imageBufferTmp DMImageBuffer[imageBufferSize];
1317      }
1318
1319      imageBuffer = &this.imageBuffer[ imageBufferCount ];
1320      imageBuffer->image = image;
1321      imageBuffer->offsetx = (short)roundf(offsetx * DM_VERTEX_NORMFACTOR);
1322      imageBuffer->offsety = (short)roundf(offsety * DM_VERTEX_NORMFACTOR);
1323      imageBuffer->sizex = (short)sizex;
1324      imageBuffer->sizey = (short)sizey;
1325    #if DM_ENABLE_IMAGE_ROTATION
1326      imageBuffer->angsin = (short)roundf( angsin * DM_IMAGE_ROTATION_NORMFACTOR );
1327      imageBuffer->angcos = (short)roundf( angcos * DM_IMAGE_ROTATION_NORMFACTOR );
1328    #endif
1329      imageBuffer->color = color;
1330      imageBuffer->orderindex = image.orderMask | orderBarrierMask;
1331
1332    #if DM_RENDER_IMAGE_DEBUG
1333    printf( "  Queue image at %d %d, order 0x%x\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex );
1334    #endif
1335
1336      imageBufferCount++;
1337    }
1338
1339    void drawImageFloatExtColor( DMImage image, float offsetx, float offsety, float sizex, float sizey, float angsin, float angcos, uint32 color, uint32 extcolor )
1340    {
1341      DMImageBuffer *imageBuffer;
1342
1343      if( ( image.flags.empty ) || ( sizex <= 0 ) || ( sizey <= 0 ) )
1344        return;
1345
1346      if( this.imageBufferCount >= this.imageBufferSize )
1347      {
1348        imageBufferSize <<= 1;
1349        this.imageBuffer = renew this.imageBuffer DMImageBuffer[imageBufferSize];
1350        imageBufferTmp = renew imageBufferTmp DMImageBuffer[imageBufferSize];
1351      }
1352
1353      imageBuffer = &this.imageBuffer[ imageBufferCount ];
1354      imageBuffer->image = image;
1355      imageBuffer->offsetx = (short)roundf( offsetx * DM_VERTEX_NORMFACTOR );
1356      imageBuffer->offsety = (short)roundf( offsety * DM_VERTEX_NORMFACTOR );
1357      imageBuffer->sizex = (short)sizex;
1358      imageBuffer->sizey = (short)sizey;
1359    #if DM_ENABLE_IMAGE_ROTATION
1360      imageBuffer->angsin = (short)roundf( angsin * DM_IMAGE_ROTATION_NORMFACTOR );
1361      imageBuffer->angcos = (short)roundf( angcos * DM_IMAGE_ROTATION_NORMFACTOR );
1362    #endif
1363      imageBuffer->color = color;
1364    #if DM_ENABLE_EXT_COLOR
1365      imageBuffer->extcolor = extcolor;
1366    #endif
1367      imageBuffer->orderindex = image.orderMask | orderBarrierMask;
1368
1369    #if DM_RENDER_IMAGE_DEBUG
1370    printf( "  Queue image at %d %d, order 0x%x\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex );
1371    #endif
1372
1373      this.imageBufferCount++;
1374    }
1375
1376    void flushImages( )
1377    {
1378      if( flags.prehistoricOpenGL )
1379        flushDrawImagesArchaic( );
1380      else
1381        flushDrawImages( );
1382
1383      if(vboAvailable)
1384         glBindBuffer( GL_ARRAY_BUFFER, 0 );
1385      glabCurArrayBuffer = 0;
1386      if( !flags.prehistoricOpenGL )
1387          glUseProgram( prevProgram );
1388       // Restore OpenGL state
1389       // FIXME: no glPushAttrib() in core profile
1390 //#ifndef SHADERS
1391       glPopAttrib();
1392       glPopClientAttrib();
1393 //#endif
1394    }
1395
1396    void drawBarrier( )
1397    {
1398       drawBarrierIndex++;
1399       if( drawBarrierIndex >= ( 1 << DM_BARRIER_ORDER_BITS ) )
1400          flushImages( );
1401       orderBarrierMask = drawBarrierIndex << DM_BARRIER_ORDER_SHIFT;
1402    }
1403 }