]> icculus.org git repositories - taylor/freespace2.git/blob - src/graphics/gropengl.cpp
Speed up the renderer a tad
[taylor/freespace2.git] / src / graphics / gropengl.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Graphics/GrOpenGL.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * Code that uses the OpenGL graphics library
16  *
17  * $Log$
18  * Revision 1.57  2002/08/31 01:39:13  theoddone33
19  * Speed up the renderer a tad
20  *
21  * Revision 1.56  2002/08/01 05:03:11  relnev
22  * minor change
23  *
24  * Revision 1.55  2002/08/01 04:55:45  relnev
25  * experimenting with texture state
26  *
27  * Revision 1.54  2002/07/30 15:00:15  relnev
28  * not use luminance alpha by default
29  *
30  * Revision 1.53  2002/06/22 17:08:16  relnev
31  * more fixes to unused alpha code
32  *
33  * Revision 1.52  2002/06/21 23:59:14  relnev
34  * moved a gr_opengl_set_state to after the gr_tcache_set
35  *
36  * Revision 1.51  2002/06/19 04:52:45  relnev
37  * MacOS X updates (Ryan)
38  *
39  * Revision 1.50  2002/06/18 23:20:44  relnev
40  * fixed _splitpath.
41  *
42  * adjusted line offsets.
43  *
44  * Revision 1.49  2002/06/17 23:11:39  relnev
45  * enable sdl key repeating.
46  *
47  * swap '/` keys.
48  *
49  * Revision 1.48  2002/06/09 04:41:17  relnev
50  * added copyright header
51  *
52  * Revision 1.47  2002/06/09 03:16:04  relnev
53  * added _splitpath.
54  *
55  * removed unneeded asm, old sdl 2d setup.
56  *
57  * fixed crash caused by opengl_get_region.
58  *
59  * Revision 1.46  2002/06/05 04:03:32  relnev
60  * finished cfilesystem.
61  *
62  * removed some old code.
63  *
64  * fixed mouse save off-by-one.
65  *
66  * sound cleanups.
67  *
68  * Revision 1.45  2002/06/03 09:25:37  relnev
69  * implement mouse cursor and screen save/restore
70  *
71  * Revision 1.44  2002/06/02 18:46:59  relnev
72  * updated
73  *
74  * Revision 1.43  2002/06/02 11:34:00  relnev
75  * adjust z coords
76  *
77  * Revision 1.42  2002/06/02 10:28:17  relnev
78  * fix texture handle leak
79  *
80  * Revision 1.41  2002/06/01 09:00:34  relnev
81  * silly debug memmanager
82  *
83  * Revision 1.40  2002/06/01 07:12:33  relnev
84  * a few NDEBUG updates.
85  *
86  * removed a few warnings.
87  *
88  * Revision 1.39  2002/06/01 05:33:15  relnev
89  * copied more code over.
90  *
91  * added scissor clipping.
92  *
93  * Revision 1.38  2002/06/01 03:35:27  relnev
94  * fix typo
95  *
96  * Revision 1.37  2002/06/01 03:32:00  relnev
97  * fix texture loading mistake.
98  *
99  * enable some d3d stuff for opengl also
100  *
101  * Revision 1.36  2002/05/31 23:25:03  relnev
102  * line fixes
103  *
104  * Revision 1.34  2002/05/31 22:15:22  relnev
105  * BGRA
106  *
107  * Revision 1.33  2002/05/31 22:04:55  relnev
108  * use d3d rect_internal
109  *
110  * Revision 1.32  2002/05/31 06:28:23  relnev
111  * more stuff
112  *
113  * Revision 1.31  2002/05/31 06:04:39  relnev
114  * fog
115  *
116  * Revision 1.30  2002/05/31 03:56:11  theoddone33
117  * Change tmapper polygon winding and enable culling
118  *
119  * Revision 1.29  2002/05/31 03:34:02  theoddone33
120  * Fix Keyboard
121  * Add titlebar
122  *
123  * Revision 1.28  2002/05/31 00:06:59  relnev
124  * minor change
125  *
126  * Revision 1.27  2002/05/30 23:46:29  theoddone33
127  * some minor key changes (not necessarily fixes)
128  *
129  * Revision 1.26  2002/05/30 23:33:12  relnev
130  * implemented a few more functions.
131  *
132  * Revision 1.25  2002/05/30 23:01:16  relnev
133  * implement gr_opengl_set_state.
134  *
135  * Revision 1.24  2002/05/30 22:12:57  relnev
136  * finish default texture case
137  *
138  * Revision 1.23  2002/05/30 22:02:30  theoddone33
139  * More gl changes
140  *
141  * Revision 1.22  2002/05/30 21:44:48  relnev
142  * implemented some missing texture stuff.
143  *
144  * enable bitmap polys for opengl.
145  *
146  * work around greenness in bitmaps.
147  *
148  * Revision 1.21  2002/05/30 17:29:30  theoddone33
149  * Fix some more stubs, change at least one polygon winding since culling is now
150  * enabled.
151  *
152  * Revision 1.20  2002/05/30 16:50:24  theoddone33
153  * Keyboard partially fixed
154  *
155  * Revision 1.19  2002/05/30 08:13:14  relnev
156  * fonts are fixed
157  *
158  * Revision 1.18  2002/05/29 23:37:36  relnev
159  * fix bitmap bug
160  *
161  * Revision 1.17  2002/05/29 23:17:49  theoddone33
162  * Non working text code and fixed keys
163  *
164  * Revision 1.16  2002/05/29 19:45:13  theoddone33
165  * More changes on texture loading
166  *
167  * Revision 1.15  2002/05/29 19:06:48  theoddone33
168  * Enable string printing.  Enable texture mapping
169  *
170  * Revision 1.14  2002/05/29 08:54:40  relnev
171  * "fixed" bitmap drawing.
172  *
173  * copied more d3d code over.
174  *
175  * Revision 1.13  2002/05/29 06:25:13  theoddone33
176  * Keyboard input, mouse tracking now work
177  *
178  * Revision 1.12  2002/05/29 04:52:45  relnev
179  * bitmap
180  *
181  * Revision 1.11  2002/05/29 04:29:56  relnev
182  * removed some unncessary stubbing, implemented opengl rect
183  *
184  * Revision 1.10  2002/05/29 04:13:27  theoddone33
185  * enable opengl_line
186  *
187  * Revision 1.9  2002/05/29 03:35:51  relnev
188  * added rest of init
189  *
190  * Revision 1.8  2002/05/29 03:30:05  relnev
191  * update opengl stubs
192  *
193  * Revision 1.7  2002/05/29 02:52:32  theoddone33
194  * Enable OpenGL renderer
195  *
196  * Revision 1.6  2002/05/28 04:56:51  theoddone33
197  * runs a little bit now
198  *
199  * Revision 1.5  2002/05/28 04:07:28  theoddone33
200  * New graphics stubbing arrangement
201  *
202  * Revision 1.4  2002/05/27 23:39:34  relnev
203  * 0
204  *
205  * Revision 1.3  2002/05/27 22:35:01  theoddone33
206  * more symbols
207  *
208  * Revision 1.2  2002/05/27 22:32:02  theoddone33
209  * throw all d3d stuff at opengl
210  *
211  * Revision 1.1.1.1  2002/05/03 03:28:09  root
212  * Initial import.
213  *
214  * 
215  * 10    7/14/99 9:42a Dave
216  * Put in clear_color debug function. Put in base for 3dnow stuff / P3
217  * stuff
218  * 
219  * 9     7/09/99 9:51a Dave
220  * Added thick polyline code.
221  * 
222  * 8     6/29/99 10:35a Dave
223  * Interface polygon bitmaps! Whee!
224  * 
225  * 7     2/03/99 11:44a Dave
226  * Fixed d3d transparent textures.
227  * 
228  * 6     1/24/99 11:37p Dave
229  * First full rev of beam weapons. Very customizable. Removed some bogus
230  * Int3()'s in low level net code.
231  * 
232  * 5     12/18/98 1:13a Dave
233  * Rough 1024x768 support for Direct3D. Proper detection and usage through
234  * the launcher.
235  * 
236  * 4     12/06/98 2:36p Dave
237  * Drastically improved nebula fogging.
238  * 
239  * 3     11/11/98 5:37p Dave
240  * Checkin for multiplayer testing.
241  * 
242  * 2     10/07/98 10:53a Dave
243  * Initial checkin.
244  * 
245  * 1     10/07/98 10:49a Dave
246  * 
247  * 14    5/20/98 9:46p John
248  * added code so the places in code that change half the palette don't
249  * have to clear the screen.
250  * 
251  * 13    5/06/98 5:30p John
252  * Removed unused cfilearchiver.  Removed/replaced some unused/little used
253  * graphics functions, namely gradient_h and _v and pixel_sp.   Put in new
254  * DirectX header files and libs that fixed the Direct3D alpha blending
255  * problems.
256  * 
257  * 12    4/14/98 12:15p John
258  * Made 16-bpp movies work.
259  * 
260  * 11    3/12/98 5:36p John
261  * Took out any unused shaders.  Made shader code take rgbc instead of
262  * matrix and vector since noone used it like a matrix and it would have
263  * been impossible to do in hardware.   Made Glide implement a basic
264  * shader for online help.  
265  * 
266  * 10    3/10/98 4:18p John
267  * Cleaned up graphics lib.  Took out most unused gr functions.   Made D3D
268  * & Glide have popups and print screen.  Took out all >8bpp software
269  * support.  Made Fred zbuffer.  Made zbuffer allocate dynamically to
270  * support Fred.  Made zbuffering key off of functions rather than one
271  * global variable.
272  * 
273  * 9     12/02/97 4:00p John
274  * Added first rev of thruster glow, along with variable levels of
275  * translucency, which retquired some restructing of palman.
276  * 
277  * 8     10/03/97 9:10a John
278  * added better antialiased line drawer
279  * 
280  * 7     9/23/97 10:45a John
281  * made so you can tell bitblt code to rle a bitmap by passing flag to
282  * gr_set_bitmap
283  * 
284  * 6     9/09/97 11:01a Sandeep
285  * fixed warning level 4 bugs
286  * 
287  * 5     7/10/97 2:06p John
288  * added code to specify alphablending type for bitmaps.
289  * 
290  * 4     6/17/97 7:04p John
291  * added d3d support for gradients.
292  * fixed some color bugs by adding screen signatures instead of watching
293  * flags and palette changes.
294  * 
295  * 3     6/12/97 2:50a Lawrance
296  * bm_unlock() now passed bitmap number, not pointer
297  * 
298  * 2     6/11/97 1:12p John
299  * Started fixing all the text colors in the game.
300  * 
301  * 1     5/12/97 12:14p John
302  *
303  * $NoKeywords: $
304  */
305
306 #ifndef PLAT_UNIX
307 #include <windows.h>
308 #include <windowsx.h>
309 #endif
310
311 #ifdef __MACOSX__
312 #include <gl.h>
313 #else
314 #include <GL/gl.h>
315 #endif
316
317 #include "pstypes.h"
318 #include "osapi.h"
319 #include "2d.h"
320 #include "3d.h"
321 #include "bmpman.h"
322 #include "floating.h"
323 #include "palman.h"
324 #include "systemvars.h"
325 #include "grinternal.h"
326 #include "gropengl.h"
327 #include "line.h"
328 #include "neb.h"
329 #include "mouse.h"
330 #include "osregistry.h"
331
332 static int Inited = 0;
333
334 typedef enum gr_texture_source {
335         TEXTURE_SOURCE_NONE,
336         TEXTURE_SOURCE_DECAL,
337         TEXTURE_SOURCE_NO_FILTERING,
338 } gr_texture_source;
339
340 typedef enum gr_alpha_blend {
341         ALPHA_BLEND_NONE,                       // 1*SrcPixel + 0*DestPixel
342         ALPHA_BLEND_ADDITIVE,                   // 1*SrcPixel + 1*DestPixel
343         ALPHA_BLEND_ALPHA_ADDITIVE,             // Alpha*SrcPixel + 1*DestPixel
344         ALPHA_BLEND_ALPHA_BLEND_ALPHA,          // Alpha*SrcPixel + (1-Alpha)*DestPixel
345         ALPHA_BLEND_ALPHA_BLEND_SRC_COLOR,      // Alpha*SrcPixel + (1-SrcPixel)*DestPixel
346 } gr_alpha_blend;
347
348 typedef enum gr_zbuffer_type {
349         ZBUFFER_TYPE_NONE,
350         ZBUFFER_TYPE_READ,
351         ZBUFFER_TYPE_WRITE,
352         ZBUFFER_TYPE_FULL,
353 } gr_zbuffer_type;
354                         
355 #define NEBULA_COLORS 20
356
357 volatile int GL_activate = 0;
358 volatile int GL_deactivate = 0;
359
360 static int GL_use_luminance_alpha;
361
362 static char *Gr_saved_screen = NULL;
363 static int Gr_saved_screen_bitmap;
364
365 #ifdef PLAT_UNIX
366 // Throw in some dummy functions - DDOI
367
368 int D3D_32bit = 0;              // grd3d.cpp
369 int D3D_fog_mode = -1;          // grd3d.cpp
370 int D3D_inited = 0;             // grd3d.cpp
371 int D3D_zbias = 1;              // grd3d.cpp
372 int D3d_rendition_uvs = 0;      // grd3d.cpp
373
374 void d3d_flush ()
375 {
376         STUB_FUNCTION;
377 }
378
379 void d3d_zbias (int a)
380 {
381         STUB_FUNCTION;
382 }
383 #endif
384
385 static void gr_opengl_set_texture_state(gr_texture_source ts);
386
387 static gr_alpha_blend GL_current_alpha_blend = (gr_alpha_blend) -1;
388 static gr_zbuffer_type GL_current_zbuffer_type = (gr_zbuffer_type) -1;
389
390 static void gr_opengl_set_state(gr_texture_source ts, gr_alpha_blend ab, gr_zbuffer_type zt)
391 {
392         gr_opengl_set_texture_state(ts);
393         
394         if (ab != GL_current_alpha_blend) {
395                 switch (ab) {
396                         case ALPHA_BLEND_NONE:                  // 1*SrcPixel + 0*DestPixel
397                                 glBlendFunc(GL_ONE, GL_ZERO);
398                                 break;
399                         case ALPHA_BLEND_ADDITIVE:              // 1*SrcPixel + 1*DestPixel
400                                 glBlendFunc(GL_ONE, GL_ONE);
401                                 break;
402                         case ALPHA_BLEND_ALPHA_ADDITIVE:        // Alpha*SrcPixel + 1*DestPixel
403                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
404                                 break;
405                         case ALPHA_BLEND_ALPHA_BLEND_ALPHA:     // Alpha*SrcPixel + (1-Alpha)*DestPixel
406                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
407                                 break;
408                         case ALPHA_BLEND_ALPHA_BLEND_SRC_COLOR: // Alpha*SrcPixel + (1-SrcPixel)*DestPixel
409                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_COLOR);
410                                 break;
411                         default:
412                                 break;
413                 }
414                 
415                 GL_current_alpha_blend = ab;
416         }
417         
418         if (zt != GL_current_zbuffer_type) {
419                 switch (zt) {
420                         case ZBUFFER_TYPE_NONE:
421                                 glDepthFunc(GL_ALWAYS);
422                                 glDepthMask(GL_FALSE);
423                                 break;
424                         case ZBUFFER_TYPE_READ:
425                                 glDepthFunc(GL_LESS);
426                                 glDepthMask(GL_FALSE);  
427                                 break;
428                         case ZBUFFER_TYPE_WRITE:
429                                 glDepthFunc(GL_ALWAYS);
430                                 glDepthMask(GL_TRUE);
431                                 break;
432                         case ZBUFFER_TYPE_FULL:
433                                 glDepthFunc(GL_LESS);
434                                 glDepthMask(GL_TRUE);
435                                 break;
436                         default:
437                                 break;
438                 }
439                 
440                 GL_current_zbuffer_type = zt;
441         }       
442 }
443
444 void gr_opengl_activate(int active)
445 {
446         if (active) {
447                 GL_activate++;
448                 
449                 /* TODO:
450                    make sure window is active and mouse grabbed
451                  */
452         } else {
453                 GL_deactivate++;
454                 
455                 /* TODO:
456                    make sure mouse is not grabbed and window minimized
457                  */
458         }
459         
460         STUB_FUNCTION;
461 }
462
463
464 void opengl_tcache_flush ();
465
466 void gr_opengl_preload_init()
467 {
468         if (gr_screen.mode != GR_OPENGL) {
469                 return;
470         }
471
472         opengl_tcache_flush ();
473 }
474
475 int GL_should_preload = 0;
476 int gr_opengl_preload(int bitmap_num, int is_aabitmap)
477 {
478         if ( gr_screen.mode != GR_OPENGL) {
479                 return 0;
480         }
481
482         if ( !GL_should_preload )      {
483                 return 0;
484         }
485
486         float u_scale, v_scale;
487
488         int retval;
489         if ( is_aabitmap )      {
490                 retval = gr_tcache_set(bitmap_num, TCACHE_TYPE_AABITMAP, &u_scale, &v_scale, 1 );
491         } else {
492                 retval = gr_tcache_set(bitmap_num, TCACHE_TYPE_NORMAL, &u_scale, &v_scale, 1 );
493         }
494
495         if ( !retval )  {
496                 mprintf(("Texture upload failed!\n" ));
497         }
498
499         return retval;
500 }
501
502 void gr_opengl_pixel(int x, int y)
503 {
504         gr_line(x,y,x,y);
505 }
506
507 void gr_opengl_clear()
508 {
509         glClearColor(gr_screen.current_clear_color.red / 255.0, 
510                 gr_screen.current_clear_color.green / 255.0, 
511                 gr_screen.current_clear_color.blue / 255.0, 1.0);
512
513         glClear ( GL_COLOR_BUFFER_BIT );
514 }
515
516 void gr_opengl_save_mouse_area(int x, int y, int w, int h);
517 void opengl_tcache_frame ();
518 void gr_opengl_flip()
519 {
520         if (!Inited) return;
521
522         gr_reset_clip();
523
524         mouse_eval_deltas();
525         
526         extern int Gr_opengl_mouse_saved;
527         Gr_opengl_mouse_saved = 0;
528         
529         if ( mouse_is_visible() )       {
530                 int mx, my;
531                 
532                 gr_reset_clip();
533                 mouse_get_pos( &mx, &my );
534                 
535                 gr_opengl_save_mouse_area(mx,my,32,32);
536                 
537                 if ( Gr_cursor == -1 )  {
538                         // stuff
539                 } else {
540                         gr_set_bitmap(Gr_cursor);
541                         gr_bitmap( mx, my );
542                 }
543          }
544          
545 #ifndef NDEBUG
546         GLenum error = glGetError();
547         int ic = 0;
548         do {
549                 error = glGetError();
550                 
551                 if (error != GL_NO_ERROR) {
552                         nprintf(("Warning", "!!DEBUG!! OpenGL Error: %d (%d this frame)\n", error, ic));
553                 }
554                 ic++;
555         } while (error != GL_NO_ERROR);
556 #endif
557         
558         SDL_GL_SwapBuffers ();
559
560         opengl_tcache_frame ();
561         
562         int cnt = GL_activate;
563         if ( cnt )      {
564                 GL_activate-=cnt;
565                 opengl_tcache_flush();
566                 // gr_opengl_clip_cursor(1); /* mouse grab, see opengl_activate */
567         }
568         
569         cnt = GL_deactivate;
570         if ( cnt )      {
571                 GL_deactivate-=cnt;
572                 // gr_opengl_clip_cursor(0);  /* mouse grab, see opengl_activate */
573         }
574 }
575
576 void gr_opengl_flip_window(uint _hdc, int x, int y, int w, int h )
577 {
578         // Not used.
579 }
580
581 void gr_opengl_set_clip(int x,int y,int w,int h)
582 {
583         // check for sanity of parameters
584         if (x < 0)
585                 x = 0;
586         if (y < 0)
587                 y = 0;
588
589         if (x >= gr_screen.max_w)
590                 x = gr_screen.max_w - 1;
591         if (y >= gr_screen.max_h)
592                 y = gr_screen.max_h - 1;
593
594         if (x + w > gr_screen.max_w)
595                 w = gr_screen.max_w - x;
596         if (y + h > gr_screen.max_h)
597                 h = gr_screen.max_h - y;
598         
599         if (w > gr_screen.max_w)
600                 w = gr_screen.max_w;
601         if (h > gr_screen.max_h)
602                 h = gr_screen.max_h;
603         
604         gr_screen.offset_x = x;
605         gr_screen.offset_y = y;
606         gr_screen.clip_left = 0;
607         gr_screen.clip_right = w-1;
608         gr_screen.clip_top = 0;
609         gr_screen.clip_bottom = h-1;
610         gr_screen.clip_width = w;
611         gr_screen.clip_height = h;
612         
613         glEnable(GL_SCISSOR_TEST);
614         glScissor(x, gr_screen.max_h-y-h, w, h);
615 }
616
617 void gr_opengl_reset_clip()
618 {
619         gr_screen.offset_x = 0;
620         gr_screen.offset_y = 0;
621         gr_screen.clip_left = 0;
622         gr_screen.clip_top = 0;
623         gr_screen.clip_right = gr_screen.max_w - 1;
624         gr_screen.clip_bottom = gr_screen.max_h - 1;
625         gr_screen.clip_width = gr_screen.max_w;
626         gr_screen.clip_height = gr_screen.max_h;
627         
628         glDisable(GL_SCISSOR_TEST);
629 //      glScissor(0, 0, gr_screen.max_w, gr_screen.max_h);
630 }
631
632 void gr_opengl_set_bitmap( int bitmap_num, int alphablend_mode, int bitblt_mode, float alpha, int sx, int sy )
633 {
634         gr_screen.current_alpha = alpha;
635         gr_screen.current_alphablend_mode = alphablend_mode;
636         gr_screen.current_bitblt_mode = bitblt_mode;
637         gr_screen.current_bitmap = bitmap_num;
638
639         gr_screen.current_bitmap_sx = sx;
640         gr_screen.current_bitmap_sy = sy;
641 }
642
643 void gr_opengl_create_shader(shader * shade, float r, float g, float b, float c )
644 {
645         shade->screen_sig = gr_screen.signature;
646         shade->r = r;
647         shade->g = g;
648         shade->b = b;
649         shade->c = c;   
650 }
651
652 void gr_opengl_set_shader( shader * shade )
653 {       
654         if ( shade )    {
655                 if (shade->screen_sig != gr_screen.signature)   {
656                         gr_create_shader( shade, shade->r, shade->g, shade->b, shade->c );
657                 }
658                 gr_screen.current_shader = *shade;
659         } else {
660                 gr_create_shader( &gr_screen.current_shader, 0.0f, 0.0f, 0.0f, 0.0f );
661         }
662 }
663
664
665 void gr_opengl_bitmap_ex_internal(int x,int y,int w,int h,int sx,int sy)
666 {
667         STUB_FUNCTION; /* who called me? */
668 }
669
670
671 void gr_opengl_bitmap_ex(int x,int y,int w,int h,int sx,int sy)
672 {
673         STUB_FUNCTION; /* who called me? */
674 }
675
676 void gr_opengl_bitmap(int x, int y)
677 {
678         STUB_FUNCTION; /* who called me? */
679 }
680
681 static void gr_opengl_rect_internal(int x, int y, int w, int h, int r, int g, int b, int a)
682 {
683         int saved_zbuf;
684         vertex v[4];
685         vertex *verts[4] = {&v[0], &v[1], &v[2], &v[3]};
686
687         saved_zbuf = gr_zbuffer_get();
688         
689         // start the frame, no zbuffering, no culling
690         g3_start_frame(1);      
691         gr_zbuffer_set(GR_ZBUFF_NONE);          
692         gr_set_cull(0);         
693
694         // stuff coords         
695         v[0].sx = i2fl(x);
696         v[0].sy = i2fl(y);
697         v[0].sw = 0.0f;
698         v[0].u = 0.0f;
699         v[0].v = 0.0f;
700         v[0].flags = PF_PROJECTED;
701         v[0].codes = 0;
702         v[0].r = (ubyte)r;
703         v[0].g = (ubyte)g;
704         v[0].b = (ubyte)b;
705         v[0].a = (ubyte)a;
706
707         v[1].sx = i2fl(x + w);
708         v[1].sy = i2fl(y);      
709         v[1].sw = 0.0f;
710         v[1].u = 0.0f;
711         v[1].v = 0.0f;
712         v[1].flags = PF_PROJECTED;
713         v[1].codes = 0;
714         v[1].r = (ubyte)r;
715         v[1].g = (ubyte)g;
716         v[1].b = (ubyte)b;
717         v[1].a = (ubyte)a;
718
719         v[2].sx = i2fl(x + w);
720         v[2].sy = i2fl(y + h);
721         v[2].sw = 0.0f;
722         v[2].u = 0.0f;
723         v[2].v = 0.0f;
724         v[2].flags = PF_PROJECTED;
725         v[2].codes = 0;
726         v[2].r = (ubyte)r;
727         v[2].g = (ubyte)g;
728         v[2].b = (ubyte)b;
729         v[2].a = (ubyte)a;
730
731         v[3].sx = i2fl(x);
732         v[3].sy = i2fl(y + h);
733         v[3].sw = 0.0f;
734         v[3].u = 0.0f;
735         v[3].v = 0.0f;
736         v[3].flags = PF_PROJECTED;
737         v[3].codes = 0;                         
738         v[3].r = (ubyte)r;
739         v[3].g = (ubyte)g;
740         v[3].b = (ubyte)b;
741         v[3].a = (ubyte)a;
742
743         // draw the polys
744         g3_draw_poly_constant_sw(4, verts, TMAP_FLAG_GOURAUD | TMAP_FLAG_RGB | TMAP_FLAG_ALPHA, 0.1f);          
745
746         g3_end_frame();
747
748         // restore zbuffer and culling
749         gr_zbuffer_set(saved_zbuf);
750         gr_set_cull(1); 
751 }
752
753 void gr_opengl_rect(int x,int y,int w,int h)
754 {
755         gr_opengl_rect_internal(x, y, w, h, gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue, gr_screen.current_color.alpha);
756 }
757
758 void gr_opengl_shade(int x,int y,int w,int h)
759 {
760         int r,g,b,a;
761         
762         float shade1 = 1.0f;
763         float shade2 = 6.0f;
764
765         r = fl2i(gr_screen.current_shader.r*255.0f*shade1);
766         if ( r < 0 ) r = 0; else if ( r > 255 ) r = 255;
767         g = fl2i(gr_screen.current_shader.g*255.0f*shade1);
768         if ( g < 0 ) g = 0; else if ( g > 255 ) g = 255;
769         b = fl2i(gr_screen.current_shader.b*255.0f*shade1);
770         if ( b < 0 ) b = 0; else if ( b > 255 ) b = 255;
771         a = fl2i(gr_screen.current_shader.c*255.0f*shade2);
772         if ( a < 0 ) a = 0; else if ( a > 255 ) a = 255;
773
774         gr_opengl_rect_internal(x, y, w, h, r, g, b, a);        
775 }
776
777 static void gr_opengl_aabitmap_ex_internal(int x,int y,int w,int h,int sx,int sy)
778 {
779         if ( w < 1 ) return;
780         if ( h < 1 ) return;
781
782         if ( !gr_screen.current_color.is_alphacolor )   return;
783
784         float u_scale, v_scale;
785
786         if ( !gr_tcache_set( gr_screen.current_bitmap, TCACHE_TYPE_AABITMAP, &u_scale, &v_scale ) )     {
787                 // Couldn't set texture
788                 mprintf(( "WARNING: Error setting aabitmap texture!\n" ));
789                 return;
790         }
791
792         gr_opengl_set_state( TEXTURE_SOURCE_NO_FILTERING, ALPHA_BLEND_ALPHA_BLEND_ALPHA, ZBUFFER_TYPE_NONE );
793         
794         float u0, u1, v0, v1;
795         float x1, x2, y1, y2;
796         int bw, bh;
797
798         bm_get_info( gr_screen.current_bitmap, &bw, &bh );
799
800         u0 = u_scale*i2fl(sx)/i2fl(bw);
801         v0 = v_scale*i2fl(sy)/i2fl(bh);
802
803         u1 = u_scale*i2fl(sx+w)/i2fl(bw);
804         v1 = v_scale*i2fl(sy+h)/i2fl(bh);
805
806         x1 = i2fl(x+gr_screen.offset_x);
807         y1 = i2fl(y+gr_screen.offset_y);
808         x2 = i2fl(x+w+gr_screen.offset_x);
809         y2 = i2fl(y+h+gr_screen.offset_y);
810
811         if ( gr_screen.current_color.is_alphacolor )    {
812                 glColor4ub(gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue,gr_screen.current_color.alpha);
813         } else {
814                 glColor3ub(gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue);
815         }
816
817         glBegin (GL_QUADS);
818           glTexCoord2f (u0, v1);
819           glVertex3f (x1, y2, -0.99);
820
821           glTexCoord2f (u1, v1);
822           glVertex3f (x2, y2, -0.99);
823
824           glTexCoord2f (u1, v0);
825           glVertex3f (x2, y1, -0.99);
826
827           glTexCoord2f (u0, v0);
828           glVertex3f (x1, y1, -0.99);
829         glEnd ();
830 }
831
832 void gr_opengl_aabitmap_ex(int x,int y,int w,int h,int sx,int sy)
833 {
834         int reclip;
835         #ifndef NDEBUG
836         int count = 0;
837         #endif
838
839         int dx1=x, dx2=x+w-1;
840         int dy1=y, dy2=y+h-1;
841
842         int bw, bh;
843         bm_get_info( gr_screen.current_bitmap, &bw, &bh, NULL );
844
845         do {
846                 reclip = 0;
847                 #ifndef NDEBUG
848                         if ( count > 1 ) Int3();
849                         count++;
850                 #endif
851         
852                 if ((dx1 > gr_screen.clip_right ) || (dx2 < gr_screen.clip_left)) return;
853                 if ((dy1 > gr_screen.clip_bottom ) || (dy2 < gr_screen.clip_top)) return;
854                 if ( dx1 < gr_screen.clip_left ) { sx += gr_screen.clip_left-dx1; dx1 = gr_screen.clip_left; }
855                 if ( dy1 < gr_screen.clip_top ) { sy += gr_screen.clip_top-dy1; dy1 = gr_screen.clip_top; }
856                 if ( dx2 > gr_screen.clip_right )       { dx2 = gr_screen.clip_right; }
857                 if ( dy2 > gr_screen.clip_bottom )      { dy2 = gr_screen.clip_bottom; }
858
859                 if ( sx < 0 ) {
860                         dx1 -= sx;
861                         sx = 0;
862                         reclip = 1;
863                 }
864
865                 if ( sy < 0 ) {
866                         dy1 -= sy;
867                         sy = 0;
868                         reclip = 1;
869                 }
870
871                 w = dx2-dx1+1;
872                 h = dy2-dy1+1;
873
874                 if ( sx + w > bw ) {
875                         w = bw - sx;
876                         dx2 = dx1 + w - 1;
877                 }
878
879                 if ( sy + h > bh ) {
880                         h = bh - sy;
881                         dy2 = dy1 + h - 1;
882                 }
883
884                 if ( w < 1 ) return;            // clipped away!
885                 if ( h < 1 ) return;            // clipped away!
886
887         } while (reclip);
888
889         // Make sure clipping algorithm works
890         #ifndef NDEBUG
891                 Assert( w > 0 );
892                 Assert( h > 0 );
893                 Assert( w == (dx2-dx1+1) );
894                 Assert( h == (dy2-dy1+1) );
895                 Assert( sx >= 0 );
896                 Assert( sy >= 0 );
897                 Assert( sx+w <= bw );
898                 Assert( sy+h <= bh );
899                 Assert( dx2 >= dx1 );
900                 Assert( dy2 >= dy1 );
901                 Assert( (dx1 >= gr_screen.clip_left ) && (dx1 <= gr_screen.clip_right) );
902                 Assert( (dx2 >= gr_screen.clip_left ) && (dx2 <= gr_screen.clip_right) );
903                 Assert( (dy1 >= gr_screen.clip_top ) && (dy1 <= gr_screen.clip_bottom) );
904                 Assert( (dy2 >= gr_screen.clip_top ) && (dy2 <= gr_screen.clip_bottom) );
905         #endif
906
907         // We now have dx1,dy1 and dx2,dy2 and sx, sy all set validly within clip regions.
908         gr_opengl_aabitmap_ex_internal(dx1,dy1,dx2-dx1+1,dy2-dy1+1,sx,sy);
909 }
910
911 void gr_opengl_aabitmap(int x, int y)
912 {
913         int w, h;
914
915         bm_get_info( gr_screen.current_bitmap, &w, &h, NULL );
916         int dx1=x, dx2=x+w-1;
917         int dy1=y, dy2=y+h-1;
918         int sx=0, sy=0;
919
920         if ((dx1 > gr_screen.clip_right ) || (dx2 < gr_screen.clip_left)) return;
921         if ((dy1 > gr_screen.clip_bottom ) || (dy2 < gr_screen.clip_top)) return;
922         if ( dx1 < gr_screen.clip_left ) { sx = gr_screen.clip_left-dx1; dx1 = gr_screen.clip_left; }
923         if ( dy1 < gr_screen.clip_top ) { sy = gr_screen.clip_top-dy1; dy1 = gr_screen.clip_top; }
924         if ( dx2 > gr_screen.clip_right )       { dx2 = gr_screen.clip_right; }
925         if ( dy2 > gr_screen.clip_bottom )      { dy2 = gr_screen.clip_bottom; }
926
927         if ( sx < 0 ) return;
928         if ( sy < 0 ) return;
929         if ( sx >= w ) return;
930         if ( sy >= h ) return;
931
932         // Draw bitmap bm[sx,sy] into (dx1,dy1)-(dx2,dy2)
933         gr_aabitmap_ex(dx1,dy1,dx2-dx1+1,dy2-dy1+1,sx,sy);
934 }
935
936 void gr_opengl_string( int sx, int sy, char *s )
937 {
938         int width, spacing, letter;
939         int x, y;
940
941         if ( !Current_font )    {
942                 return;
943         }
944
945         gr_set_bitmap(Current_font->bitmap_id);
946
947         x = sx;
948         y = sy;
949
950         if (sx==0x8000) {                       //centered
951                 x = get_centered_x(s);
952         } else {
953                 x = sx;
954         }
955         
956         spacing = 0;
957
958         while (*s)      {
959                 x += spacing;
960
961                 while (*s== '\n' )      {
962                         s++;
963                         y += Current_font->h;
964                         if (sx==0x8000) {                       //centered
965                                 x = get_centered_x(s);
966                         } else {
967                                 x = sx;
968                         }
969                 }
970                 if (*s == 0 ) break;
971
972                 letter = get_char_width(s[0],s[1],&width,&spacing);
973                 s++;
974
975                 //not in font, draw as space
976                 if (letter<0)   {
977                         continue;
978                 }
979
980                 int xd, yd, xc, yc;
981                 int wc, hc;
982
983                 // Check if this character is totally clipped
984                 if ( x + width < gr_screen.clip_left ) continue;
985                 if ( y + Current_font->h < gr_screen.clip_top ) continue;
986                 if ( x > gr_screen.clip_right ) continue;
987                 if ( y > gr_screen.clip_bottom ) continue;
988
989                 xd = yd = 0;
990                 if ( x < gr_screen.clip_left ) xd = gr_screen.clip_left - x;
991                 if ( y < gr_screen.clip_top ) yd = gr_screen.clip_top - y;
992                 xc = x+xd;
993                 yc = y+yd;
994
995                 wc = width - xd; hc = Current_font->h - yd;
996                 if ( xc + wc > gr_screen.clip_right ) wc = gr_screen.clip_right - xc;
997                 if ( yc + hc > gr_screen.clip_bottom ) hc = gr_screen.clip_bottom - yc;
998
999                 if ( wc < 1 ) continue;
1000                 if ( hc < 1 ) continue;
1001
1002                 int u = Current_font->bm_u[letter];
1003                 int v = Current_font->bm_v[letter];
1004
1005                 gr_opengl_aabitmap_ex_internal( xc, yc, wc, hc, u+xd, v+yd );
1006         }
1007 }
1008
1009 void gr_opengl_line(int x1,int y1,int x2,int y2)
1010 {
1011         int clipped = 0, swapped=0;
1012
1013         gr_opengl_set_state( TEXTURE_SOURCE_NONE, ALPHA_BLEND_ALPHA_BLEND_ALPHA, ZBUFFER_TYPE_NONE );
1014         
1015         INT_CLIPLINE(x1,y1,x2,y2,gr_screen.clip_left,gr_screen.clip_top,gr_screen.clip_right,gr_screen.clip_bottom,return,clipped=1,swapped=1);
1016         
1017         float sx1, sy1;
1018         float sx2, sy2;
1019         
1020         sx1 = i2fl(x1 + gr_screen.offset_x)+0.5;
1021         sy1 = i2fl(y1 + gr_screen.offset_y)+0.5;
1022         sx2 = i2fl(x2 + gr_screen.offset_x)+0.5;
1023         sy2 = i2fl(y2 + gr_screen.offset_y)+0.5;
1024         
1025         if ( x1 == x2 && y1 == y2 ) {
1026                 glBegin (GL_POINTS);
1027                   glColor4ub (gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue, gr_screen.current_color.alpha);
1028                   glVertex3f (sx1, sy1, -0.99f);
1029                 glEnd ();
1030                 
1031                 return;
1032         }
1033         
1034         if ( x1 == x2 ) {
1035                 if ( sy1 < sy2 )    {
1036                         sy2 += 0.5f;
1037                 } else {
1038                         sy1 += 0.5f;
1039                 }
1040         } else if ( y1 == y2 )  {
1041                 if ( sx1 < sx2 )    {
1042                         sx2 += 0.5f;
1043                 } else {
1044                         sx1 += 0.5f;
1045                 }
1046         }
1047         
1048         glBegin (GL_LINES);
1049           glColor4ub (gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue, gr_screen.current_color.alpha);
1050           glVertex3f (sx2, sy2, -0.99f);
1051           glVertex3f (sx1, sy1, -0.99f);
1052         glEnd ();
1053 }
1054
1055 void gr_opengl_aaline(vertex *v1, vertex *v2)
1056 {
1057         gr_opengl_line( fl2i(v1->sx), fl2i(v1->sy), fl2i(v2->sx), fl2i(v2->sy) );
1058 }
1059
1060 void gr_opengl_gradient(int x1,int y1,int x2,int y2)
1061 {
1062         int clipped = 0, swapped=0;
1063
1064         if ( !gr_screen.current_color.is_alphacolor )   {
1065                 gr_line( x1, y1, x2, y2 );
1066                 return;
1067         }
1068
1069         INT_CLIPLINE(x1,y1,x2,y2,gr_screen.clip_left,gr_screen.clip_top,gr_screen.clip_right,gr_screen.clip_bottom,return,clipped=1,swapped=1);
1070
1071         gr_opengl_set_state( TEXTURE_SOURCE_NONE, ALPHA_BLEND_ALPHA_BLEND_ALPHA, ZBUFFER_TYPE_NONE );
1072
1073         int aa = swapped ? 0 : gr_screen.current_color.alpha;
1074         int ba = swapped ? gr_screen.current_color.alpha : 0;
1075         
1076         float sx1, sy1;
1077         float sx2, sy2;
1078         
1079         sx1 = i2fl(x1 + gr_screen.offset_x)+0.5;
1080         sy1 = i2fl(y1 + gr_screen.offset_y)+0.5;
1081         sx2 = i2fl(x2 + gr_screen.offset_x)+0.5;
1082         sy2 = i2fl(y2 + gr_screen.offset_y)+0.5;
1083
1084         if ( x1 == x2 ) {
1085                 if ( sy1 < sy2 )    {
1086                         sy2 += 0.5f;
1087                 } else {
1088                         sy1 += 0.5f;
1089                 }
1090         } else if ( y1 == y2 )  {
1091                 if ( sx1 < sx2 )    {
1092                         sx2 += 0.5f;
1093                 } else {
1094                         sx1 += 0.5f;
1095                 }
1096         }
1097         
1098         glBegin (GL_LINES);
1099           glColor4ub (gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue, ba);
1100           glVertex3f (sx2, sy2, -0.99f);
1101           glColor4ub (gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue, aa);
1102           glVertex3f (sx1, sy1, -0.99f);
1103         glEnd ();       
1104 }
1105
1106 void gr_opengl_circle( int xc, int yc, int d )
1107 {
1108         int p,x, y, r;
1109
1110         r = d/2;
1111         p=3-d;
1112         x=0;
1113         y=r;
1114
1115         // Big clip
1116         if ( (xc+r) < gr_screen.clip_left ) return;
1117         if ( (xc-r) > gr_screen.clip_right ) return;
1118         if ( (yc+r) < gr_screen.clip_top ) return;
1119         if ( (yc-r) > gr_screen.clip_bottom ) return;
1120
1121         while(x<y)      {
1122                 // Draw the first octant
1123                 gr_opengl_line( xc-y, yc-x, xc+y, yc-x );
1124                 gr_opengl_line( xc-y, yc+x, xc+y, yc+x );
1125                                 
1126                 if (p<0) 
1127                         p=p+(x<<2)+6;
1128                 else    {
1129                         // Draw the second octant
1130                         gr_opengl_line( xc-x, yc-y, xc+x, yc-y );
1131                         gr_opengl_line( xc-x, yc+y, xc+x, yc+y );
1132                                                 
1133                         p=p+((x-y)<<2)+10;
1134                         y--;
1135                 }
1136                 x++;
1137         }
1138         if(x==y) {
1139                 gr_opengl_line( xc-x, yc-y, xc+x, yc-y );
1140                 gr_opengl_line( xc-x, yc+y, xc+x, yc+y );
1141         }
1142         return;
1143 }
1144
1145 static void gr_opengl_stuff_fog_value(float z, int *r, int *g, int *b, int *a)
1146 {
1147         float f_float;
1148         
1149         f_float = (gr_screen.fog_far - z) / (gr_screen.fog_far - gr_screen.fog_near);
1150         if (f_float < 0.0f) {
1151                 f_float = 0.0f;
1152         } else {
1153                 f_float = 1.0f;
1154         }
1155         *r = 0;
1156         *g = 0;
1157         *b = 0;
1158         *a = (int)(f_float * 255.0);
1159 }
1160
1161 static void gr_opengl_tmapper_internal( int nv, vertex ** verts, uint flags, int is_scaler )
1162 {
1163         int i;
1164         float u_scale = 1.0f, v_scale = 1.0f;
1165
1166         // Make nebula use the texture mapper... this blends the colors better.
1167         if ( flags & TMAP_FLAG_NEBULA ){
1168                 Int3 ();
1169         }
1170
1171         gr_texture_source texture_source = (gr_texture_source)-1;
1172         gr_alpha_blend alpha_blend = (gr_alpha_blend)-1;
1173         gr_zbuffer_type zbuffer_type = (gr_zbuffer_type)-1;
1174         
1175         if ( gr_zbuffering )    {
1176                 if ( is_scaler || (gr_screen.current_alphablend_mode == GR_ALPHABLEND_FILTER)   )       {
1177                         zbuffer_type = ZBUFFER_TYPE_READ;
1178                 } else {
1179                         zbuffer_type = ZBUFFER_TYPE_FULL;
1180                 }
1181         } else {
1182                 zbuffer_type = ZBUFFER_TYPE_NONE;
1183         }
1184         
1185         int alpha;
1186
1187         int tmap_type = TCACHE_TYPE_NORMAL;
1188
1189         int r, g, b;
1190
1191         if ( flags & TMAP_FLAG_TEXTURED )       {
1192                 r = g = b = 255;
1193         } else {
1194                 r = gr_screen.current_color.red;
1195                 g = gr_screen.current_color.green;
1196                 b = gr_screen.current_color.blue;
1197         }
1198
1199         if ( gr_screen.current_alphablend_mode == GR_ALPHABLEND_FILTER )        
1200         {
1201                 if (1) {
1202                         tmap_type = TCACHE_TYPE_NORMAL;
1203                         alpha_blend = ALPHA_BLEND_ALPHA_ADDITIVE;
1204                         
1205                         // Blend with screen pixel using src*alpha+dst
1206                         float factor = gr_screen.current_alpha;
1207                         
1208                         alpha = 255;
1209                         
1210                         if ( factor <= 1.0f )   {
1211                                 int tmp_alpha = fl2i(gr_screen.current_alpha*255.0f);
1212                                 r = (r*tmp_alpha)/255;
1213                                 g = (g*tmp_alpha)/255;
1214                                 b = (b*tmp_alpha)/255;
1215                         }
1216                 } else {
1217                         tmap_type = TCACHE_TYPE_XPARENT;
1218                         
1219                         alpha_blend = ALPHA_BLEND_ALPHA_BLEND_ALPHA;
1220                         
1221                         // Blend with screen pixel using src*alpha+dst
1222                         float factor = gr_screen.current_alpha;
1223                                 
1224                         if ( factor > 1.0f )    {
1225                                 alpha = 255;
1226                         } else {
1227                                 alpha = fl2i(gr_screen.current_alpha*255.0f);
1228                         }
1229                 }
1230         } else {
1231                 if(Bm_pixel_format == BM_PIXEL_FORMAT_ARGB) {
1232                         alpha_blend = ALPHA_BLEND_ALPHA_BLEND_ALPHA;
1233                 } else {
1234                         alpha_blend = ALPHA_BLEND_NONE;
1235                 }
1236                 alpha = 255;
1237         }
1238
1239         if(flags & TMAP_FLAG_BITMAP_SECTION){
1240                 tmap_type = TCACHE_TYPE_BITMAP_SECTION;
1241         }
1242         
1243         texture_source = TEXTURE_SOURCE_NONE;
1244         
1245         if ( flags & TMAP_FLAG_TEXTURED )       {
1246                 if ( !gr_tcache_set(gr_screen.current_bitmap, tmap_type, &u_scale, &v_scale, 0, gr_screen.current_bitmap_sx, gr_screen.current_bitmap_sy ))
1247                 {
1248                         mprintf(( "Not rendering a texture because it didn't fit in VRAM!\n" ));
1249                         return;
1250                 }
1251
1252                 // use nonfiltered textures for bitmap sections
1253                 if(flags & TMAP_FLAG_BITMAP_SECTION){
1254                         texture_source = TEXTURE_SOURCE_NO_FILTERING;
1255                 } else {
1256                         texture_source = TEXTURE_SOURCE_DECAL;
1257                 }
1258         }
1259
1260
1261         gr_opengl_set_state( texture_source, alpha_blend, zbuffer_type );
1262         
1263         if ( flags & TMAP_FLAG_TEXTURED )
1264         {
1265                 // rendition junk
1266                 // STUB_FUNCTION;
1267         }
1268
1269         if (flags & TMAP_FLAG_PIXEL_FOG) {
1270                 int r, g, b;
1271                 int ra, ga, ba;
1272                 ra = ga = ba = 0;
1273         
1274                 /* argh */
1275                 for (i=nv-1;i>=0;i--)   // DDOI - change polygon winding
1276                 {
1277                         vertex * va = verts[i];
1278                         float sx, sy;
1279                 
1280                         int x, y;
1281                         x = fl2i(va->sx*16.0f);
1282                         y = fl2i(va->sy*16.0f);
1283                 
1284                         x += gr_screen.offset_x*16;
1285                         y += gr_screen.offset_y*16;
1286                 
1287                         sx = i2fl(x) / 16.0f;
1288                         sy = i2fl(y) / 16.0f;
1289                 
1290                         neb2_get_pixel((int)sx, (int)sy, &r, &g, &b);
1291                         
1292                         ra += r;
1293                         ga += g;
1294                         ba += b;
1295                 }
1296                 
1297                 ra /= nv;
1298                 ga /= nv;
1299                 ba /= nv;
1300                 
1301                 gr_fog_set(GR_FOGMODE_FOG, ra, ga, ba);
1302         }
1303         
1304         glBegin(GL_TRIANGLE_FAN);
1305         for (i = nv-1; i >= 0; i--) {           
1306                 vertex * va = verts[i];
1307                 float sx, sy, sz;
1308                 float tu, tv;
1309                 float rhw;
1310                 int a;
1311                 
1312                 if ( gr_zbuffering || (flags & TMAP_FLAG_NEBULA) )      {
1313                         sz = 1.0 - 1.0 / (1.0 + va->z / (32768.0 / 256.0));
1314                         
1315                         if ( sz > 0.98f ) {
1316                                 sz = 0.98f;
1317                         }
1318                 } else {
1319                         sz = 0.99f;
1320                 }
1321
1322                 if ( flags & TMAP_FLAG_CORRECT )        {
1323                         rhw = va->sw;
1324                 } else {
1325                         rhw = 1.0f;
1326                 }
1327                 
1328                 if (flags & TMAP_FLAG_ALPHA) {
1329                         a = verts[i]->a;
1330                 } else {
1331                         a = alpha;
1332                 }
1333
1334                 if (flags & TMAP_FLAG_NEBULA ) {
1335                         int pal = (verts[i]->b*(NEBULA_COLORS-1))/255;
1336                         r = gr_palette[pal*3+0];
1337                         g = gr_palette[pal*3+1];
1338                         b = gr_palette[pal*3+2];
1339                 } else if ( (flags & TMAP_FLAG_RAMP) && (flags & TMAP_FLAG_GOURAUD) )   {
1340                         r = Gr_gamma_lookup[verts[i]->b];
1341                         g = Gr_gamma_lookup[verts[i]->b];
1342                         b = Gr_gamma_lookup[verts[i]->b];
1343                 } else if ( (flags & TMAP_FLAG_RGB)  && (flags & TMAP_FLAG_GOURAUD) )   {
1344                         // Make 0.75 be 256.0f
1345                         r = Gr_gamma_lookup[verts[i]->r];
1346                         g = Gr_gamma_lookup[verts[i]->g];
1347                         b = Gr_gamma_lookup[verts[i]->b];
1348                 } else {
1349                         // use constant RGB values...
1350                 }
1351                 glColor4ub (r,g,b,a);
1352
1353                 if((gr_screen.current_fog_mode != GR_FOGMODE_NONE) && (D3D_fog_mode == 1)){
1354                         int sr, sg, sb, sa;
1355                         
1356                         /* this is for GL_EXT_SECONDARY_COLOR */
1357                         gr_opengl_stuff_fog_value(va->z, &sr, &sg, &sb, &sa);
1358                         /* do separate color call here */
1359                         
1360                         STUB_FUNCTION;
1361                 }
1362                 
1363                 int x, y;
1364                 x = fl2i(va->sx*16.0f);
1365                 y = fl2i(va->sy*16.0f);
1366
1367                 x += gr_screen.offset_x*16;
1368                 y += gr_screen.offset_y*16;
1369                 
1370                 sx = i2fl(x) / 16.0f;
1371                 sy = i2fl(y) / 16.0f;
1372
1373                 if ( flags & TMAP_FLAG_TEXTURED )       {
1374                         tu = va->u*u_scale;
1375                         tv = va->v*v_scale;
1376                         glTexCoord2f(tu, tv);
1377                 }
1378                 
1379                 glVertex4f(sx/rhw, sy/rhw, -sz/rhw, 1.0/rhw);
1380         }
1381         glEnd();
1382 }
1383
1384 void gr_opengl_tmapper( int nverts, vertex **verts, uint flags )
1385 {
1386         gr_opengl_tmapper_internal( nverts, verts, flags, 0 );
1387 }
1388
1389 #define FIND_SCALED_NUM(x,x0,x1,y0,y1) (((((x)-(x0))*((y1)-(y0)))/((x1)-(x0)))+(y0))
1390
1391 void gr_opengl_scaler(vertex *va, vertex *vb )
1392 {
1393         float x0, y0, x1, y1;
1394         float u0, v0, u1, v1;
1395         float clipped_x0, clipped_y0, clipped_x1, clipped_y1;
1396         float clipped_u0, clipped_v0, clipped_u1, clipped_v1;
1397         float xmin, xmax, ymin, ymax;
1398         int dx0, dy0, dx1, dy1;
1399
1400         //============= CLIP IT =====================
1401
1402         x0 = va->sx; y0 = va->sy;
1403         x1 = vb->sx; y1 = vb->sy;
1404
1405         xmin = i2fl(gr_screen.clip_left); ymin = i2fl(gr_screen.clip_top);
1406         xmax = i2fl(gr_screen.clip_right); ymax = i2fl(gr_screen.clip_bottom);
1407
1408         u0 = va->u; v0 = va->v;
1409         u1 = vb->u; v1 = vb->v;
1410
1411         // Check for obviously offscreen bitmaps...
1412         if ( (y1<=y0) || (x1<=x0) ) return;
1413         if ( (x1<xmin ) || (x0>xmax) ) return;
1414         if ( (y1<ymin ) || (y0>ymax) ) return;
1415
1416         clipped_u0 = u0; clipped_v0 = v0;
1417         clipped_u1 = u1; clipped_v1 = v1;
1418
1419         clipped_x0 = x0; clipped_y0 = y0;
1420         clipped_x1 = x1; clipped_y1 = y1;
1421
1422         // Clip the left, moving u0 right as necessary
1423         if ( x0 < xmin )        {
1424                 clipped_u0 = FIND_SCALED_NUM(xmin,x0,x1,u0,u1);
1425                 clipped_x0 = xmin;
1426         }
1427
1428         // Clip the right, moving u1 left as necessary
1429         if ( x1 > xmax )        {
1430                 clipped_u1 = FIND_SCALED_NUM(xmax,x0,x1,u0,u1);
1431                 clipped_x1 = xmax;
1432         }
1433
1434         // Clip the top, moving v0 down as necessary
1435         if ( y0 < ymin )        {
1436                 clipped_v0 = FIND_SCALED_NUM(ymin,y0,y1,v0,v1);
1437                 clipped_y0 = ymin;
1438         }
1439
1440         // Clip the bottom, moving v1 up as necessary
1441         if ( y1 > ymax )        {
1442                 clipped_v1 = FIND_SCALED_NUM(ymax,y0,y1,v0,v1);
1443                 clipped_y1 = ymax;
1444         }
1445         
1446         dx0 = fl2i(clipped_x0); dx1 = fl2i(clipped_x1);
1447         dy0 = fl2i(clipped_y0); dy1 = fl2i(clipped_y1);
1448
1449         if (dx1<=dx0) return;
1450         if (dy1<=dy0) return;
1451
1452         //============= DRAW IT =====================
1453
1454         vertex v[4];
1455         vertex *vl[4];
1456
1457         vl[0] = &v[0];  
1458         v->sx = clipped_x0;
1459         v->sy = clipped_y0;
1460         v->sw = va->sw;
1461         v->z = va->z;
1462         v->u = clipped_u0;
1463         v->v = clipped_v0;
1464
1465         vl[1] = &v[1];  
1466         v[1].sx = clipped_x1;
1467         v[1].sy = clipped_y0;
1468         v[1].sw = va->sw;
1469         v[1].z = va->z;
1470         v[1].u = clipped_u1;
1471         v[1].v = clipped_v0;
1472
1473         vl[2] = &v[2];  
1474         v[2].sx = clipped_x1;
1475         v[2].sy = clipped_y1;
1476         v[2].sw = va->sw;
1477         v[2].z = va->z;
1478         v[2].u = clipped_u1;
1479         v[2].v = clipped_v1;
1480
1481         vl[3] = &v[3];  
1482         v[3].sx = clipped_x0;
1483         v[3].sy = clipped_y1;
1484         v[3].sw = va->sw;
1485         v[3].z = va->z;
1486         v[3].u = clipped_u0;
1487         v[3].v = clipped_v1;
1488
1489         gr_opengl_tmapper_internal( 4, vl, TMAP_FLAG_TEXTURED, 1 );
1490 }
1491
1492 void gr_opengl_set_palette(ubyte *new_palette, int is_alphacolor)
1493 {
1494 }
1495
1496 void gr_opengl_get_color( int * r, int * g, int * b )
1497 {
1498         if (r) *r = gr_screen.current_color.red;
1499         if (g) *g = gr_screen.current_color.green;
1500         if (b) *b = gr_screen.current_color.blue;
1501 }
1502
1503 void gr_opengl_init_color(color *c, int r, int g, int b)
1504 {
1505         c->screen_sig = gr_screen.signature;
1506         c->red = (unsigned char)r;
1507         c->green = (unsigned char)g;
1508         c->blue = (unsigned char)b;
1509         c->alpha = 255;
1510         c->ac_type = AC_TYPE_NONE;
1511         c->alphacolor = -1;
1512         c->is_alphacolor = 0;
1513         c->magic = 0xAC01;
1514 }
1515
1516 void gr_opengl_init_alphacolor( color *clr, int r, int g, int b, int alpha, int type )
1517 {
1518         if ( r < 0 ) r = 0; else if ( r > 255 ) r = 255;
1519         if ( g < 0 ) g = 0; else if ( g > 255 ) g = 255;
1520         if ( b < 0 ) b = 0; else if ( b > 255 ) b = 255;
1521         if ( alpha < 0 ) alpha = 0; else if ( alpha > 255 ) alpha = 255;
1522
1523         gr_opengl_init_color( clr, r, g, b );
1524
1525         clr->alpha = (unsigned char)alpha;
1526         clr->ac_type = (ubyte)type;
1527         clr->alphacolor = -1;
1528         clr->is_alphacolor = 1;
1529 }
1530
1531 void gr_opengl_set_color( int r, int g, int b )
1532 {
1533         Assert((r >= 0) && (r < 256));
1534         Assert((g >= 0) && (g < 256));
1535         Assert((b >= 0) && (b < 256));
1536
1537         gr_opengl_init_color( &gr_screen.current_color, r, g, b );      
1538 }
1539
1540 void gr_opengl_set_color_fast(color *dst)
1541 {
1542         if ( dst->screen_sig != gr_screen.signature )   {
1543                 if ( dst->is_alphacolor )       {
1544                         gr_opengl_init_alphacolor( dst, dst->red, dst->green, dst->blue, dst->alpha, dst->ac_type );
1545                 } else {
1546                         gr_opengl_init_color( dst, dst->red, dst->green, dst->blue );
1547                 }
1548         }
1549         gr_screen.current_color = *dst;
1550 }
1551
1552 void gr_opengl_print_screen(char *filename)
1553 {
1554         STUB_FUNCTION;
1555 }
1556
1557 int gr_opengl_supports_res_ingame(int res)
1558 {
1559         STUB_FUNCTION;
1560         
1561         return 1;
1562 }
1563
1564 int gr_opengl_supports_res_interface(int res)
1565 {
1566         STUB_FUNCTION;
1567         
1568         return 1;
1569 }
1570
1571 void opengl_tcache_cleanup ();
1572 void gr_opengl_cleanup()
1573 {
1574         if ( !Inited )  return;
1575
1576
1577         gr_reset_clip();
1578         gr_clear();
1579         gr_flip();
1580
1581         opengl_tcache_cleanup ();
1582
1583         Inited = 0;
1584 }
1585
1586 void gr_opengl_fog_set(int fog_mode, int r, int g, int b, float fog_near, float fog_far)
1587 {
1588         Assert((r >= 0) && (r < 256));
1589         Assert((g >= 0) && (g < 256));
1590         Assert((b >= 0) && (b < 256));
1591         
1592         if (fog_mode == GR_FOGMODE_NONE) {
1593                 if (gr_screen.current_fog_mode != fog_mode) {
1594                         glDisable(GL_FOG);
1595                 }
1596                 gr_screen.current_fog_mode = fog_mode;
1597                 
1598                 return;
1599         }
1600         
1601         if (gr_screen.current_fog_mode != fog_mode) {
1602                 glEnable(GL_FOG);
1603                 
1604                 if (D3D_fog_mode == 2) {
1605                         glFogi(GL_FOG_MODE, GL_LINEAR);
1606                 }
1607                 
1608                 gr_screen.current_fog_mode = fog_mode;
1609         }
1610         
1611         if ( (gr_screen.current_fog_color.red != r) ||
1612                         (gr_screen.current_fog_color.green != g) ||
1613                         (gr_screen.current_fog_color.blue != b) ) {
1614                 GLfloat fc[4];
1615                 
1616                 gr_opengl_init_color( &gr_screen.current_fog_color, r, g, b );
1617         
1618                 fc[0] = (float)r/255.0;
1619                 fc[1] = (float)g/255.0;
1620                 fc[2] = (float)b/255.0;
1621                 fc[3] = 1.0;
1622                 
1623                 glFogfv(GL_FOG_COLOR, fc);
1624         }
1625         
1626         if( (fog_near >= 0.0f) && (fog_far >= 0.0f) && 
1627                         ((fog_near != gr_screen.fog_near) || 
1628                         (fog_far != gr_screen.fog_far)) ) {
1629                 gr_screen.fog_near = fog_near;
1630                 gr_screen.fog_far = fog_far;
1631                 
1632                 if (D3D_fog_mode == 2) {
1633                         glFogf(GL_FOG_START, fog_near);
1634                         glFogf(GL_FOG_END, fog_far);
1635                 }
1636         }
1637 }
1638
1639 void gr_opengl_get_pixel(int x, int y, int *r, int *g, int *b)
1640 {
1641         // Not used.
1642 }
1643
1644 void gr_opengl_set_cull(int cull)
1645 {
1646         if (cull) {
1647                 glEnable (GL_CULL_FACE);
1648                 glFrontFace (GL_CCW);
1649         } else {
1650                 glDisable (GL_CULL_FACE);
1651         }
1652 }
1653
1654 void gr_opengl_filter_set(int filter)
1655 {
1656 }
1657
1658 // cross fade
1659 void gr_opengl_cross_fade(int bmap1, int bmap2, int x1, int y1, int x2, int y2, float pct)
1660 {
1661         if ( pct <= 50 ) {
1662                 gr_set_bitmap(bmap1);
1663                 gr_bitmap(x1, y1);
1664         } else {
1665                 gr_set_bitmap(bmap2);
1666                 gr_bitmap(x2, y2);
1667         }               
1668 }
1669
1670
1671 typedef struct tcache_slot_opengl {
1672         GLuint  texture_handle;
1673         float   u_scale, v_scale;
1674         int     bitmap_id;
1675         int     size;
1676         int     used_this_frame;
1677         int     time_created;
1678         ushort  w,h;
1679
1680         // sections
1681         tcache_slot_opengl      *data_sections[MAX_BMAP_SECTIONS_X][MAX_BMAP_SECTIONS_Y];
1682         tcache_slot_opengl      *parent;
1683         
1684         gr_texture_source       texture_mode;
1685 } tcache_slot_opengl;
1686
1687 static void *Texture_sections = NULL;
1688 static tcache_slot_opengl *Textures = NULL;
1689
1690 static tcache_slot_opengl *GL_bound_texture;
1691
1692 int GL_texture_sections = 0;
1693 int GL_texture_ram = 0;
1694 int GL_frame_count = 0;
1695 int GL_min_texture_width = 0;
1696 int GL_max_texture_width = 0;
1697 int GL_min_texture_height = 0;
1698 int GL_max_texture_height = 0;
1699 int GL_square_textures = 0;
1700 int GL_textures_in = 0;
1701 int GL_textures_in_frame = 0;
1702 int GL_last_bitmap_id = -1;
1703 int GL_last_detail = -1;
1704 int GL_last_bitmap_type = -1;
1705 int GL_last_section_x = -1;
1706 int GL_last_section_y = -1;
1707
1708 int vram_full = 0;
1709
1710 static gr_texture_source GL_current_texture_source = (gr_texture_source) -1;
1711
1712 static void gr_opengl_set_texture_state(gr_texture_source ts)
1713 {
1714         if (ts == TEXTURE_SOURCE_NONE) {
1715                 GL_bound_texture = NULL;
1716                                 
1717                 glBindTexture(GL_TEXTURE_2D, 0);
1718                 gr_tcache_set(-1, -1, NULL, NULL );
1719         } else if (GL_bound_texture &&
1720                 GL_bound_texture->texture_mode != ts) {
1721                 switch (ts) {
1722                         case TEXTURE_SOURCE_DECAL:
1723                                 glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1724                                 glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1725                                 break;
1726                         case TEXTURE_SOURCE_NO_FILTERING:
1727                                 glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1728                                 glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1729                                 break;
1730                         default:
1731                                 break;
1732                 }
1733                         
1734                 GL_bound_texture->texture_mode = ts;
1735         }
1736         
1737         GL_current_texture_source = ts;
1738 }
1739
1740 void opengl_tcache_init (int use_sections)
1741 {
1742         int i, idx, s_idx;
1743
1744         // DDOI - FIXME skipped a lot of stuff here
1745         GL_should_preload = 0;
1746
1747         //uint tmp_pl = os_config_read_uint( NULL, NOX("D3DPreloadTextures"), 255 );
1748         uint tmp_pl = 1;
1749
1750         if ( tmp_pl == 0 )      {
1751                 GL_should_preload = 0;
1752         } else if ( tmp_pl == 1 )       {
1753                 GL_should_preload = 1;
1754         } else {
1755                 GL_should_preload = 1;
1756         }
1757
1758         STUB_FUNCTION;
1759
1760         GL_min_texture_width = 16;
1761         GL_min_texture_height = 16;
1762         GL_max_texture_width = 256;
1763         GL_max_texture_height = 256;
1764
1765         GL_square_textures = 1;
1766
1767         Textures = (tcache_slot_opengl *)malloc(MAX_BITMAPS*sizeof(tcache_slot_opengl));
1768         if ( !Textures )        {
1769                 exit(1);
1770         }
1771
1772         if(use_sections){
1773                 Texture_sections = (tcache_slot_opengl*)malloc(MAX_BITMAPS * MAX_BMAP_SECTIONS_X * MAX_BMAP_SECTIONS_Y * sizeof(tcache_slot_opengl));
1774                 if(!Texture_sections){
1775                         exit(1);
1776                 }
1777                 memset(Texture_sections, 0, MAX_BITMAPS * MAX_BMAP_SECTIONS_X * MAX_BMAP_SECTIONS_Y * sizeof(tcache_slot_opengl));
1778         }
1779
1780         // Init the texture structures
1781         int section_count = 0;
1782         for( i=0; i<MAX_BITMAPS; i++ )  {
1783                 /*
1784                 Textures[i].vram_texture = NULL;
1785                 Textures[i].vram_texture_surface = NULL;
1786                 */
1787                 Textures[i].texture_handle = 0;
1788
1789                 Textures[i].bitmap_id = -1;
1790                 Textures[i].size = 0;
1791                 Textures[i].used_this_frame = 0;
1792
1793                 Textures[i].parent = NULL;
1794
1795                 // allocate sections
1796                 if(use_sections){
1797                         for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
1798                                 for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
1799                                         Textures[i].data_sections[idx][s_idx] = &((tcache_slot_opengl*)Texture_sections)[section_count++];
1800                                         Textures[i].data_sections[idx][s_idx]->parent = &Textures[i];
1801                                         /*
1802                                         Textures[i].data_sections[idx][s_idx]->vram_texture = NULL;
1803                                         Textures[i].data_sections[idx][s_idx]->vram_texture_surface = NULL;
1804                                         */
1805                                         Textures[i].data_sections[idx][s_idx]->texture_handle = 0;
1806                                         Textures[i].data_sections[idx][s_idx]->bitmap_id = -1;
1807                                         Textures[i].data_sections[idx][s_idx]->size = 0;
1808                                         Textures[i].data_sections[idx][s_idx]->used_this_frame = 0;
1809                                 }
1810                         }
1811                 } else {
1812                         for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
1813                                 for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
1814                                         Textures[i].data_sections[idx][s_idx] = NULL;
1815                                 }
1816                         }
1817                 }
1818         }
1819
1820         GL_texture_sections = use_sections;
1821
1822         //GL_last_detail = Detail.hardware_textures;
1823         GL_last_bitmap_id = -1;
1824         GL_last_bitmap_type = -1;
1825
1826         GL_last_section_x = -1;
1827         GL_last_section_y = -1;
1828
1829         GL_textures_in = 0;
1830         GL_textures_in_frame = 0;
1831 }
1832
1833 int opengl_free_texture (tcache_slot_opengl *t);
1834
1835 void opengl_free_texture_with_handle(int handle)
1836 {
1837         for(int i=0; i<MAX_BITMAPS; i++ )  {
1838                 if (Textures[i].bitmap_id == handle) {
1839                         Textures[i].used_this_frame = 0; // this bmp doesn't even exist any longer...
1840                         opengl_free_texture ( &Textures[i] );
1841                 }
1842         }
1843 }
1844
1845 void opengl_tcache_flush ()
1846 {
1847         int i;
1848
1849         for( i=0; i<MAX_BITMAPS; i++ )  {
1850                 opengl_free_texture ( &Textures[i] );
1851         }
1852         if (GL_textures_in != 0) {
1853                 mprintf(( "WARNING: VRAM is at %d instead of zero after flushing!\n", GL_textures_in ));
1854                 GL_textures_in = 0;
1855         }
1856
1857         GL_last_bitmap_id = -1;
1858         GL_last_section_x = -1;
1859         GL_last_section_y = -1;
1860 }
1861
1862 void opengl_tcache_cleanup ()
1863 {
1864         opengl_tcache_flush ();
1865
1866         GL_textures_in = 0;
1867         GL_textures_in_frame = 0;
1868
1869         if ( Textures ) {
1870                 free(Textures);
1871                 Textures = NULL;
1872         }
1873
1874         if( Texture_sections != NULL ){
1875                 free(Texture_sections);
1876                 Texture_sections = NULL;
1877         }
1878 }
1879
1880 void opengl_tcache_frame ()
1881 {
1882         int idx, s_idx;
1883
1884         GL_last_bitmap_id = -1;
1885         GL_textures_in_frame = 0;
1886
1887         GL_frame_count++;
1888
1889         /*
1890         int i;
1891         for( i=0; i<MAX_BITMAPS; i++ )  {
1892                 Textures[i].used_this_frame = 0;
1893
1894                 // data sections
1895                 if(Textures[i].data_sections[0][0] != NULL){
1896                         Assert(GL_texture_sections);
1897                         if(GL_texture_sections){
1898                                 for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
1899                                         for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
1900                                                 if(Textures[i].data_sections[idx][s_idx] != NULL){
1901                                                         Textures[i].data_sections[idx][s_idx]->used_this_frame = 0;
1902                                                 }
1903                                         }
1904                                 }
1905                         }
1906                 }
1907         }
1908         */
1909
1910         if ( vram_full )        {
1911                 opengl_tcache_flush();
1912                 vram_full = 0;
1913         }
1914 }
1915
1916 int opengl_free_texture ( tcache_slot_opengl *t )
1917 {
1918         int idx, s_idx;
1919         
1920
1921         // Bitmap changed!!     
1922         if ( t->bitmap_id > -1 )        {
1923                 // if I, or any of my children have been used this frame, bail  
1924                 if(t->used_this_frame == GL_frame_count){
1925                         return 0;
1926                 }
1927                 for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
1928                         for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
1929                                 if((t->data_sections[idx][s_idx] != NULL) && (t->data_sections[idx][s_idx]->used_this_frame == GL_frame_count)){
1930                                         return 0;
1931                                 }
1932                         }
1933                 }
1934
1935                 // ok, now we know its legal to free everything safely
1936                 t->texture_mode = (gr_texture_source) -1;
1937                 glDeleteTextures (1, &t->texture_handle);
1938                 t->texture_handle = 0;
1939
1940                 if ( GL_last_bitmap_id == t->bitmap_id )       {
1941                         GL_last_bitmap_id = -1;
1942                 }
1943
1944                 // if this guy has children, free them too, since the children
1945                 // actually make up his size
1946                 for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
1947                         for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
1948                                 if(t->data_sections[idx][s_idx] != NULL){
1949                                         opengl_free_texture(t->data_sections[idx][s_idx]);
1950                                 }
1951                         }
1952                 }
1953
1954                 t->bitmap_id = -1;
1955                 t->used_this_frame = 0;
1956                 GL_textures_in -= t->size;
1957         }
1958
1959         return 1;
1960 }
1961
1962 void opengl_tcache_get_adjusted_texture_size(int w_in, int h_in, int *w_out, int *h_out)
1963 {
1964         int tex_w, tex_h;
1965
1966         // bogus
1967         if((w_out == NULL) ||  (h_out == NULL)){
1968                 return;
1969         }
1970
1971         // starting size
1972         tex_w = w_in;
1973         tex_h = h_in;
1974
1975         if (1)        {
1976                 int i;
1977                 for (i=0; i<16; i++ )   {
1978                         if ( (tex_w > (1<<i)) && (tex_w <= (1<<(i+1))) )        {
1979                                 tex_w = 1 << (i+1);
1980                                 break;
1981                         }
1982                 }
1983
1984                 for (i=0; i<16; i++ )   {
1985                         if ( (tex_h > (1<<i)) && (tex_h <= (1<<(i+1))) )        {
1986                                 tex_h = 1 << (i+1);
1987                                 break;
1988                         }
1989                 }
1990         }
1991
1992         if ( tex_w < GL_min_texture_width ) {
1993                 tex_w = GL_min_texture_width;
1994         } else if ( tex_w > GL_max_texture_width )     {
1995                 tex_w = GL_max_texture_width;
1996         }
1997
1998         if ( tex_h < GL_min_texture_height ) {
1999                 tex_h = GL_min_texture_height;
2000         } else if ( tex_h > GL_max_texture_height )    {
2001                 tex_h = GL_max_texture_height;
2002         }
2003
2004         if ( GL_square_textures )      {
2005                 int new_size;
2006                 // Make the both be equal to larger of the two
2007                 new_size = max(tex_w, tex_h);
2008                 tex_w = new_size;
2009                 tex_h = new_size;
2010         }
2011
2012         // store the outgoing size
2013         *w_out = tex_w;
2014         *h_out = tex_h;
2015 }
2016
2017 // data == start of bitmap data
2018 // sx == x offset into bitmap
2019 // sy == y offset into bitmap
2020 // src_w == absolute width of section on source bitmap
2021 // src_h == absolute height of section on source bitmap
2022 // bmap_w == width of source bitmap
2023 // bmap_h == height of source bitmap
2024 // tex_w == width of final texture
2025 // tex_h == height of final texture
2026 int opengl_create_texture_sub(int bitmap_type, int texture_handle, ushort *data, int sx, int sy, int src_w, int src_h, int bmap_w, int bmap_h, int tex_w, int tex_h, tcache_slot_opengl *t, int reload, int fail_on_full)
2027 {
2028         int ret_val = 1;
2029
2030         // bogus
2031         if(t == NULL){
2032                 return 0;
2033         }
2034
2035         if ( t->used_this_frame == GL_frame_count )       {
2036                 mprintf(( "ARGHH!!! Texture already used this frame!  Cannot free it!\n" ));
2037                 return 0;
2038         }
2039         if ( !reload )  {
2040                 // gah
2041                 if(!opengl_free_texture(t)){
2042                         return 0;
2043                 }
2044         }
2045
2046         // get final texture size
2047         opengl_tcache_get_adjusted_texture_size(tex_w, tex_h, &tex_w, &tex_h);
2048
2049         if ( (tex_w < 1) || (tex_h < 1) )       {
2050                 mprintf(("Bitmap is to small at %dx%d.\n", tex_w, tex_h ));
2051                 return 0;
2052         }
2053
2054         if ( bitmap_type == TCACHE_TYPE_AABITMAP )      {
2055                 t->u_scale = (float)bmap_w / (float)tex_w;
2056                 t->v_scale = (float)bmap_h / (float)tex_h;
2057         } else if(bitmap_type == TCACHE_TYPE_BITMAP_SECTION){
2058                 t->u_scale = (float)src_w / (float)tex_w;
2059                 t->v_scale = (float)src_h / (float)tex_h;
2060         } else {
2061                 t->u_scale = 1.0f;
2062                 t->v_scale = 1.0f;
2063         }
2064
2065         if (!reload) {
2066                 glGenTextures (1, &t->texture_handle);
2067         }
2068         
2069         if (t->texture_handle == 0) {
2070                 nprintf(("Error", "!!DEBUG!! t->texture_handle == 0"));
2071                 return 0;
2072         }
2073                 
2074         GL_bound_texture = t;
2075         
2076         GL_bound_texture->texture_mode = (gr_texture_source) -1;
2077         
2078         glBindTexture (GL_TEXTURE_2D, t->texture_handle);
2079         
2080         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
2081         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
2082         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
2083
2084         /* this should be set next anyway */    
2085 //      if (GL_current_texture_source != TEXTURE_SOURCE_NONE) {
2086 //              gr_opengl_set_texture_state(GL_current_texture_source);
2087 //      }
2088         
2089         switch (bitmap_type) {
2090
2091                 case TCACHE_TYPE_AABITMAP:
2092                         {
2093                         int i,j;
2094                         ubyte *bmp_data = ((ubyte*)data);
2095                         ubyte *texmem;
2096                         ubyte *texmemp;
2097                         
2098                         ubyte xlat[256];
2099                         
2100                         for (i=0; i<16; i++) {
2101                                 xlat[i] = Gr_gamma_lookup[(i*255)/15];
2102                         }
2103                         xlat[15] = xlat[1];
2104                         for ( ; i<256; i++ )    {
2105                                 xlat[i] = xlat[0];
2106                         }
2107                         
2108                         if (GL_use_luminance_alpha) {
2109                                 texmem = (ubyte *) malloc (tex_w*tex_h*2);
2110                                 texmemp = texmem;
2111                                                         
2112                                 for (i=0;i<tex_h;i++)
2113                                 {
2114                                         for (j=0;j<tex_w;j++)
2115                                         {
2116                                                 if (i < bmap_h && j < bmap_w) {
2117                                                         *texmemp++ = 0xff;
2118                                                         *texmemp++ = xlat[bmp_data[i*bmap_w+j]];
2119                                                 } else {
2120                                                         *texmemp++ = 0;
2121                                                         *texmemp++ = 0;
2122                                                 }
2123                                         }
2124                                 }
2125
2126                                 glTexImage2D (GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, tex_w, tex_h, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, texmem);
2127
2128                                 free (texmem);
2129                         } else {
2130                                 texmem = (ubyte *) malloc (tex_w*tex_h*4);
2131                                 texmemp = texmem;
2132                                                         
2133                                 for (i=0;i<tex_h;i++)
2134                                 {
2135                                         for (j=0;j<tex_w;j++)
2136                                         {
2137                                                 if (i < bmap_h && j < bmap_w) {
2138                                                         *texmemp++ = 0xff; /* R */
2139                                                         *texmemp++ = 0xff; /* G */
2140                                                         *texmemp++ = 0xff; /* B */
2141                                                         *texmemp++ = xlat[bmp_data[i*bmap_w+j]];
2142                                                 } else {
2143                                                         *texmemp++ = 0;
2144                                                         *texmemp++ = 0;
2145                                                         *texmemp++ = 0;
2146                                                         *texmemp++ = 0;
2147                                                 }
2148                                         }
2149                                 }
2150
2151                                 glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, tex_w, tex_h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texmem);
2152
2153                                 free (texmem);
2154                         }
2155                         }
2156                         break;
2157                 case TCACHE_TYPE_BITMAP_SECTION:
2158                         {
2159                                 int i,j;
2160                                 ubyte *bmp_data = ((ubyte*)data);
2161                                 ubyte *texmem = (ubyte *) malloc (tex_w*tex_h*2);
2162                                 ubyte *texmemp = texmem;
2163                                 
2164                                 for (i=0;i<tex_h;i++)
2165                                 {
2166                                         for (j=0;j<tex_w;j++)
2167                                         {
2168                                                 if (i < src_h && j < src_w) {
2169                                                         *texmemp++ = bmp_data[((i+sy)*bmap_w+(j+sx))*2+0];
2170                                                         *texmemp++ = bmp_data[((i+sy)*bmap_w+(j+sx))*2+1];
2171                                                 } else {
2172                                                         *texmemp++ = 0;
2173                                                         *texmemp++ = 0;
2174                                                 }
2175                                         }
2176                                 }
2177                                 glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, tex_w, tex_h, 0, GL_BGRA,
2178                                         GL_UNSIGNED_SHORT_1_5_5_5_REV, texmem);
2179                                         
2180                                 free(texmem);
2181                                 break;
2182                         }
2183                 default:
2184                         {
2185                                 int i,j;
2186                                 ubyte *bmp_data = ((ubyte*)data);
2187                                 ubyte *texmem = (ubyte *) malloc (tex_w*tex_h*2);
2188                                 ubyte *texmemp = texmem;
2189                                 
2190                                 fix u, utmp, v, du, dv;
2191                                 
2192                                 u = v = 0;
2193                                 
2194                                 du = ( (bmap_w-1)*F1_0 ) / tex_w;
2195                                 dv = ( (bmap_h-1)*F1_0 ) / tex_h;
2196                                 
2197                                 for (j=0;j<tex_h;j++)
2198                                 {
2199                                         utmp = u;
2200                                         for (i=0;i<tex_w;i++)
2201                                         {
2202                                                 *texmemp++ = bmp_data[(f2i(v)*bmap_w+f2i(utmp))*2+0];
2203                                                 *texmemp++ = bmp_data[(f2i(v)*bmap_w+f2i(utmp))*2+1];
2204                                                 utmp += du;
2205                                         }
2206                                         v += dv;
2207                                 }
2208
2209                                 glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, tex_w, tex_h, 0, GL_BGRA,
2210                                         GL_UNSIGNED_SHORT_1_5_5_5_REV, texmem);
2211                                         
2212                                 free(texmem);
2213                                 break;
2214                         }
2215                         break;
2216         }
2217         
2218         t->bitmap_id = texture_handle;
2219         t->time_created = GL_frame_count;
2220         t->used_this_frame = 0;
2221         t->size = tex_w * tex_h * 2;
2222         t->w = (ushort)tex_w;
2223         t->h = (ushort)tex_h;
2224         GL_textures_in_frame += t->size;
2225         if (!reload) {
2226                 GL_textures_in += t->size;
2227         }
2228
2229         return ret_val;
2230 }
2231
2232 int opengl_create_texture (int bitmap_handle, int bitmap_type, tcache_slot_opengl *tslot, int fail_on_full)
2233 {
2234         ubyte flags;
2235         bitmap *bmp;
2236         int final_w, final_h;
2237         ubyte bpp = 16;
2238         int reload = 0;
2239
2240         // setup texture/bitmap flags
2241         flags = 0;
2242         switch(bitmap_type){
2243                 case TCACHE_TYPE_AABITMAP:
2244                         flags |= BMP_AABITMAP;
2245                         bpp = 8;
2246                         break;
2247                 case TCACHE_TYPE_NORMAL:
2248                         flags |= BMP_TEX_OTHER;
2249                 case TCACHE_TYPE_XPARENT:
2250                         flags |= BMP_TEX_XPARENT;
2251                         break;
2252                 case TCACHE_TYPE_NONDARKENING:
2253                         Int3();
2254                         flags |= BMP_TEX_NONDARK;
2255                         break;
2256         }
2257
2258         // lock the bitmap into the proper format
2259         bmp = bm_lock(bitmap_handle, bpp, flags);
2260         if ( bmp == NULL ) {
2261                 mprintf(("Couldn't lock bitmap %d.\n", bitmap_handle ));
2262                 return 0;
2263         }
2264
2265         int max_w = bmp->w;
2266         int max_h = bmp->h;
2267
2268         
2269            // DDOI - TODO
2270         if ( bitmap_type != TCACHE_TYPE_AABITMAP )      {
2271                 // max_w /= D3D_texture_divider;
2272                 // max_h /= D3D_texture_divider;
2273
2274                 // Detail.debris_culling goes from 0 to 4.
2275                 max_w /= (16 >> Detail.hardware_textures);
2276                 max_h /= (16 >> Detail.hardware_textures);
2277         }
2278         
2279
2280         // get final texture size as it will be allocated as a DD surface
2281         opengl_tcache_get_adjusted_texture_size(max_w, max_h, &final_w, &final_h); 
2282
2283         // if this tcache slot has no bitmap
2284         if ( tslot->bitmap_id < 0) {
2285                 reload = 0;
2286         }
2287         // different bitmap altogether - determine if the new one can use the old one's slot
2288         else if (tslot->bitmap_id != bitmap_handle)     {
2289                 if((final_w == tslot->w) && (final_h == tslot->h)){
2290                         reload = 1;
2291                         //ml_printf("Reloading texture %d\n", bitmap_handle);
2292                 } else {
2293                         reload = 0;
2294                 }
2295         }
2296
2297         // call the helper
2298         int ret_val = opengl_create_texture_sub(bitmap_type, bitmap_handle, (ushort*)bmp->data, 0, 0, bmp->w, bmp->h, bmp->w, bmp->h, max_w, max_h, tslot, reload, fail_on_full);
2299
2300         // unlock the bitmap
2301         bm_unlock(bitmap_handle);
2302
2303         return ret_val;
2304 }
2305
2306 int opengl_create_texture_sectioned(int bitmap_handle, int bitmap_type, tcache_slot_opengl *tslot, int sx, int sy, int fail_on_full)
2307 {
2308         ubyte flags;
2309         bitmap *bmp;
2310         int final_w, final_h;
2311         int section_x, section_y;
2312         int reload = 0;
2313
2314         // setup texture/bitmap flags
2315         Assert(bitmap_type == TCACHE_TYPE_BITMAP_SECTION);
2316         if(bitmap_type != TCACHE_TYPE_BITMAP_SECTION){
2317                 bitmap_type = TCACHE_TYPE_BITMAP_SECTION;
2318         }
2319         flags = BMP_TEX_XPARENT;
2320
2321         // lock the bitmap in the proper format
2322         bmp = bm_lock(bitmap_handle, 16, flags);
2323         if ( bmp == NULL ) {
2324                 mprintf(("Couldn't lock bitmap %d.\n", bitmap_handle ));
2325                 return 0;
2326         }
2327         // determine the width and height of this section
2328         bm_get_section_size(bitmap_handle, sx, sy, &section_x, &section_y);
2329
2330         // get final texture size as it will be allocated as an opengl texture
2331         opengl_tcache_get_adjusted_texture_size(section_x, section_y, &final_w, &final_h);
2332
2333         // if this tcache slot has no bitmap
2334         if ( tslot->bitmap_id < 0) {
2335                 reload = 0;
2336         }
2337         // different bitmap altogether - determine if the new one can use the old one's slot
2338         else if (tslot->bitmap_id != bitmap_handle)     {
2339                 if((final_w == tslot->w) && (final_h == tslot->h)){
2340                         reload = 1;
2341                 } else {
2342                         reload = 0;
2343                 }
2344         }
2345
2346         // call the helper
2347         int ret_val = opengl_create_texture_sub(bitmap_type, bitmap_handle, (ushort*)bmp->data, bmp->sections.sx[sx], bmp->sections.sy[sy], section_x, section_y, bmp->w, bmp->h, section_x, section_y, tslot, reload, fail_on_full);
2348
2349         // unlock the bitmap
2350         bm_unlock(bitmap_handle);
2351
2352         return ret_val;
2353 }
2354
2355                 
2356 extern int bm_get_cache_slot( int bitmap_id, int separate_ani_frames );
2357 int gr_opengl_tcache_set(int bitmap_id, int bitmap_type, float *u_scale, float *v_scale, int fail_on_full = 0, int sx = -1, int sy = -1, int force = 0)
2358 {
2359         bitmap *bmp = NULL;
2360
2361         int idx, s_idx;
2362         int ret_val = 1;
2363
2364         if (bitmap_id < 0)
2365         {
2366                 GL_last_bitmap_id = -1;
2367                 return 0;
2368         }
2369
2370         if ( GL_last_detail != Detail.hardware_textures )      {
2371                 GL_last_detail = Detail.hardware_textures;
2372                 opengl_tcache_flush();
2373         }
2374
2375         if (vram_full) {
2376                 return 0;
2377         }
2378
2379         int n = bm_get_cache_slot (bitmap_id, 1);
2380         tcache_slot_opengl *t = &Textures[n];
2381
2382         if ( (GL_last_bitmap_id == bitmap_id) && (GL_last_bitmap_type==bitmap_type) && (t->bitmap_id == bitmap_id) && (GL_last_section_x == sx) && (GL_last_section_y == sy))       {
2383                 t->used_this_frame = GL_frame_count;
2384
2385                 // mark all children as used
2386                 if(GL_texture_sections){
2387                         for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
2388                                 for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
2389                                         if(t->data_sections[idx][s_idx] != NULL){
2390                                                 t->data_sections[idx][s_idx]->used_this_frame = GL_frame_count;
2391                                         }
2392                                 }
2393                         }
2394                 }
2395
2396                 *u_scale = t->u_scale;
2397                 *v_scale = t->v_scale;
2398                 return 1;
2399         }
2400
2401         if (bitmap_type == TCACHE_TYPE_BITMAP_SECTION){
2402                 Assert((sx >= 0) && (sy >= 0) && (sx < MAX_BMAP_SECTIONS_X) && (sy < MAX_BMAP_SECTIONS_Y));
2403                 if(!((sx >= 0) && (sy >= 0) && (sx < MAX_BMAP_SECTIONS_X) && (sy < MAX_BMAP_SECTIONS_Y))){
2404                         return 0;
2405                 }
2406
2407                 ret_val = 1;
2408
2409                 // if the texture sections haven't been created yet
2410                 if((t->bitmap_id < 0) || (t->bitmap_id != bitmap_id)){
2411
2412                         // lock the bitmap in the proper format
2413                         bmp = bm_lock(bitmap_id, 16, BMP_TEX_XPARENT);
2414                         bm_unlock(bitmap_id);
2415
2416                         // now lets do something for each texture
2417
2418                         for(idx=0; idx<bmp->sections.num_x; idx++){
2419                                 for(s_idx=0; s_idx<bmp->sections.num_y; s_idx++){
2420                                         // hmm. i'd rather we didn't have to do it this way...
2421                                         if(!opengl_create_texture_sectioned(bitmap_id, bitmap_type, t->data_sections[idx][s_idx], idx, s_idx, fail_on_full)){
2422                                                 ret_val = 0;
2423                                         }
2424
2425                                         // not used this frame
2426                                         t->data_sections[idx][s_idx]->used_this_frame = 0;
2427                                 }
2428                         }
2429
2430                         // zero out pretty much everything in the parent struct since he's just the root
2431                         t->bitmap_id = bitmap_id;
2432                         t->texture_handle = 0;
2433                         t->time_created = t->data_sections[sx][sy]->time_created;
2434                         t->used_this_frame = 0;
2435                         /*
2436                         t->vram_texture = NULL;
2437                         t->vram_texture_surface = NULL
2438                         */
2439                 }
2440
2441                 // argh. we failed to upload. free anything we can
2442                 if(!ret_val){
2443                         opengl_free_texture(t);
2444                 }
2445                 // swap in the texture we want
2446                 else {
2447                         t = t->data_sections[sx][sy];
2448                 }
2449         }
2450         // all other "normal" textures
2451         else if((bitmap_id < 0) || (bitmap_id != t->bitmap_id)){
2452                 ret_val = opengl_create_texture( bitmap_id, bitmap_type, t, fail_on_full );
2453         }
2454
2455         // everything went ok
2456         if(ret_val && (t->texture_handle) && !vram_full){
2457                 *u_scale = t->u_scale;
2458                 *v_scale = t->v_scale;
2459
2460                 GL_bound_texture = t;
2461                 
2462                 glBindTexture (GL_TEXTURE_2D, t->texture_handle );
2463
2464                 /* this should be set next anyway */
2465 //              if (GL_current_texture_source != TEXTURE_SOURCE_NONE) {
2466 //                      gr_opengl_set_texture_state(GL_current_texture_source);
2467 //              }
2468                 
2469                 GL_last_bitmap_id = t->bitmap_id;
2470                 GL_last_bitmap_type = bitmap_type;
2471                 GL_last_section_x = sx;
2472                 GL_last_section_y = sy;
2473
2474                 t->used_this_frame = GL_frame_count;
2475         }
2476         // gah
2477         else {
2478                 GL_last_bitmap_id = -1;
2479                 GL_last_bitmap_type = -1;
2480
2481                 GL_last_section_x = -1;
2482                 GL_last_section_y = -1;
2483
2484                 GL_bound_texture = NULL;
2485                 
2486                 glBindTexture (GL_TEXTURE_2D, 0);       // test - DDOI
2487                 return 0;
2488         }
2489
2490         return 1;
2491 }
2492
2493 void gr_opengl_set_clear_color(int r, int g, int b)
2494 {
2495         gr_init_color (&gr_screen.current_clear_color, r, g, b);
2496 }
2497
2498 void gr_opengl_flash(int r, int g, int b)
2499 {
2500         CAP(r,0,255);
2501         CAP(g,0,255);
2502         CAP(b,0,255);
2503         
2504         if ( r || g || b ) {
2505                 gr_opengl_set_state( TEXTURE_SOURCE_NONE, ALPHA_BLEND_ALPHA_ADDITIVE, ZBUFFER_TYPE_NONE );
2506                 
2507                 float x1, x2, y1, y2;
2508                 x1 = i2fl(gr_screen.clip_left+gr_screen.offset_x);
2509                 y1 = i2fl(gr_screen.clip_top+gr_screen.offset_y);
2510                 x2 = i2fl(gr_screen.clip_right+gr_screen.offset_x);
2511                 y2 = i2fl(gr_screen.clip_bottom+gr_screen.offset_y);
2512                 
2513                 glColor4ub(r, g, b, 255);
2514                 glBegin (GL_QUADS);
2515                   glVertex3f (x1, y2, -0.99);
2516
2517                   glVertex3f (x2, y2, -0.99);
2518
2519                   glVertex3f (x2, y1, -0.99);
2520
2521                   glVertex3f (x1, y1, -0.99);
2522                 glEnd ();         
2523         }
2524 }
2525
2526 int gr_opengl_zbuffer_get()
2527 {
2528         if ( !gr_global_zbuffering )    {
2529                 return GR_ZBUFF_NONE;
2530         }
2531         return gr_zbuffering_mode;
2532 }
2533
2534 int gr_opengl_zbuffer_set(int mode)
2535 {
2536         int tmp = gr_zbuffering_mode;
2537
2538         gr_zbuffering_mode = mode;
2539
2540         if (gr_zbuffering_mode == GR_ZBUFF_NONE )      {
2541                 gr_zbuffering = 0;
2542         } else {
2543                 gr_zbuffering = 1;
2544         }
2545         return tmp;
2546 }
2547
2548 void gr_opengl_zbuffer_clear(int mode)
2549 {
2550         if (mode) {
2551                 gr_zbuffering = 1;
2552                 gr_zbuffering_mode = GR_ZBUFF_FULL;
2553                 gr_global_zbuffering = 1;
2554                 
2555                 gr_opengl_set_state( TEXTURE_SOURCE_NONE, ALPHA_BLEND_NONE, ZBUFFER_TYPE_FULL );
2556                 glClear ( GL_DEPTH_BUFFER_BIT );
2557         } else {
2558                 gr_zbuffering = 0;
2559                 gr_zbuffering_mode = GR_ZBUFF_NONE;
2560                 gr_global_zbuffering = 0;
2561         }
2562 }
2563
2564 void gr_opengl_set_gamma(float gamma)
2565 {
2566         Gr_gamma = gamma;
2567         Gr_gamma_int = int (Gr_gamma*10);
2568
2569         // Create the Gamma lookup table
2570         int i;
2571         for (i=0;i<256; i++) {
2572                 int v = fl2i(pow(i2fl(i)/255.0f, 1.0f/Gr_gamma)*255.0f);
2573                 if ( v > 255 ) {
2574                         v = 255;
2575                 } else if ( v < 0 )     {
2576                         v = 0;
2577                 }
2578                 Gr_gamma_lookup[i] = v;
2579         }
2580
2581         // Flush any existing textures
2582         opengl_tcache_flush();
2583 }
2584
2585 void gr_opengl_fade_in(int instantaneous)
2586 {
2587         // Empty - DDOI
2588 }
2589
2590 void gr_opengl_fade_out(int instantaneous)
2591 {
2592         // Empty - DDOI
2593 }
2594
2595 void gr_opengl_get_region(int front, int w, int h, ubyte *data)
2596 {
2597         if (front) {
2598                 glReadBuffer(GL_FRONT);
2599         } else {
2600                 glReadBuffer(GL_BACK);
2601         }
2602         
2603         gr_opengl_set_state(TEXTURE_SOURCE_NO_FILTERING, ALPHA_BLEND_NONE, ZBUFFER_TYPE_NONE);
2604         
2605         glPixelStorei(GL_UNPACK_ROW_LENGTH, gr_screen.max_w);
2606         
2607         if (gr_screen.bits_per_pixel == 15) {
2608                 glReadPixels(0, gr_screen.max_h-h-1, w, h, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, data);
2609         } else if (gr_screen.bits_per_pixel == 32) {
2610                 glReadPixels(0, gr_screen.max_h-h-1, w, h, GL_RGBA, GL_UNSIGNED_BYTE, data);
2611         }
2612         
2613         glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
2614 }
2615
2616 static int Gr_opengl_mouse_saved = 0;
2617 static int Gr_opengl_mouse_saved_x1 = 0;
2618 static int Gr_opengl_mouse_saved_y1 = 0;
2619 static int Gr_opengl_mouse_saved_x2 = 0;
2620 static int Gr_opengl_mouse_saved_y2 = 0;
2621 static int Gr_opengl_mouse_saved_w = 0;
2622 static int Gr_opengl_mouse_saved_h = 0;
2623 #define MAX_SAVE_SIZE (32*32)
2624 static ubyte Gr_opengl_mouse_saved_data[MAX_SAVE_SIZE*2];
2625
2626 #define CLAMP(x,r1,r2) do { if ( (x) < (r1) ) (x) = (r1); else if ((x) > (r2)) (x) = (r2); } while(0)
2627
2628 void gr_opengl_save_mouse_area(int x, int y, int w, int h)
2629 {
2630         Gr_opengl_mouse_saved_x1 = x;
2631         Gr_opengl_mouse_saved_y1 = y;
2632         Gr_opengl_mouse_saved_x2 = x+w-1;
2633         Gr_opengl_mouse_saved_y2 = y+h-1;
2634         
2635         CLAMP(Gr_opengl_mouse_saved_x1, gr_screen.clip_left, gr_screen.clip_right );
2636         CLAMP(Gr_opengl_mouse_saved_x2, gr_screen.clip_left, gr_screen.clip_right );
2637         CLAMP(Gr_opengl_mouse_saved_y1, gr_screen.clip_top, gr_screen.clip_bottom );
2638         CLAMP(Gr_opengl_mouse_saved_y2, gr_screen.clip_top, gr_screen.clip_bottom );
2639         
2640         Gr_opengl_mouse_saved_w = Gr_opengl_mouse_saved_x2 - Gr_opengl_mouse_saved_x1 + 1;
2641         Gr_opengl_mouse_saved_h = Gr_opengl_mouse_saved_y2 - Gr_opengl_mouse_saved_y1 + 1;
2642
2643         if ( Gr_opengl_mouse_saved_w < 1 ) return;
2644         if ( Gr_opengl_mouse_saved_h < 1 ) return;
2645         
2646         Assert( (Gr_opengl_mouse_saved_w*Gr_opengl_mouse_saved_h) <= MAX_SAVE_SIZE );
2647
2648         gr_opengl_set_state(TEXTURE_SOURCE_NO_FILTERING, ALPHA_BLEND_NONE, ZBUFFER_TYPE_NONE);
2649         
2650         glReadBuffer(GL_BACK);
2651         glReadPixels(x, gr_screen.max_h-y-1-h, w, h, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, Gr_opengl_mouse_saved_data);
2652         
2653         Gr_opengl_mouse_saved = 1;
2654 }
2655
2656 int gr_opengl_save_screen()
2657 {
2658         gr_reset_clip();
2659
2660         if ( Gr_saved_screen )  {
2661                 mprintf(( "Screen alread saved!\n" ));
2662                 return -1;
2663         }
2664
2665         Gr_saved_screen = (char*)malloc( gr_screen.max_w * gr_screen.max_h * gr_screen.bytes_per_pixel );
2666         if (!Gr_saved_screen) {
2667                 mprintf(( "Couldn't get memory for saved screen!\n" ));
2668                 return -1;
2669         }
2670
2671         char *Gr_saved_screen_tmp = (char*)malloc( gr_screen.max_w * gr_screen.max_h * gr_screen.bytes_per_pixel );
2672         if (!Gr_saved_screen_tmp) {
2673                 mprintf(( "Couldn't get memory for temporary saved screen!\n" ));
2674                 return -1;
2675         }
2676         
2677         gr_opengl_set_state(TEXTURE_SOURCE_NO_FILTERING, ALPHA_BLEND_NONE, ZBUFFER_TYPE_NONE);
2678         
2679         glReadBuffer(GL_FRONT);
2680         glReadPixels(0, 0, gr_screen.max_w, gr_screen.max_h, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, Gr_saved_screen_tmp);
2681         
2682         ubyte *sptr, *dptr;
2683         
2684         sptr = (ubyte *)&Gr_saved_screen_tmp[gr_screen.max_w*gr_screen.max_h*2];
2685         dptr = (ubyte *)Gr_saved_screen;
2686         for (int j = 0; j < gr_screen.max_h; j++) {
2687                 sptr -= gr_screen.max_w*2;
2688                 memcpy(dptr, sptr, gr_screen.max_w*2);
2689                 dptr += gr_screen.max_w*2;
2690         }
2691         
2692         free(Gr_saved_screen_tmp);
2693         
2694         if (Gr_opengl_mouse_saved) {
2695                 sptr = (ubyte *)Gr_opengl_mouse_saved_data;
2696                 dptr = (ubyte *)&Gr_saved_screen[2*(Gr_opengl_mouse_saved_x1+(Gr_opengl_mouse_saved_y2)*gr_screen.max_w)];
2697                 for (int i = 0; i < Gr_opengl_mouse_saved_h; i++) {
2698                         memcpy(dptr, sptr, Gr_opengl_mouse_saved_w*2);
2699                 
2700                         sptr += 32*2;
2701                         dptr -= gr_screen.max_w*2;
2702                 }
2703         }
2704
2705         // this leaks texture handles, and the opengl doesn't currently 
2706         // perform some sort of garbage collection, so a hack was added
2707         // to bmpman to make it free textures when released
2708         Gr_saved_screen_bitmap = bm_create(16, gr_screen.max_w, gr_screen.max_h, Gr_saved_screen, 0);
2709         
2710         return Gr_saved_screen_bitmap;
2711 }
2712
2713 void gr_opengl_restore_screen(int id)
2714 {
2715         gr_reset_clip();
2716         
2717         if ( !Gr_saved_screen ) {
2718                 gr_clear();
2719                 return;
2720         }
2721
2722         gr_opengl_set_state(TEXTURE_SOURCE_NO_FILTERING, ALPHA_BLEND_NONE, ZBUFFER_TYPE_NONE);
2723         
2724         gr_set_bitmap(Gr_saved_screen_bitmap);
2725         gr_bitmap(0, 0);                
2726 }
2727
2728 void gr_opengl_free_screen(int id)
2729 {
2730         bm_release(Gr_saved_screen_bitmap);
2731         
2732         if ( Gr_saved_screen )  {
2733                 free( Gr_saved_screen );
2734                 Gr_saved_screen = NULL;
2735         }
2736 }
2737
2738 void gr_opengl_dump_frame_start(int first_frame, int frames_between_dumps)
2739 {
2740         STUB_FUNCTION;
2741 }
2742
2743 void gr_opengl_dump_frame_stop()
2744 {
2745         STUB_FUNCTION;
2746 }
2747
2748 void gr_opengl_dump_frame()
2749 {
2750         STUB_FUNCTION;
2751 }
2752
2753 uint gr_opengl_lock()
2754 {
2755         STUB_FUNCTION;
2756         
2757         return 1;
2758 }
2759         
2760 void gr_opengl_unlock()
2761 {
2762 }
2763
2764 void opengl_zbias(int bias)
2765 {
2766         if (bias) {
2767                 glEnable(GL_POLYGON_OFFSET_FILL);
2768                 glPolygonOffset(0.0, -bias);
2769         } else {
2770                 glDisable(GL_POLYGON_OFFSET_FILL);
2771         }
2772 }
2773                 
2774 extern char *Osreg_title;
2775 void gr_opengl_init()
2776 {
2777         if ( Inited )   {
2778                 gr_opengl_cleanup();
2779                 Inited = 0;
2780         }
2781
2782         mprintf(( "Initializing opengl graphics device...\n" ));
2783         Inited = 1;
2784
2785 #ifdef PLAT_UNIX        
2786         if (SDL_InitSubSystem (SDL_INIT_VIDEO) < 0)
2787         {
2788                 fprintf (stderr, "Couldn't init SDL: %s", SDL_GetError());
2789                 exit (1);
2790         }
2791
2792         atexit (SDL_Quit);
2793
2794         SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
2795         SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
2796         SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
2797         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
2798         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
2799         
2800         int flags = SDL_OPENGL;
2801         
2802         if (os_config_read_uint( NULL, "Fullscreen", 0 ) == 1)
2803                 flags |= SDL_FULLSCREEN;
2804
2805         if (SDL_SetVideoMode (gr_screen.max_w, gr_screen.max_h,0,flags) == NULL)
2806         {
2807                 fprintf (stderr, "Couldn't set video mode: %s", SDL_GetError ());
2808                 exit (1);
2809         }               
2810
2811         SDL_ShowCursor(0);
2812         SDL_WM_SetCaption (Osreg_title, "FS2");
2813         
2814         /* might as well put this here */
2815         SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
2816 #endif
2817         GL_use_luminance_alpha = os_config_read_uint(NOX("OpenGL"), NOX("UseLuminanceAlpha"), 0);
2818
2819         glViewport(0, 0, gr_screen.max_w, gr_screen.max_h);
2820
2821         glMatrixMode(GL_PROJECTION);
2822         glLoadIdentity();
2823         glOrtho(0, gr_screen.max_w, gr_screen.max_h, 0, 0.0, 1.0);
2824         glMatrixMode(GL_MODELVIEW);
2825         glLoadIdentity();
2826         
2827         glShadeModel(GL_SMOOTH);
2828         glEnable(GL_DITHER);
2829         glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
2830         glHint(GL_FOG_HINT, GL_NICEST);
2831                 
2832         glEnable(GL_DEPTH_TEST);
2833         glEnable(GL_BLEND);
2834         
2835         glEnable(GL_TEXTURE_2D);
2836         
2837         glDepthRange(0.0, 1.0);
2838         
2839         glPixelStorei(GL_PACK_ALIGNMENT, 1);
2840         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
2841         
2842         D3D_32bit = 1;              // grd3d.cpp
2843         extern int D3D_enabled;
2844         D3D_enabled = 1;
2845         /* 
2846           TODO: set fog_mode to 1 if EXT_secondary_color found and wanted 
2847           1 = use secondary color ext
2848           2 = use opengl linear fog
2849          */
2850         D3D_fog_mode = 2;          // grd3d.cpp
2851
2852         glFlush();
2853         
2854         Bm_pixel_format = BM_PIXEL_FORMAT_ARGB;
2855         Gr_bitmap_poly = 1;
2856         
2857         int bpp = 15;
2858         
2859         switch( bpp )   {
2860         case 15:
2861                 gr_screen.bits_per_pixel = 15;
2862                 gr_screen.bytes_per_pixel = 2;
2863                 
2864                 Gr_red.bits = 5;
2865                 Gr_red.shift = 10;
2866                 Gr_red.scale = 8;
2867                 Gr_red.mask = 0x7C00;
2868
2869                 Gr_green.bits = 5;
2870                 Gr_green.shift = 5;
2871                 Gr_green.scale = 8;
2872                 Gr_green.mask = 0x3E0;
2873
2874                 Gr_blue.bits = 5;
2875                 Gr_blue.shift = 0;
2876                 Gr_blue.scale = 8;
2877                 Gr_blue.mask = 0x1F;
2878
2879                 break;
2880
2881         case 16:
2882                 gr_screen.bits_per_pixel = 16;
2883                 gr_screen.bytes_per_pixel = 2;
2884                 
2885                 Gr_red.bits = 5;
2886                 Gr_red.shift = 11;
2887                 Gr_red.scale = 8;
2888                 Gr_red.mask = 0xF800;
2889
2890                 Gr_green.bits = 6;
2891                 Gr_green.shift = 5;
2892                 Gr_green.scale = 4;
2893                 Gr_green.mask = 0x7E0;
2894
2895                 Gr_blue.bits = 5;
2896                 Gr_blue.shift = 0;
2897                 Gr_blue.scale = 8;
2898                 Gr_blue.mask = 0x1F;
2899
2900                 break;
2901
2902         case 32:
2903                 gr_screen.bits_per_pixel = 32;
2904                 gr_screen.bytes_per_pixel = 4;
2905                 
2906                 Gr_red.bits = 8;
2907                 Gr_red.shift = 16;
2908                 Gr_red.scale = 1;
2909                 Gr_red.mask = 0xff0000;
2910
2911                 Gr_green.bits = 8;
2912                 Gr_green.shift = 8;
2913                 Gr_green.scale = 1;
2914                 Gr_green.mask = 0xff00;
2915
2916                 Gr_blue.bits = 8;
2917                 Gr_blue.shift = 0;
2918                 Gr_blue.scale = 1;
2919                 Gr_blue.mask = 0xff;
2920
2921                 break;
2922
2923         default:
2924                 Int3(); // Illegal bpp
2925         }
2926
2927         // DDOI - set these so no one else does!
2928         Gr_ta_red.mask = 0x0f00;
2929         Gr_ta_red.shift = 8;
2930         Gr_ta_red.scale = 16;
2931
2932         Gr_ta_green.mask = 0x00f0;
2933         Gr_ta_green.shift = 4;
2934         Gr_ta_green.scale = 16;
2935         
2936         Gr_ta_blue.mask = 0x000f;
2937         Gr_ta_blue.shift = 0;
2938         Gr_ta_blue.scale = 16;
2939
2940         Gr_ta_alpha.mask = 0xf000;
2941         Gr_ta_alpha.shift = 12;
2942         Gr_ta_alpha.scale = 16;
2943
2944
2945         opengl_tcache_init (1);
2946         gr_opengl_clear();
2947
2948         Gr_current_red = &Gr_red;
2949         Gr_current_blue = &Gr_blue;
2950         Gr_current_green = &Gr_green;
2951         Gr_current_alpha = &Gr_alpha;
2952                                 
2953         gr_screen.gf_flip = gr_opengl_flip;
2954         gr_screen.gf_flip_window = gr_opengl_flip_window;
2955         gr_screen.gf_set_clip = gr_opengl_set_clip;
2956         gr_screen.gf_reset_clip = gr_opengl_reset_clip;
2957         gr_screen.gf_set_font = grx_set_font;
2958         
2959         gr_screen.gf_set_color = gr_opengl_set_color;
2960         gr_screen.gf_set_bitmap = gr_opengl_set_bitmap;
2961         gr_screen.gf_create_shader = gr_opengl_create_shader;
2962         gr_screen.gf_set_shader = gr_opengl_set_shader;
2963         gr_screen.gf_clear = gr_opengl_clear;
2964         // gr_screen.gf_bitmap = gr_opengl_bitmap;
2965         // gr_screen.gf_bitmap_ex = gr_opengl_bitmap_ex;
2966         gr_screen.gf_aabitmap = gr_opengl_aabitmap;
2967         gr_screen.gf_aabitmap_ex = gr_opengl_aabitmap_ex;
2968         
2969         gr_screen.gf_rect = gr_opengl_rect;
2970         gr_screen.gf_shade = gr_opengl_shade;
2971         gr_screen.gf_string = gr_opengl_string;
2972         gr_screen.gf_circle = gr_opengl_circle;
2973
2974         gr_screen.gf_line = gr_opengl_line;
2975         gr_screen.gf_aaline = gr_opengl_aaline;
2976         gr_screen.gf_pixel = gr_opengl_pixel;
2977         gr_screen.gf_scaler = gr_opengl_scaler;
2978         gr_screen.gf_tmapper = gr_opengl_tmapper;
2979
2980         gr_screen.gf_gradient = gr_opengl_gradient;
2981
2982         gr_screen.gf_set_palette = gr_opengl_set_palette;
2983         gr_screen.gf_get_color = gr_opengl_get_color;
2984         gr_screen.gf_init_color = gr_opengl_init_color;
2985         gr_screen.gf_init_alphacolor = gr_opengl_init_alphacolor;
2986         gr_screen.gf_set_color_fast = gr_opengl_set_color_fast;
2987         gr_screen.gf_print_screen = gr_opengl_print_screen;
2988
2989         gr_screen.gf_fade_in = gr_opengl_fade_in;
2990         gr_screen.gf_fade_out = gr_opengl_fade_out;
2991         gr_screen.gf_flash = gr_opengl_flash;
2992         
2993         gr_screen.gf_zbuffer_get = gr_opengl_zbuffer_get;
2994         gr_screen.gf_zbuffer_set = gr_opengl_zbuffer_set;
2995         gr_screen.gf_zbuffer_clear = gr_opengl_zbuffer_clear;
2996         
2997         gr_screen.gf_save_screen = gr_opengl_save_screen;
2998         gr_screen.gf_restore_screen = gr_opengl_restore_screen;
2999         gr_screen.gf_free_screen = gr_opengl_free_screen;
3000         
3001         gr_screen.gf_dump_frame_start = gr_opengl_dump_frame_start;
3002         gr_screen.gf_dump_frame_stop = gr_opengl_dump_frame_stop;
3003         gr_screen.gf_dump_frame = gr_opengl_dump_frame;
3004         
3005         gr_screen.gf_set_gamma = gr_opengl_set_gamma;
3006         
3007         gr_screen.gf_lock = gr_opengl_lock;
3008         gr_screen.gf_unlock = gr_opengl_unlock;
3009         
3010         gr_screen.gf_fog_set = gr_opengl_fog_set;       
3011
3012         gr_screen.gf_get_region = gr_opengl_get_region;
3013
3014         gr_screen.gf_get_pixel = gr_opengl_get_pixel;
3015
3016         gr_screen.gf_set_cull = gr_opengl_set_cull;
3017
3018         gr_screen.gf_cross_fade = gr_opengl_cross_fade;
3019
3020         gr_screen.gf_filter_set = gr_opengl_filter_set;
3021
3022         gr_screen.gf_tcache_set = gr_opengl_tcache_set;
3023
3024         gr_screen.gf_set_clear_color = gr_opengl_set_clear_color;
3025         
3026         Mouse_hidden++;
3027         gr_reset_clip();
3028         gr_clear();
3029         gr_flip();
3030         Mouse_hidden--;
3031 }