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