]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
fabb712dc5b787bbe613e2b89338daadd33998bc
[lugaru.git] / Source / OpenGL_Windows.cpp
1 /*
2 Copyright (C) 2003, 2010 - Wolfire Games
3
4 This file is part of Lugaru.
5
6 Lugaru is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 */
21
22 /* No need for Visual Leak Detector
23 #ifdef WIN32
24 #include <vld.h>
25 #endif
26 */
27
28 #define USE_DEVIL 0
29
30 #ifndef USE_DEVIL
31 #  ifdef WIN32
32 #    define USE_DEVIL
33 #  endif
34 #endif
35
36 #if USE_DEVIL
37     #include "IL/il.h"
38     #include "IL/ilu.h"
39     #include "IL/ilut.h"
40         #include "Game.h"
41 #else
42
43         #include <zlib.h>
44         #include <png.h>
45         #include <jpeglib.h>
46         #include "Game.h"
47     static bool load_image(const char * fname, TGAImageRec & tex);
48     static bool load_png(const char * fname, TGAImageRec & tex);
49     static bool load_jpg(const char * fname, TGAImageRec & tex);
50     static bool save_image(const char * fname);
51     static bool save_png(const char * fname);
52 #endif
53
54 // ADDED GWC
55 #ifdef _MSC_VER
56 #pragma comment(lib, "opengl32.lib")
57 #pragma comment(lib, "glu32.lib")
58 #pragma comment(lib, "glaux.lib")
59 #endif
60
61 extern bool buttons[3];
62 extern float multiplier;
63 extern float screenwidth,screenheight;
64 extern float sps;
65 extern float realmultiplier;
66 extern int slomo;
67 extern bool ismotionblur;
68 extern float usermousesensitivity;
69 extern int detail;
70 extern bool floatjump;
71 extern bool cellophane;
72 // MODIFIED GWC
73 //extern int terraindetail;
74 //extern int texdetail;
75 extern float terraindetail;
76 extern float texdetail;
77 extern int bloodtoggle;
78 extern bool osx;
79 extern bool autoslomo;
80 extern bool foliage;
81 extern bool musictoggle;
82 extern bool trilinear;
83 extern float gamespeed;
84 extern int difficulty;
85 extern bool damageeffects;
86 extern int numplayers;
87 extern bool decals;
88 extern bool invertmouse;
89 extern bool texttoggle;
90 extern bool ambientsound;
91 extern bool mousejump;
92 extern bool freeze;
93 extern Person player[maxplayers];
94 extern bool vblsync;
95 extern bool stillloading;
96 extern bool showpoints;
97 extern bool alwaysblur;
98 extern bool immediate;
99 extern bool velocityblur;
100 extern bool debugmode;
101 extern int mainmenu;
102 /*extern*/ bool gameFocused;
103 extern int kBitsPerPixel;
104 extern float slomospeed;
105 extern float slomofreq;
106 extern float oldgamespeed;
107 extern float volume;
108
109 #include <math.h>
110 #include <stdio.h>
111 #include <string.h>
112 #include <fstream>
113 #include <iostream>
114 #include "gamegl.h"
115 #include "MacCompatibility.h"
116
117 #ifdef WIN32
118 #include <shellapi.h>
119 #endif
120
121 #include "fmod.h"
122
123 #include "res/resource.h"
124
125 using namespace std;
126
127
128 #if USE_SDL
129 SDL_Rect **resolutions = NULL;
130 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
131 static SDL_Rect rect_800_600  = { 0, 0, 800,  600 };
132 static SDL_Rect rect_640_480  = { 0, 0, 640,  480 };
133 static SDL_Rect *hardcoded_resolutions[] = {
134     &rect_1024_768,
135     &rect_800_600,
136     &rect_640_480,
137     NULL
138 };
139 #endif
140
141
142 unsigned int resolutionDepths[8][2] = {0};
143
144 bool selectDetail(int & width, int & height, int & bpp, int & detail);
145 int closestResolution(int width, int height);
146 int resolutionID(int width, int height);
147
148 void ReportError (char * strError);
149
150 void SetupDSpFullScreen();
151 void ShutdownDSp();
152
153 void DrawGL(Game & game);
154
155 void CreateGLWindow (void);
156 Boolean SetUp (Game & game);
157 void DoKey (SInt8 theKey, SInt8 theCode);
158 void DoUpdate (Game & game);
159
160 void DoEvent (void);
161 void CleanUp (void);
162
163
164 // statics/globals (internal only) ------------------------------------------
165 #ifndef WIN32
166 typedef struct tagPOINT { 
167   int x;
168   int y;
169 } POINT, *PPOINT; 
170 #endif
171
172 #if USE_SDL
173 #define GL_FUNC(ret,fn,params,call,rt) \
174     extern "C" { \
175         static ret GLAPIENTRY (*p##fn) params = NULL; \
176         ret GLAPIENTRY fn params { rt p##fn call; } \
177     }
178 #include "glstubs.h"
179 #undef GL_FUNC
180
181 static bool lookup_glsym(const char *funcname, void **func)
182 {
183     *func = SDL_GL_GetProcAddress(funcname);
184     if (*func == NULL)
185     {
186         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
187         return false;
188     }
189     return true;
190 }
191
192 static bool lookup_all_glsyms(void)
193 {
194     bool retval = true;
195     #define GL_FUNC(ret,fn,params,call,rt) \
196         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
197     #include "glstubs.h"
198     #undef GL_FUNC
199     return retval;
200 }
201
202 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
203 {
204     // no-op.
205 }
206
207
208
209 void sdlGetCursorPos(POINT *pt)
210 {
211     int x, y;
212     SDL_GetMouseState(&x, &y);
213     pt->x = x;
214     pt->y = y;
215 }
216 #define GetCursorPos(x) sdlGetCursorPos(x)
217 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
218 #define ScreenToClient(x, pt)
219 #define ClientToScreen(x, pt)
220 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
221 #endif
222
223 Point delta;
224
225 #ifdef WIN32
226 static const char g_wndClassName[]={ "LUGARUWINDOWCLASS" };
227 static HINSTANCE g_appInstance;
228 static HWND g_windowHandle;
229 static HGLRC hRC;
230 #endif
231
232 static bool g_button, fullscreen = true;
233
234
235 // Menu defs
236 enum 
237 {
238         kFileQuit = 1
239 };
240
241 enum 
242 {
243         kForegroundSleep = 10,
244         kBackgroundSleep = 10000
245 };
246
247
248 int kContextWidth;
249 int kContextHeight;
250
251 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
252
253 GLuint gFontList;
254 char gcstrMode [256] = "";
255
256 UInt32 gSleepTime = kForegroundSleep;
257 Boolean gDone = false, gfFrontProcess = true;
258
259 Game * pgame = 0;
260
261
262 static int _argc = 0;
263 static char **_argv = NULL;
264
265 bool cmdline(const char *cmd)
266 {
267     for (int i = 1; i < _argc; i++)
268     {
269         char *arg = _argv[i];
270         while (*arg == '-')
271             arg++;
272         if (strcasecmp(arg, cmd) == 0)
273             return true;
274     }
275
276     return false;
277 }
278
279
280 // --------------------------------------------------------------------------
281
282 void ReportError (char * strError)
283 {
284 #ifdef WIN32  // !!! FIXME.  --ryan.
285         throw std::exception( strError);
286 #endif
287
288         /*      char errMsgCStr [256];
289         Str255 strErr;
290
291         sprintf (errMsgCStr, "%s", strError); 
292
293         // out as debug string
294         CToPStr (strErr, errMsgCStr);
295         DebugStr (strErr);
296         */
297 }
298
299 void SetupDSpFullScreen ()
300 {
301 #ifdef WIN32
302         LOGFUNC;
303
304         if (fullscreen)
305         {
306                 DEVMODE dmScreenSettings;
307                 memset( &dmScreenSettings, 0, sizeof( dmScreenSettings));
308                 dmScreenSettings.dmSize = sizeof( dmScreenSettings);
309                 dmScreenSettings.dmPelsWidth    = kContextWidth;
310                 dmScreenSettings.dmPelsHeight   = kContextHeight;
311                 dmScreenSettings.dmBitsPerPel   = kBitsPerPixel;
312                 dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
313
314                 // set video mode
315                 if (ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
316                 {
317                         ReportError( "Could not set display mode");
318                         return;
319                 }
320         }
321
322         ShowCursor(FALSE);
323 #endif
324 }
325
326
327 void ShutdownDSp ()
328 {
329 #ifdef WIN32
330         LOGFUNC;
331
332         if (fullscreen)
333         {
334                 ChangeDisplaySettings( NULL, 0);
335         }
336
337         ShowCursor(TRUE);
338 #endif
339 }
340
341
342 //-----------------------------------------------------------------------------------------------------------------------
343
344 // OpenGL Drawing
345
346 void DrawGL (Game & game)
347 {
348 #ifdef WIN32
349         if (hDC == 0)
350                 return;
351 #endif
352
353         game.DrawGLScene();
354 }
355
356
357 static KeyMap g_theKeys;
358
359 void SetKey( int key)
360 {
361     g_theKeys[ key >> 3] |= (1 << (key & 7));
362 }
363
364 void ClearKey( int key)
365 {
366     g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
367 }
368
369 void GetKeys(  unsigned char theKeys[16])
370 {
371     memcpy( theKeys, &g_theKeys, 16);
372 }
373
374 Boolean Button()
375 {
376     return g_button;
377 }
378
379 #if !USE_SDL
380 static void initSDLKeyTable(void) {}
381 #else
382 #define MAX_SDLKEYS SDLK_LAST
383 static unsigned short KeyTable[MAX_SDLKEYS];
384
385 static void initSDLKeyTable(void)
386 {
387     memset(KeyTable, 0xFF, sizeof (KeyTable));
388     KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
389     KeyTable[SDLK_TAB] = MAC_TAB_KEY;
390     KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
391     KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
392     KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
393     KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
394     KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
395     KeyTable[SDLK_END] = MAC_END_KEY;
396     KeyTable[SDLK_HOME] = MAC_HOME_KEY;
397     KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
398     KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
399     KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
400     KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
401     KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
402     KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
403     KeyTable[SDLK_0] = MAC_0_KEY;
404     KeyTable[SDLK_1] = MAC_1_KEY;
405     KeyTable[SDLK_2] = MAC_2_KEY;
406     KeyTable[SDLK_3] = MAC_3_KEY;
407     KeyTable[SDLK_4] = MAC_4_KEY;
408     KeyTable[SDLK_5] = MAC_5_KEY;
409     KeyTable[SDLK_6] = MAC_6_KEY;
410     KeyTable[SDLK_7] = MAC_7_KEY;
411     KeyTable[SDLK_8] = MAC_8_KEY;
412     KeyTable[SDLK_9] = MAC_9_KEY;
413     KeyTable[SDLK_a] = MAC_A_KEY;
414     KeyTable[SDLK_b] = MAC_B_KEY;
415     KeyTable[SDLK_c] = MAC_C_KEY;
416     KeyTable[SDLK_d] = MAC_D_KEY;
417     KeyTable[SDLK_e] = MAC_E_KEY;
418     KeyTable[SDLK_f] = MAC_F_KEY;
419     KeyTable[SDLK_g] = MAC_G_KEY;
420     KeyTable[SDLK_h] = MAC_H_KEY;
421     KeyTable[SDLK_i] = MAC_I_KEY;
422     KeyTable[SDLK_j] = MAC_J_KEY;
423     KeyTable[SDLK_k] = MAC_K_KEY;
424     KeyTable[SDLK_l] = MAC_L_KEY;
425     KeyTable[SDLK_m] = MAC_M_KEY;
426     KeyTable[SDLK_n] = MAC_N_KEY;
427     KeyTable[SDLK_o] = MAC_O_KEY;
428     KeyTable[SDLK_p] = MAC_P_KEY;
429     KeyTable[SDLK_q] = MAC_Q_KEY;
430     KeyTable[SDLK_r] = MAC_R_KEY;
431     KeyTable[SDLK_s] = MAC_S_KEY;
432     KeyTable[SDLK_t] = MAC_T_KEY;
433     KeyTable[SDLK_u] = MAC_U_KEY;
434     KeyTable[SDLK_v] = MAC_V_KEY;
435     KeyTable[SDLK_w] = MAC_W_KEY;
436     KeyTable[SDLK_x] = MAC_X_KEY;
437     KeyTable[SDLK_y] = MAC_Y_KEY;
438     KeyTable[SDLK_z] = MAC_Z_KEY;
439     KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
440     KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
441     KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
442     KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
443     KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
444     KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
445     KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
446     KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
447     KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
448     KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
449     KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
450     KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
451     KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
452     KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
453     KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
454     KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
455     KeyTable[SDLK_F1] = MAC_F1_KEY;
456     KeyTable[SDLK_F2] = MAC_F2_KEY;
457     KeyTable[SDLK_F3] = MAC_F3_KEY;
458     KeyTable[SDLK_F4] = MAC_F4_KEY;
459     KeyTable[SDLK_F5] = MAC_F5_KEY;
460     KeyTable[SDLK_F6] = MAC_F6_KEY;
461     KeyTable[SDLK_F7] = MAC_F7_KEY;
462     KeyTable[SDLK_F8] = MAC_F8_KEY;
463     KeyTable[SDLK_F9] = MAC_F9_KEY;
464     KeyTable[SDLK_F10] = MAC_F10_KEY;
465     KeyTable[SDLK_F11] = MAC_F11_KEY;
466     KeyTable[SDLK_F12] = MAC_F12_KEY;
467     KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
468     KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
469     KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
470     KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
471     KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
472     KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
473     KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
474     KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
475     KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
476     KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
477     KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
478 }
479
480 static inline int clamp_sdl_mouse_button(Uint8 button)
481 {
482     if (button == 2)   // right mouse button is button 3 in SDL.
483         button = 3;
484     else if (button == 3)
485         button = 2;
486
487     if ((button >= 1) && (button <= 3))
488         return button - 1;
489     return -1;
490 }
491
492 static void sdlEventProc(const SDL_Event &e, Game &game)
493 {
494     int val;
495     bool skipkey = false;
496     SDLMod mod;
497
498     switch(e.type)
499         {
500         case SDL_MOUSEMOTION:
501             game.deltah += e.motion.xrel;
502             game.deltav += e.motion.yrel;
503             return;
504
505                 case SDL_MOUSEBUTTONDOWN:
506                         {
507                 val = clamp_sdl_mouse_button(e.button.button);
508                 if ((val >= 0) && (val <= 2))
509                 {
510                     if (val == 0)
511                                     g_button = true;
512                                 buttons[val] = true;
513                 }
514                         }
515                         return;
516
517                 case SDL_MOUSEBUTTONUP:
518                         {
519                 val = clamp_sdl_mouse_button(e.button.button);
520                 if ((val >= 0) && (val <= 2))
521                 {
522                     if (val == 0)
523                                     g_button = false;
524                                 buttons[val] = false;
525                 }
526                         }
527             return;
528
529         case SDL_KEYDOWN:
530             if (e.key.keysym.sym == SDLK_g)
531             {
532                 if (e.key.keysym.mod & KMOD_CTRL)
533                 {
534                     skipkey = true;
535                     SDL_GrabMode mode = SDL_GRAB_ON;
536                     if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
537                     {
538                         mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
539                         mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
540                     }
541                     SDL_WM_GrabInput(mode);
542                 }
543             }
544
545             else if (e.key.keysym.sym == SDLK_RETURN)
546             {
547                 if (e.key.keysym.mod & KMOD_ALT)
548                 {
549                     skipkey = true;
550                     SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
551                 }
552             }
553
554             if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
555             {
556                 if (KeyTable[e.key.keysym.sym] != 0xffff)
557                     SetKey(KeyTable[e.key.keysym.sym]);
558             }
559
560             mod = SDL_GetModState();
561             if (mod & KMOD_CTRL)
562                 SetKey(MAC_CONTROL_KEY);
563             if (mod & KMOD_ALT)
564                 SetKey(MAC_OPTION_KEY);
565             if (mod & KMOD_META)
566                 SetKey(MAC_COMMAND_KEY);
567             if (mod & KMOD_SHIFT)
568                 SetKey(MAC_SHIFT_KEY);
569             if (mod & KMOD_CAPS)
570                 SetKey(MAC_CAPS_LOCK_KEY);
571
572             return;
573
574         case SDL_KEYUP:
575             if (e.key.keysym.sym < SDLK_LAST)
576             {
577                 if (KeyTable[e.key.keysym.sym] != 0xffff)
578                     ClearKey(KeyTable[e.key.keysym.sym]);
579             }
580
581             mod = SDL_GetModState();
582             if ((mod & KMOD_CTRL) == 0)
583                 ClearKey(MAC_CONTROL_KEY);
584             if ((mod & KMOD_ALT) == 0)
585                 ClearKey(MAC_OPTION_KEY);
586             if ((mod & KMOD_SHIFT) == 0)
587                 ClearKey(MAC_SHIFT_KEY);
588             if ((mod & KMOD_CAPS) == 0)
589                 ClearKey(MAC_CAPS_LOCK_KEY);
590             return;
591     }
592 }
593 #endif
594
595 // --------------------------------------------------------------------------
596
597 static Point gMidPoint;
598
599 Boolean SetUp (Game & game)
600 {
601         char string[10];
602
603         LOGFUNC;
604
605         randSeed = UpTime().lo;
606
607         osx = 0;
608         ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
609         detail=1;
610         ismotionblur=0;
611         usermousesensitivity=1;
612         kContextWidth=640;
613         kContextHeight=480;
614         kBitsPerPixel = 32;
615         floatjump=0;
616         cellophane=0;
617         texdetail=4;
618         autoslomo=1;
619         decals=1;
620         invertmouse=0;
621         bloodtoggle=0;
622         terraindetail=2;
623         foliage=1;
624         musictoggle=1;
625         trilinear=1;
626         gamespeed=1;
627         difficulty=1;
628         damageeffects=0;
629         texttoggle=1;
630         alwaysblur=0;
631         showpoints=0;
632         immediate=0;
633         velocityblur=0;
634
635         slomospeed=0.25;
636         slomofreq=8012;
637
638         volume = 0.8f;
639
640         game.crouchkey=MAC_SHIFT_KEY;
641         game.jumpkey=MAC_SPACE_KEY;
642         game.leftkey=MAC_A_KEY;
643         game.forwardkey=MAC_W_KEY;
644         game.backkey=MAC_S_KEY;
645         game.rightkey=MAC_D_KEY;
646         game.drawkey=MAC_E_KEY;
647         game.throwkey=MAC_Q_KEY;
648         game.attackkey=MAC_MOUSEBUTTON1;
649         game.chatkey=MAC_T_KEY;
650         numplayers=1;
651         ambientsound=1;
652         vblsync=0;
653         debugmode=0;
654
655         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
656
657         if(!ipstream) {
658                 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
659                 opstream << "Screenwidth:\n";
660                 opstream << kContextWidth;
661                 opstream << "\nScreenheight:\n";
662                 opstream << kContextHeight;
663                 opstream << "\nMouse sensitivity:\n";
664                 opstream << usermousesensitivity;
665                 opstream << "\nBlur(0,1):\n";
666                 opstream << ismotionblur;
667                 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
668                 opstream << detail;
669                 opstream << "\nFloating jump:\n";
670                 opstream << floatjump;
671                 opstream << "\nMouse jump:\n";
672                 opstream << mousejump;
673                 opstream << "\nAmbient sound:\n";
674                 opstream << ambientsound;
675                 opstream << "\nBlood (0,1,2):\n";
676                 opstream << bloodtoggle;
677                 opstream << "\nAuto slomo:\n";
678                 opstream << autoslomo;
679                 opstream << "\nFoliage:\n";
680                 opstream << foliage;
681                 opstream << "\nMusic:\n";
682                 opstream << musictoggle;
683                 opstream << "\nTrilinear:\n";
684                 opstream << trilinear;
685                 opstream << "\nDecals(shadows,blood puddles,etc):\n";
686                 opstream << decals;
687                 opstream << "\nInvert mouse:\n";
688                 opstream << invertmouse;
689                 opstream << "\nGamespeed:\n";
690                 opstream << gamespeed;
691                 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
692                 opstream << difficulty;
693                 opstream << "\nDamage effects(blackout, doublevision):\n";
694                 opstream << damageeffects;
695                 opstream << "\nText:\n";
696                 opstream << texttoggle;
697                 opstream << "\nDebug:\n";
698                 opstream << debugmode;
699                 opstream << "\nVBL Sync:\n";
700                 opstream << vblsync;
701                 opstream << "\nShow Points:\n";
702                 opstream << showpoints;
703                 opstream << "\nAlways Blur:\n";
704                 opstream << alwaysblur;
705                 opstream << "\nImmediate mode (turn on on G5):\n";
706                 opstream << immediate;
707                 opstream << "\nVelocity blur:\n";
708                 opstream << velocityblur;
709                 opstream << "\nVolume:\n";
710                 opstream << volume;
711                 opstream << "\nForward key:\n";
712                 opstream << KeyToChar(game.forwardkey);
713                 opstream << "\nBack key:\n";
714                 opstream << KeyToChar(game.backkey);
715                 opstream << "\nLeft key:\n";
716                 opstream << KeyToChar(game.leftkey);
717                 opstream << "\nRight key:\n";
718                 opstream << KeyToChar(game.rightkey);
719                 opstream << "\nJump key:\n";
720                 opstream << KeyToChar(game.jumpkey);
721                 opstream << "\nCrouch key:\n";
722                 opstream << KeyToChar(game.crouchkey);
723                 opstream << "\nDraw key:\n";
724                 opstream << KeyToChar(game.drawkey);
725                 opstream << "\nThrow key:\n";
726                 opstream << KeyToChar(game.throwkey);
727                 opstream << "\nAttack key:\n";
728                 opstream << KeyToChar(game.attackkey);
729                 opstream << "\nChat key:\n";
730                 opstream << KeyToChar(game.chatkey);
731                 opstream.close();
732         }
733         if(ipstream){
734                 int i;
735                 ipstream.ignore(256,'\n');
736                 ipstream >> kContextWidth;
737                 ipstream.ignore(256,'\n');
738                 ipstream.ignore(256,'\n');
739                 ipstream >> kContextHeight;
740                 ipstream.ignore(256,'\n');
741                 ipstream.ignore(256,'\n');
742                 ipstream >> usermousesensitivity;
743                 ipstream.ignore(256,'\n');
744                 ipstream.ignore(256,'\n');
745                 ipstream >> i;
746                 ismotionblur = (i != 0);
747                 ipstream.ignore(256,'\n');
748                 ipstream.ignore(256,'\n');
749                 ipstream >> detail;
750                 if(detail!=0)kBitsPerPixel=32;
751                 else kBitsPerPixel=16;
752                 ipstream.ignore(256,'\n');
753                 ipstream.ignore(256,'\n');
754                 ipstream >> i;
755                 floatjump = (i != 0);
756                 ipstream.ignore(256,'\n');
757                 ipstream.ignore(256,'\n');
758                 ipstream >> i;
759                 mousejump = (i != 0);
760                 ipstream.ignore(256,'\n');
761                 ipstream.ignore(256,'\n');
762                 ipstream >> i;
763                 ambientsound = (i != 0);
764                 ipstream.ignore(256,'\n');
765                 ipstream.ignore(256,'\n');
766                 ipstream >> bloodtoggle;
767                 ipstream.ignore(256,'\n');
768                 ipstream.ignore(256,'\n');
769                 ipstream >> i;
770                 autoslomo = (i != 0);
771                 ipstream.ignore(256,'\n');
772                 ipstream.ignore(256,'\n');
773                 ipstream >> i;
774                 foliage = (i != 0);
775                 ipstream.ignore(256,'\n');
776                 ipstream.ignore(256,'\n');
777                 ipstream >> i;
778                 musictoggle = (i != 0);
779                 ipstream.ignore(256,'\n');
780                 ipstream.ignore(256,'\n');
781                 ipstream >> i;
782                 trilinear = (i != 0);
783                 ipstream.ignore(256,'\n');
784                 ipstream.ignore(256,'\n');
785                 ipstream >> i;
786                 decals = (i != 0);
787                 ipstream.ignore(256,'\n');
788                 ipstream.ignore(256,'\n');
789                 ipstream >> i;
790                 invertmouse = (i != 0);
791                 ipstream.ignore(256,'\n');
792                 ipstream.ignore(256,'\n');
793                 ipstream >> gamespeed;
794                 oldgamespeed=gamespeed;
795                 if(oldgamespeed==0){
796                         gamespeed=1;
797                         oldgamespeed=1;
798                 }
799                 ipstream.ignore(256,'\n');
800                 ipstream.ignore(256,'\n');
801                 ipstream >> difficulty;
802                 ipstream.ignore(256,'\n');
803                 ipstream.ignore(256,'\n');
804                 ipstream >> i;
805                 damageeffects = (i != 0);
806                 ipstream.ignore(256,'\n');
807                 ipstream.ignore(256,'\n');
808                 ipstream >> i;
809                 texttoggle = (i != 0);
810                 ipstream.ignore(256,'\n');
811                 ipstream.ignore(256,'\n');
812                 ipstream >> i;
813                 debugmode = (i != 0);
814                 ipstream.ignore(256,'\n');
815                 ipstream.ignore(256,'\n');
816                 ipstream >> i;
817                 vblsync = (i != 0);
818                 ipstream.ignore(256,'\n');
819                 ipstream.ignore(256,'\n');
820                 ipstream >> i;
821                 showpoints = (i != 0);
822                 ipstream.ignore(256,'\n');
823                 ipstream.ignore(256,'\n');
824                 ipstream >> i;
825                 alwaysblur = (i != 0);
826                 ipstream.ignore(256,'\n');
827                 ipstream.ignore(256,'\n');
828                 ipstream >> i;
829                 immediate = (i != 0);
830                 ipstream.ignore(256,'\n');
831                 ipstream.ignore(256,'\n');
832                 ipstream >> i;
833                 velocityblur = (i != 0);
834                 ipstream.ignore(256,'\n');
835                 ipstream.ignore(256,'\n'); 
836                 ipstream >> volume;
837                 ipstream.ignore(256,'\n');
838                 ipstream.ignore(256,'\n'); 
839                 ipstream >> string;
840                 game.forwardkey=CharToKey(string);
841                 ipstream.ignore(256,'\n');
842                 ipstream.ignore(256,'\n');
843                 ipstream >> string;
844                 game.backkey=CharToKey(string);
845                 ipstream.ignore(256,'\n');
846                 ipstream.ignore(256,'\n');
847                 ipstream >> string;
848                 game.leftkey=CharToKey(string);
849                 ipstream.ignore(256,'\n');
850                 ipstream.ignore(256,'\n');
851                 ipstream >> string;
852                 game.rightkey=CharToKey(string);
853                 ipstream.ignore(256,'\n');
854                 ipstream.ignore(256,'\n');
855                 ipstream >> string;
856                 game.jumpkey=CharToKey(string);
857                 ipstream.ignore(256,'\n');
858                 ipstream.ignore(256,'\n');
859                 ipstream >> string;
860                 game.crouchkey=CharToKey(string);
861                 ipstream.ignore(256,'\n');
862                 ipstream.ignore(256,'\n');
863                 ipstream >> string;
864                 game.drawkey=CharToKey(string);
865                 ipstream.ignore(256,'\n');
866                 ipstream.ignore(256,'\n');
867                 ipstream >> string;
868                 game.throwkey=CharToKey(string);
869                 ipstream.ignore(256,'\n');
870                 ipstream.ignore(256,'\n');
871                 ipstream >> string;
872                 game.attackkey=CharToKey(string);
873                 ipstream.ignore(256,'\n');
874                 ipstream.ignore(256,'\n');
875                 ipstream >> string;
876                 game.chatkey=CharToKey(string);
877                 ipstream.close();
878
879                 if(detail>2)detail=2;
880                 if(detail<0)detail=0;
881                 if(screenwidth<0)screenwidth=640;
882                 if(screenheight<0)screenheight=480;
883 #if !USE_SDL  // we'll take anything that works.
884                 if(screenwidth>3000)screenwidth=640;
885                 if(screenheight>3000)screenheight=480;
886 #endif
887         }
888         if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
889                 kBitsPerPixel=16;
890         }
891
892
893         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
894
895         SetupDSpFullScreen();
896
897 #if USE_SDL
898     if (!SDL_WasInit(SDL_INIT_VIDEO))
899     {
900         if (SDL_Init(SDL_INIT_VIDEO) == -1)
901         {
902             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
903             return false;
904         }
905
906         if (SDL_GL_LoadLibrary(NULL) == -1)
907         {
908             fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
909             SDL_Quit();
910             return false;
911         }
912
913         SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
914         if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
915             res = hardcoded_resolutions;
916
917         // reverse list (it was sorted biggest to smallest by SDL)...
918         int count;
919         for (count = 0; res[count]; count++)
920         {
921             if ((res[count]->w < 640) || (res[count]->h < 480))
922                 break;   // sane lower limit.
923         }
924
925         static SDL_Rect *resolutions_block = NULL;
926         resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
927         resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
928         if ((resolutions_block == NULL) || (resolutions == NULL))
929         {
930             SDL_Quit();
931             fprintf(stderr, "Out of memory!\n");
932             return false;
933         }
934
935         resolutions[count--] = NULL;
936         for (int i = 0; count >= 0; i++, count--)
937         {
938             memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
939             resolutions[count] = &resolutions_block[count];
940         }
941
942         if (cmdline("showresolutions"))
943         {
944             printf("Resolutions we think are okay:\n");
945             for (int i = 0; resolutions[i]; i++)
946                 printf("  %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
947         }
948     }
949
950     Uint32 sdlflags = SDL_OPENGL;
951     if (!cmdline("windowed"))
952         sdlflags |= SDL_FULLSCREEN;
953
954     SDL_WM_SetCaption("Lugaru", "Lugaru");
955
956     SDL_ShowCursor(0);
957
958     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
959
960     if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
961     {
962         fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
963         fprintf(stderr, "forcing 640x480...\n");
964         kContextWidth = 640;
965         kContextHeight = 480;
966         if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
967         {
968             fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
969             fprintf(stderr, "forcing 640x480 windowed mode...\n");
970             sdlflags &= ~SDL_FULLSCREEN;
971             if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
972             {
973                 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
974                 return false;
975             }
976         }
977     }
978
979     int dblbuf = 0;
980     if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
981     {
982         fprintf(stderr, "Failed to get double buffered GL context!\n");
983         SDL_Quit();
984         return false;
985     }
986
987     if (!lookup_all_glsyms())
988     {
989         SDL_Quit();
990         return false;
991     }
992
993     if (!cmdline("nomousegrab"))
994         SDL_WM_GrabInput(SDL_GRAB_ON);
995
996 #elif (defined WIN32)
997         //------------------------------------------------------------------
998         // create window
999         int x = 0, y = 0;
1000         RECT r = {0, 0, kContextWidth-1, kContextHeight-1};
1001         DWORD dwStyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE;
1002         DWORD dwExStyle = WS_EX_APPWINDOW;
1003
1004         if (fullscreen)
1005         {
1006                 dwStyle |= WS_POPUP;
1007         }
1008         else
1009         {
1010
1011                 dwStyle |= WS_OVERLAPPEDWINDOW;
1012                 dwExStyle |= WS_EX_WINDOWEDGE;
1013         }
1014
1015         AdjustWindowRectEx(&r, dwStyle, FALSE, dwExStyle);
1016
1017         if (!fullscreen)
1018         {
1019                 x = (GetSystemMetrics(SM_CXSCREEN) >> 1) - ((r.right - r.left + 1) >> 1);
1020                 y = (GetSystemMetrics(SM_CYSCREEN) >> 1) - ((r.bottom - r.top + 1) >> 1);
1021         }
1022
1023         g_windowHandle=CreateWindowEx(
1024                 dwExStyle,
1025                 g_wndClassName, "Lugaru", dwStyle,
1026                 x, y,
1027 //              kContextWidth, kContextHeight,
1028                 r.right - r.left + 1, r.bottom - r.top + 1,
1029                 NULL,NULL,g_appInstance,NULL );
1030         if (!g_windowHandle)
1031         {
1032                 ReportError("Could not create window");
1033                 return false;
1034         }
1035
1036         //------------------------------------------------------------------
1037         // setup OpenGL
1038
1039         static PIXELFORMATDESCRIPTOR pfd =
1040         {
1041                 sizeof(PIXELFORMATDESCRIPTOR),                          // Size Of This Pixel Format Descriptor
1042                         1,                                                                                      // Version Number
1043                         PFD_DRAW_TO_WINDOW |                                            // Format Must Support Window
1044                         PFD_SUPPORT_OPENGL |                                            // Format Must Support OpenGL
1045                         PFD_DOUBLEBUFFER,                                                       // Must Support Double Buffering
1046                         PFD_TYPE_RGBA,                                                          // Request An RGBA Format
1047                         kBitsPerPixel,                                                          // Select Our Color Depth
1048                         0, 0, 0, 0, 0, 0,                                                       // Color Bits Ignored
1049                         0,                                                                                      // No Alpha Buffer
1050                         0,                                                                                      // Shift Bit Ignored
1051                         0,                                                                                      // No Accumulation Buffer
1052                         0, 0, 0, 0,                                                                     // Accumulation Bits Ignored
1053                         16,                                                                                     // 16Bit Z-Buffer (Depth Buffer)  
1054                         0,                                                                                      // No Stencil Buffer
1055                         0,                                                                                      // No Auxiliary Buffer
1056                         PFD_MAIN_PLANE,                                                         // Main Drawing Layer
1057                         0,                                                                                      // Reserved
1058                         0, 0, 0                                                                         // Layer Masks Ignored
1059         };
1060
1061         if (!(hDC = GetDC( g_windowHandle)))
1062                 ReportError( "Could not get device context");
1063
1064         GLuint PixelFormat;
1065         if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))
1066         {
1067                 ReportError( "Could not find appropriate pixel format");
1068                 return false;
1069         }
1070
1071         if (!DescribePixelFormat(hDC, PixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd))
1072         {
1073                 ReportError( "Could not retrieve pixel format");
1074                 return false;
1075         }
1076
1077         if (!SetPixelFormat( hDC, PixelFormat, &pfd))
1078         {
1079                 ReportError( "Could not set pixel format");
1080                 return false;
1081         }
1082
1083         if (!(hRC = wglCreateContext(hDC)))
1084         {
1085                 ReportError( "Could not create rendering context");
1086                 return false;
1087         }
1088
1089         if (!wglMakeCurrent(hDC, hRC))
1090         {
1091                 ReportError( "Could not activate rendering context");
1092                 return false;
1093         }
1094
1095         if (fullscreen)
1096         {
1097                 // Place the window above all topmost windows
1098                 SetWindowPos( g_windowHandle, HWND_TOPMOST, 0,0,0,0,
1099                         SWP_NOMOVE | SWP_NOSIZE );
1100         }
1101
1102         SetForegroundWindow(g_windowHandle);
1103         SetFocus(g_windowHandle);
1104 #endif
1105
1106         glClear( GL_COLOR_BUFFER_BIT );
1107         swap_gl_buffers();
1108
1109         // clear all states
1110         glDisable( GL_ALPHA_TEST);
1111         glDisable( GL_BLEND);
1112         glDisable( GL_DEPTH_TEST);
1113         //      glDisable( GL_DITHER);
1114         glDisable( GL_FOG);
1115         glDisable( GL_LIGHTING);
1116         glDisable( GL_LOGIC_OP);
1117         glDisable( GL_STENCIL_TEST);
1118         glDisable( GL_TEXTURE_1D);
1119         glDisable( GL_TEXTURE_2D);
1120         glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
1121         glPixelTransferi( GL_RED_SCALE, 1);
1122         glPixelTransferi( GL_RED_BIAS, 0);
1123         glPixelTransferi( GL_GREEN_SCALE, 1);
1124         glPixelTransferi( GL_GREEN_BIAS, 0);
1125         glPixelTransferi( GL_BLUE_SCALE, 1);
1126         glPixelTransferi( GL_BLUE_BIAS, 0);
1127         glPixelTransferi( GL_ALPHA_SCALE, 1);
1128         glPixelTransferi( GL_ALPHA_BIAS, 0);
1129
1130         // set initial rendering states
1131         glShadeModel( GL_SMOOTH);
1132         glClearDepth( 1.0f);
1133         glDepthFunc( GL_LEQUAL);
1134         glDepthMask( GL_TRUE);
1135         //      glDepthRange( FRONT_CLIP, BACK_CLIP);
1136         glEnable( GL_DEPTH_TEST);
1137         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
1138         glCullFace( GL_FRONT);
1139         glEnable( GL_CULL_FACE);
1140         glEnable( GL_LIGHTING);
1141 //      glEnable( GL_LIGHT_MODEL_AMBIENT);
1142         glEnable( GL_DITHER);
1143         glEnable( GL_COLOR_MATERIAL);
1144         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1145         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1146         glAlphaFunc( GL_GREATER, 0.5f);
1147
1148 #if USE_DEVIL
1149         if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION ||
1150                 iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION ||
1151                 ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION)
1152         {
1153                 ReportError("DevIL version is different...exiting!\n");
1154                 return false;
1155         }
1156
1157         ilInit();
1158         iluInit();
1159         ilutInit();
1160
1161         ilutRenderer(ILUT_OPENGL);
1162
1163         ilEnable(IL_ORIGIN_SET);
1164         ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
1165 #endif
1166
1167         GLint width = kContextWidth;
1168         GLint height = kContextHeight;
1169         gMidPoint.h = width / 2;
1170         gMidPoint.v = height / 2;
1171         screenwidth=width;
1172         screenheight=height;
1173
1174         game.newdetail=detail;
1175         game.newscreenwidth=screenwidth;
1176         game.newscreenheight=screenheight;
1177
1178         game.InitGame();
1179
1180         return true;
1181 }
1182
1183
1184 static void DoMouse(Game & game)
1185 {
1186 #if USE_SDL
1187         if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1188         {
1189                 game.deltah *= usermousesensitivity;
1190                 game.deltav *= usermousesensitivity;
1191                 game.mousecoordh += game.deltah;
1192                 game.mousecoordv += game.deltav;
1193         if (game.mousecoordh < 0)
1194             game.mousecoordh = 0;
1195         else if (game.mousecoordh >= kContextWidth)
1196             game.mousecoordh = kContextWidth - 1;
1197         if (game.mousecoordv < 0)
1198             game.mousecoordv = 0;
1199         else if (game.mousecoordv >= kContextHeight)
1200             game.mousecoordv = kContextHeight - 1;
1201         }
1202 #else
1203         static Point lastMouse = {-1,-1};
1204         Point globalMouse;
1205
1206         POINT pos;
1207         GetCursorPos(&pos);
1208         ScreenToClient(g_windowHandle, &pos);
1209         globalMouse.h = pos.x;
1210         globalMouse.v = pos.y;
1211
1212         if (lastMouse.h == globalMouse.h && lastMouse.v == globalMouse.v)
1213         {
1214                 game.deltah=0;
1215                 game.deltav=0;
1216         }
1217         else
1218         {
1219                 static Point virtualMouse = {0,0};
1220                 delta = globalMouse;
1221
1222                 delta.h -= lastMouse.h;
1223                 delta.v -= lastMouse.v;
1224                 lastMouse.h = pos.x;
1225                 lastMouse.v = pos.y;
1226
1227                 if(mainmenu||(abs(delta.h)<10*realmultiplier*1000&&abs(delta.v)<10*realmultiplier*1000)){
1228                         game.deltah=delta.h*usermousesensitivity;
1229                         game.deltav=delta.v*usermousesensitivity;
1230                         game.mousecoordh=globalMouse.h;
1231                         game.mousecoordv=globalMouse.v;
1232                 }
1233
1234                 if(!mainmenu)
1235                 {
1236                         if(lastMouse.h>gMidPoint.h+100||lastMouse.h<gMidPoint.h-100||lastMouse.v>gMidPoint.v+100||lastMouse.v<gMidPoint.v-100){
1237                                 pos.x = gMidPoint.h;
1238                                 pos.y = gMidPoint.v;
1239                                 ClientToScreen(g_windowHandle, &pos);
1240                                 //SetCursorPos( gMidPoint.h,gMidPoint.v);
1241                                 SetCursorPos(pos.x, pos.y);
1242                                 lastMouse = gMidPoint;
1243                         }
1244                 }
1245         }
1246 #endif
1247 }
1248
1249
1250
1251 // --------------------------------------------------------------------------
1252
1253 void DoKey (SInt8 theKey, SInt8 theCode)
1254 {
1255         // do nothing
1256 }
1257
1258 // --------------------------------------------------------------------------
1259
1260
1261
1262 void DoFrameRate (int update)
1263 {       
1264         static long frames = 0;
1265
1266         static AbsoluteTime time = {0,0};
1267         static AbsoluteTime frametime = {0,0};
1268         AbsoluteTime currTime = UpTime ();
1269         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1270
1271         if (0 > deltaTime)      // if negative microseconds
1272                 deltaTime /= -1000000.0;
1273         else                            // else milliseconds
1274                 deltaTime /= 1000.0;
1275
1276         multiplier=deltaTime;
1277         if(multiplier<.001)multiplier=.001;
1278         if(multiplier>10)multiplier=10;
1279         if(update)frametime = currTime; // reset for next time interval
1280
1281         deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1282
1283         if (0 > deltaTime)      // if negative microseconds
1284                 deltaTime /= -1000000.0;
1285         else                            // else milliseconds
1286                 deltaTime /= 1000.0;
1287         frames++;
1288         if (0.001 <= deltaTime) // has update interval passed
1289         {
1290                 if(update){
1291                         time = currTime;        // reset for next time interval
1292                         frames = 0;
1293                 }
1294         }
1295 }
1296
1297
1298 void DoUpdate (Game & game)
1299 {
1300         static float sps=200;
1301         static int count;
1302         static float oldmult;
1303
1304         DoFrameRate(1);
1305         if(multiplier>.6)multiplier=.6;
1306
1307         game.fps=1/multiplier;
1308
1309         count = multiplier*sps;
1310         if(count<2)count=2;
1311         //if(count>10)count=10;
1312
1313         realmultiplier=multiplier;
1314         multiplier*=gamespeed;
1315         if(difficulty==1)multiplier*=.9;
1316         if(difficulty==0)multiplier*=.8;
1317
1318         if(game.loading==4)multiplier*=.00001;
1319         //multiplier*.9;
1320         if(slomo&&!mainmenu)multiplier*=slomospeed;
1321         //if(freeze)multiplier*=0.00001;
1322         oldmult=multiplier;
1323         multiplier/=(float)count;
1324
1325         DoMouse(game);
1326
1327         game.TickOnce();
1328
1329         for(int i=0;i<count;i++)
1330         {
1331                 game.Tick();
1332         }
1333         multiplier=oldmult;
1334
1335         game.TickOnceAfter();
1336 /* - Debug code to test how many channels were active on average per frame
1337         static long frames = 0;
1338
1339         static AbsoluteTime start = {0,0};
1340         AbsoluteTime currTime = UpTime ();
1341         static int num_channels = 0;
1342         
1343         num_channels += FSOUND_GetChannelsPlaying();
1344         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1345
1346         if (0 > deltaTime)      // if negative microseconds
1347                 deltaTime /= -1000000.0;
1348         else                            // else milliseconds
1349                 deltaTime /= 1000.0;
1350
1351         ++frames;
1352
1353         if (deltaTime >= 1)
1354         {
1355                 start = currTime;
1356                 float avg_channels = (float)num_channels / (float)frames;
1357
1358                 ofstream opstream("log.txt",ios::app); 
1359                 opstream << "Average frame count: ";
1360                 opstream << frames;
1361                 opstream << " frames - ";
1362                 opstream << avg_channels;
1363                 opstream << " per frame.\n";
1364                 opstream.close();
1365
1366                 frames = 0;
1367                 num_channels = 0;
1368         }
1369 */
1370         DrawGL (game);
1371 }
1372
1373 // --------------------------------------------------------------------------
1374
1375
1376 void CleanUp (void)
1377 {
1378         LOGFUNC;
1379
1380 //      game.Dispose();
1381
1382 #if USE_DEVIL
1383         ilShutDown();
1384 #endif
1385
1386 #if USE_SDL
1387     SDL_Quit();
1388     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1389     #include "glstubs.h"
1390     #undef GL_FUNC
1391     // cheat here...static destructors are calling glDeleteTexture() after
1392     //  the context is destroyed and libGL unloaded by SDL_Quit().
1393     pglDeleteTextures = glDeleteTextures_doNothing;
1394
1395 #elif (defined WIN32)
1396         if (hRC)
1397         {
1398                 wglMakeCurrent( NULL, NULL);
1399                 wglDeleteContext( hRC);
1400                 hRC = NULL;
1401         }
1402
1403         if (hDC)
1404         {
1405                 ReleaseDC( g_windowHandle, hDC);
1406                 hDC = NULL;
1407         }
1408
1409         if (g_windowHandle)
1410         {
1411                 ShowWindow( g_windowHandle, SW_HIDE );
1412                 DestroyWindow( g_windowHandle);
1413                 g_windowHandle = NULL;
1414         }
1415
1416         ShutdownDSp ();
1417         ClipCursor(NULL);
1418 #endif
1419 }
1420
1421 // --------------------------------------------------------------------------
1422
1423 static bool g_focused = true;
1424
1425
1426 static bool IsFocused()
1427 {
1428 #ifdef WIN32
1429         if (!g_focused)
1430                 return false;
1431
1432         if (GetActiveWindow() != g_windowHandle)
1433                 return false;
1434
1435         if (IsIconic( g_windowHandle))
1436                 return false;
1437 #endif
1438
1439         return true;
1440 }
1441
1442
1443 static void launch_web_browser(const char *url)
1444 {
1445 #ifdef WIN32
1446     ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1447
1448 #elif (defined(__APPLE__) && defined(__MACH__))
1449     const char *fmt = "open '%s'";
1450     const size_t len = strlen(fmt) + strlen(url) + 16;
1451     char *buf = new char[len];
1452     snprintf(buf, len, fmt, url);
1453     system(buf);
1454     delete[] buf;
1455
1456 #elif PLATFORM_LINUX
1457     const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1458     const size_t len = strlen(fmt) + strlen(url) + 16;
1459     char *buf = new char[len];
1460     snprintf(buf, len, fmt, url);
1461     system(buf);
1462     delete[] buf;
1463 #endif
1464 }
1465
1466
1467 #ifndef WIN32
1468 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1469 static char *findBinaryInPath(const char *bin, char *envr)
1470 {
1471     size_t alloc_size = 0;
1472     char *exe = NULL;
1473     char *start = envr;
1474     char *ptr;
1475
1476     do
1477     {
1478         size_t size;
1479         ptr = strchr(start, ':');  /* find next $PATH separator. */
1480         if (ptr)
1481             *ptr = '\0';
1482
1483         size = strlen(start) + strlen(bin) + 2;
1484         if (size > alloc_size)
1485         {
1486             char *x = (char *) realloc(exe, size);
1487             if (x == NULL)
1488             {
1489                 if (exe != NULL)
1490                     free(exe);
1491                 return(NULL);
1492             } /* if */
1493
1494             alloc_size = size;
1495             exe = x;
1496         } /* if */
1497
1498         /* build full binary path... */
1499         strcpy(exe, start);
1500         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1501             strcat(exe, "/");
1502         strcat(exe, bin);
1503
1504         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
1505         {
1506             strcpy(exe, start);  /* i'm lazy. piss off. */
1507             return(exe);
1508         } /* if */
1509
1510         start = ptr + 1;  /* start points to beginning of next element. */
1511     } while (ptr != NULL);
1512
1513     if (exe != NULL)
1514         free(exe);
1515
1516     return(NULL);  /* doesn't exist in path. */
1517 } /* findBinaryInPath */
1518
1519
1520 char *calcBaseDir(const char *argv0)
1521 {
1522     /* If there isn't a path on argv0, then look through the $PATH for it. */
1523     char *retval;
1524     char *envr;
1525
1526     char *ptr = strrchr((char *)argv0, '/');
1527     if (strchr(argv0, '/'))
1528     {
1529         retval = strdup(argv0);
1530         if (retval)
1531             *(strrchr(retval, '/')) = '\0';
1532         return(retval);
1533     }
1534
1535     envr = getenv("PATH");
1536     if (!envr) return NULL;
1537     envr = strdup(envr);
1538     if (!envr) return NULL;
1539     retval = findBinaryInPath(argv0, envr);
1540     free(envr);
1541     return(retval);
1542 }
1543
1544 static inline void chdirToAppPath(const char *argv0)
1545 {
1546     char *dir = calcBaseDir(argv0);
1547     if (dir)
1548     {
1549         #if (defined(__APPLE__) && defined(__MACH__))
1550         // Chop off /Contents/MacOS if it's at the end of the string, so we
1551         //  land in the base of the app bundle.
1552         const size_t len = strlen(dir);
1553         const char *bundledirs = "/Contents/MacOS";
1554         const size_t bundledirslen = strlen(bundledirs);
1555         if (len > bundledirslen)
1556         {
1557             char *ptr = (dir + len) - bundledirslen;
1558             if (strcasecmp(ptr, bundledirs) == 0)
1559                 *ptr = '\0';
1560         }
1561         #endif
1562         chdir(dir);
1563         free(dir);
1564     }
1565 }
1566 #endif
1567
1568
1569 int main(int argc, char **argv)
1570 {
1571     _argc = argc;
1572     _argv = argv;
1573 #ifndef WIN32
1574     chdirToAppPath(argv[0]);
1575 #endif
1576
1577         LOGFUNC;
1578
1579 #ifndef WIN32  // this is in WinMain, too.
1580         memset( &g_theKeys, 0, sizeof( KeyMap));
1581 #endif
1582
1583     initSDLKeyTable();
1584
1585         try
1586         {
1587                 bool regnow = false;
1588                 {
1589                         Game game;
1590                         pgame = &game;
1591
1592                         //ofstream os("error.txt");
1593                         //os.close();
1594                         //ofstream os("log.txt");
1595                         //os.close();
1596
1597                         if (!SetUp (game))
1598                 return 42;
1599
1600                         while (!gDone&&!game.quit&&(!game.tryquit||!game.registered))
1601                         {
1602                                 if (IsFocused())
1603                                 {
1604                                         gameFocused = true;
1605
1606                                         // check windows messages
1607                                         #if USE_SDL
1608                                         game.deltah = 0;
1609                                         game.deltav = 0;
1610                                         SDL_Event e;
1611                                         // message pump
1612                                         while( SDL_PollEvent( &e ) )
1613                                         {
1614                                                 if( e.type == SDL_QUIT )
1615                                                 {
1616                                                         gDone=true;
1617                                                         break;
1618                                                 }
1619                                                 sdlEventProc(e, game);
1620                                         }
1621
1622                                         #elif (defined WIN32)
1623                                         MSG msg;
1624                                         // message pump
1625                                         while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE | PM_NOYIELD ) )
1626                                         {
1627                                                 if( msg.message == WM_QUIT )
1628                                                 {
1629                                                         gDone=true;
1630                                                         break;
1631                                                 }
1632                                                 else
1633                                                 {
1634                                                         TranslateMessage( &msg );
1635                                                         DispatchMessage( &msg );
1636                                                 }
1637                                         }
1638                                         #endif
1639
1640                                         // game
1641                                         DoUpdate(game);
1642                                 }
1643                                 else
1644                                 {
1645                                         if (gameFocused)
1646                                         {
1647                                                 // allow game chance to pause
1648                                                 gameFocused = false;
1649                                                 DoUpdate(game);
1650                                         }
1651
1652                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1653                     #ifdef WIN32
1654                                         MSG msg;
1655                                         BOOL bRet;
1656                                         //if (GetMessage( &msg, g_windowHandle, 0, 0 ))
1657                                         /*if (GetMessage( &msg, NULL, 0, 0 ))
1658                                         {
1659                                                 TranslateMessage(&msg);
1660                                                 DispatchMessage(&msg);
1661                                         }*/
1662                                         if ( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
1663                                         { 
1664                                                 if (bRet <= 0)
1665                                                 {
1666                                                         // handle the error and possibly exit
1667                                                         gDone=true;
1668                                                 }
1669                                                 else
1670                                                 {
1671                                                         TranslateMessage(&msg); 
1672                                                         DispatchMessage(&msg); 
1673                                                 }
1674                                         }
1675                     #else
1676                     STUBBED("give up CPU but sniff the event queue");
1677                     #endif
1678                                 }
1679                         }
1680
1681                         regnow = game.registernow;
1682                 }
1683                 pgame = 0;
1684
1685                 CleanUp ();
1686 //              if(game.registernow){
1687                 if(regnow)
1688                 {
1689             #if (defined(__APPLE__) && defined(__MACH__))
1690             launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1691             #elif PLATFORM_LINUX
1692             launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1693             #else
1694             launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1695             #endif
1696                 }
1697
1698         #if PLATFORM_LINUX  // (this may not be necessary any more.)
1699         _exit(0);  // !!! FIXME: hack...crashes on exit!
1700         #endif
1701                 return 0;
1702         }
1703         catch (const std::exception& error)
1704         {
1705                 CleanUp();
1706
1707                 std::string e = "Caught exception: ";
1708                 e += error.what();
1709
1710                 LOG(e);
1711
1712                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1713         }
1714
1715         CleanUp();
1716
1717         return -1;
1718 }
1719
1720
1721
1722         // --------------------------------------------------------------------------
1723
1724 #ifdef WIN32
1725 #define MAX_WINKEYS 256
1726         static unsigned short KeyTable[MAX_WINKEYS]=
1727         {
1728                 0xffff,  // (0)
1729                         MAC_MOUSEBUTTON1,  // VK_LBUTTON        (1)
1730                         MAC_MOUSEBUTTON2,  // VK_RBUTTON        (2)
1731                         0xffff,  // VK_CANCEL   (3)
1732                         0xffff,  // VK_MBUTTON  (4)
1733                         0xffff,  // (5)
1734                         0xffff,  // (6)
1735                         0xffff,  // (7)
1736                         MAC_DELETE_KEY,  // VK_BACK     (8)
1737                         MAC_TAB_KEY,  // VK_TAB (9)
1738                         0xffff,  // (10)
1739                         0xffff,  // (11)
1740                         0xffff,  // VK_CLEAR    (12)
1741                         MAC_RETURN_KEY,  // VK_RETURN   (13)
1742                         0xffff,  // (14)
1743                         0xffff,  // (15)
1744                         MAC_SHIFT_KEY,  // VK_SHIFT     (16)
1745                         MAC_CONTROL_KEY,  // VK_CONTROL (17)
1746                         MAC_OPTION_KEY,  // VK_MENU     (18)
1747                         0xffff,  // VK_PAUSE    (19)
1748                         MAC_CAPS_LOCK_KEY,  // #define VK_CAPITAL       (20)
1749                         0xffff,  // (21)
1750                         0xffff,  // (22)
1751                         0xffff,  // (23)
1752                         0xffff,  // (24)
1753                         0xffff,  // (25)
1754                         0xffff,  // (26)
1755                         MAC_ESCAPE_KEY,  // VK_ESCAPE   (27)
1756                         0xffff,  // (28)
1757                         0xffff,  // (29)
1758                         0xffff,  // (30)
1759                         0xffff,  // (31)
1760                         MAC_SPACE_KEY,  // VK_SPACE     (32)
1761                         MAC_PAGE_UP_KEY,  // VK_PRIOR   (33)
1762                         MAC_PAGE_DOWN_KEY,  // VK_NEXT  (34)
1763                         MAC_END_KEY,  // VK_END (35)
1764                         MAC_HOME_KEY,  // VK_HOME       (36)
1765                         MAC_ARROW_LEFT_KEY,  // VK_LEFT (37)
1766                         MAC_ARROW_UP_KEY,  // VK_UP     (38)
1767                         MAC_ARROW_RIGHT_KEY,  // VK_RIGHT       (39)
1768                         MAC_ARROW_DOWN_KEY,  // VK_DOWN (40)
1769                         0xffff,  // VK_SELECT   (41)
1770                         0xffff,  // VK_PRINT    (42)
1771                         0xffff,  // VK_EXECUTE  (43)
1772                         0xffff,  // VK_SNAPSHOT (44)
1773                         MAC_INSERT_KEY,  // VK_INSERT   (45)
1774                         MAC_DEL_KEY,  // VK_DELETE      (46)
1775                         0xffff,  // VK_HELP     (47)
1776                         MAC_0_KEY,  // VK_0     (48)
1777                         MAC_1_KEY,  // VK_1     (49)
1778                         MAC_2_KEY,  // VK_2     (50)
1779                         MAC_3_KEY,  // VK_3     (51)
1780                         MAC_4_KEY,  // VK_4     (52)
1781                         MAC_5_KEY,  // VK_5     (53)
1782                         MAC_6_KEY,  // VK_6     (54)
1783                         MAC_7_KEY,  // VK_7     (55)
1784                         MAC_8_KEY,  // VK_8     (56)
1785                         MAC_9_KEY,  // VK_9     (57)
1786                         0xffff,  // (58)
1787                         0xffff,  // (59)
1788                         0xffff,  // (60)
1789                         0xffff,  // (61)
1790                         0xffff,  // (62)
1791                         0xffff,  // (63)
1792                         0xffff,  // (64)
1793                         MAC_A_KEY,  // VK_A     (65)
1794                         MAC_B_KEY,  // VK_B     (66)
1795                         MAC_C_KEY,  // VK_C     (67)
1796                         MAC_D_KEY,  // VK_D     (68)
1797                         MAC_E_KEY,  // VK_E     (69)
1798                         MAC_F_KEY,  // VK_F     (70)
1799                         MAC_G_KEY,  // VK_G     (71)
1800                         MAC_H_KEY,  // VK_H     (72)
1801                         MAC_I_KEY,  // VK_I     (73)
1802                         MAC_J_KEY,  // VK_J     (74)
1803                         MAC_K_KEY,  // VK_K     (75)
1804                         MAC_L_KEY,  // VK_L     (76)
1805                         MAC_M_KEY,  // VK_M     (77)
1806                         MAC_N_KEY,  // VK_N     (78)
1807                         MAC_O_KEY,  // VK_O     (79)
1808                         MAC_P_KEY,  // VK_P     (80)
1809                         MAC_Q_KEY,  // VK_Q     (81)
1810                         MAC_R_KEY,  // VK_R     (82)
1811                         MAC_S_KEY,  // VK_S     (83)
1812                         MAC_T_KEY,  // VK_T     (84)
1813                         MAC_U_KEY,  // VK_U     (85)
1814                         MAC_V_KEY,  // VK_V     (86)
1815                         MAC_W_KEY,  // VK_W     (87)
1816                         MAC_X_KEY,  // VK_X     (88)
1817                         MAC_Y_KEY,  // VK_Y     (89)
1818                         MAC_Z_KEY,  // VK_Z     (90)
1819                         0xffff,  // (91)
1820                         0xffff,  // (92)
1821                         0xffff,  // (93)
1822                         0xffff,  // (94)
1823                         0xffff,  // (95)
1824                         MAC_NUMPAD_0_KEY,  // VK_NUMPAD0        (96)
1825                         MAC_NUMPAD_1_KEY,  // VK_NUMPAD1        (97)
1826                         MAC_NUMPAD_2_KEY,  // VK_NUMPAD2        (98)
1827                         MAC_NUMPAD_3_KEY,  // VK_NUMPAD3        (99)
1828                         MAC_NUMPAD_4_KEY,  // VK_NUMPAD4        (100)
1829                         MAC_NUMPAD_5_KEY,  // VK_NUMPAD5        (101)
1830                         MAC_NUMPAD_6_KEY,  // VK_NUMPAD6        (102)
1831                         MAC_NUMPAD_7_KEY,  // VK_NUMPAD7        (103)
1832                         MAC_NUMPAD_8_KEY,  // VK_NUMPAD8        (104)
1833                         MAC_NUMPAD_9_KEY,  // VK_NUMPAD9        (105)
1834                         MAC_NUMPAD_ASTERISK_KEY,  // VK_MULTIPLY        (106)
1835                         MAC_NUMPAD_PLUS_KEY,  // VK_ADD (107)
1836                         MAC_NUMPAD_ENTER_KEY,  // VK_SEPARATOR  (108)
1837                         MAC_NUMPAD_MINUS_KEY,  // VK_SUBTRACT   (109)
1838                         MAC_NUMPAD_PERIOD_KEY,  // VK_DECIMAL   (110)
1839                         MAC_NUMPAD_SLASH_KEY,  // VK_DIVIDE     (111)
1840                         MAC_F1_KEY,  // VK_F1   (112)
1841                         MAC_F2_KEY,  // VK_F2   (113)
1842                         MAC_F3_KEY,  // VK_F3   (114)
1843                         MAC_F4_KEY,  // VK_F4   (115)
1844                         MAC_F5_KEY,  // VK_F5   (116)
1845                         MAC_F6_KEY,  // VK_F6   (117)
1846                         MAC_F7_KEY,  // VK_F7   (118)
1847                         MAC_F8_KEY,  // VK_F8   (119)
1848                         MAC_F9_KEY,  // VK_F9   (120)
1849                         MAC_F10_KEY,  // VK_F10 (121)
1850                         MAC_F11_KEY,  // VK_F11 (122)
1851                         MAC_F12_KEY,  // VK_F12 (123)
1852                         0xffff,  // (124)
1853                         0xffff,  // (125)
1854                         0xffff,  // (126)
1855                         0xffff,  // (127)
1856                         0xffff,  // (128)
1857                         0xffff,  // (129)
1858                         0xffff,  // (130)
1859                         0xffff,  // (131)
1860                         0xffff,  // (132)
1861                         0xffff,  // (133)
1862                         0xffff,  // (134)
1863                         0xffff,  // (135)
1864                         0xffff,  // (136)
1865                         0xffff,  // (137)
1866                         0xffff,  // (138)
1867                         0xffff,  // (139)
1868                         0xffff,  // (130)
1869                         0xffff,  // (141)
1870                         0xffff,  // (142)
1871                         0xffff,  // (143)
1872                         0xffff,  // VK_NUMLOCK  (144)
1873                         0xffff,  // VK_SCROLL   (145)
1874                         0xffff,  // (146)
1875                         0xffff,  // (147)
1876                         0xffff,  // (148)
1877                         0xffff,  // (149)
1878                         0xffff,  // (150)
1879                         0xffff,  // (151)
1880                         0xffff,  // (152)
1881                         0xffff,  // (153)
1882                         0xffff,  // (154)
1883                         0xffff,  // (155)
1884                         0xffff,  // (156)
1885                         0xffff,  // (157)
1886                         0xffff,  // (158)
1887                         0xffff,  // (159)
1888                         MAC_SHIFT_KEY,  // VK_LSHIFT    (160)
1889                         MAC_SHIFT_KEY,  // VK_RSHIFT    (161)
1890                         MAC_CONTROL_KEY,  // VK_LCONTROL        (162)
1891                         MAC_CONTROL_KEY,  // VK_RCONTROL        (163)
1892                         MAC_OPTION_KEY,  // VK_LMENU    (164)
1893                         MAC_OPTION_KEY,  // VK_RMENU    (165)
1894                         0xffff,  // (166)
1895                         0xffff,  // (167)
1896                         0xffff,  // (168)
1897                         0xffff,  // (169)
1898                         0xffff,  // (170)
1899                         0xffff,  // (171)
1900                         0xffff,  // (172)
1901                         0xffff,  // (173)
1902                         0xffff,  // (174)
1903                         0xffff,  // (175)
1904                         0xffff,  // (176)
1905                         0xffff,  // (177)
1906                         0xffff,  // (178)
1907                         0xffff,  // (179)
1908                         0xffff,  // (180)
1909                         0xffff,  // (181)
1910                         0xffff,  // (182)
1911                         0xffff,  // (183)
1912                         0xffff,  // (184)
1913                         0xffff,  // (185)
1914                         MAC_SEMICOLON_KEY,  // (186)
1915                         MAC_PLUS_KEY,  // (187)
1916                         MAC_COMMA_KEY,  // (188)
1917                         MAC_MINUS_KEY,  // (189)
1918                         MAC_PERIOD_KEY,  // (190)
1919                         MAC_SLASH_KEY,  // (191)
1920                         MAC_TILDE_KEY,  // (192)
1921                         0xffff,  // (193)
1922                         0xffff,  // (194)
1923                         0xffff,  // (195)
1924                         0xffff,  // (196)
1925                         0xffff,  // (197)
1926                         0xffff,  // (198)
1927                         0xffff,  // (199)
1928                         0xffff,  // (200)
1929                         0xffff,  // (201)
1930                         0xffff,  // (202)
1931                         0xffff,  // (203)
1932                         0xffff,  // (204)
1933                         0xffff,  // (205)
1934                         0xffff,  // (206)
1935                         0xffff,  // (207)
1936                         0xffff,  // (208)
1937                         0xffff,  // (209)
1938                         0xffff,  // (210)
1939                         0xffff,  // (211)
1940                         0xffff,  // (212)
1941                         0xffff,  // (213)
1942                         0xffff,  // (214)
1943                         0xffff,  // (215)
1944                         0xffff,  // (216)
1945                         0xffff,  // (217)
1946                         0xffff,  // (218)
1947                         MAC_LEFTBRACKET_KEY,  // (219)
1948                         MAC_BACKSLASH_KEY,  // (220)
1949                         MAC_RIGHTBRACKET_KEY,  // (221)
1950                         MAC_APOSTROPHE_KEY,  // (222)
1951                         0xffff,  // (223)
1952                         0xffff,  // (224)
1953                         0xffff,  // (225)
1954                         0xffff,  // (226)
1955                         0xffff,  // (227)
1956                         0xffff,  // (228)
1957                         0xffff,  // (229)
1958                         0xffff,  // (230)
1959                         0xffff,  // (231)
1960                         0xffff,  // (232)
1961                         0xffff,  // (233)
1962                         0xffff,  // (234)
1963                         0xffff,  // (235)
1964                         0xffff,  // (236)
1965                         0xffff,  // (237)
1966                         0xffff,  // (238)
1967                         0xffff,  // (239)
1968                         0xffff,  // (240)
1969                         0xffff,  // (241)
1970                         0xffff,  // (242)
1971                         0xffff,  // (243)
1972                         0xffff,  // (244)
1973                         0xffff,  // (245)
1974                         0xffff,  // (246)
1975                         0xffff,  // (247)
1976                         0xffff,  // (248)
1977                         0xffff,  // (249)
1978                         0xffff,  // (250)
1979                         0xffff,  // (251)
1980                         0xffff,  // (252)
1981                         0xffff,  // (253)
1982                         0xffff,  // (254)
1983                         0xffff,  // (255)
1984         };
1985
1986         void ClipMouseToWindow(HWND window)
1987         {
1988                 RECT wRect;
1989
1990                 GetClientRect(window, &wRect);
1991
1992                 ClientToScreen(window, (LPPOINT)&wRect.left);
1993                 ClientToScreen(window, (LPPOINT)&wRect.right);
1994
1995                 ClipCursor(&wRect);
1996
1997                 return;
1998         }
1999
2000         LRESULT FAR PASCAL AppWndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
2001         {
2002                 /* this is where we receive all messages concerning this window
2003                 * we can either process a message or pass it on to the default
2004                 * message handler of windows */
2005
2006                 static PAINTSTRUCT ps;
2007
2008                 switch(msg)
2009                 {
2010                 case WM_ACTIVATE:       // Watch For Window Activate Message
2011                         {
2012                                 // Check Minimization State
2013                                 BOOL iconified = HIWORD(wParam) ? TRUE : FALSE;
2014
2015                                 if (LOWORD(wParam) == WA_INACTIVE)
2016                                 {
2017                                         ClipCursor(NULL);
2018
2019                                         if (fullscreen)
2020                                         {
2021                                                 if( !iconified )
2022                                                 {
2023                                                         // Minimize window
2024                                                         CloseWindow( hWnd );
2025
2026                                                         // The window is now iconified
2027                                                         iconified = GL_TRUE;
2028                                                 }
2029                                         }
2030
2031                                         ShutdownDSp();
2032
2033                                         g_focused=false;                                // Program Is Active
2034                                 }
2035                                 else
2036                                 {
2037                                         SetupDSpFullScreen();
2038
2039                                         if( iconified )
2040                                         {
2041                                                 // Minimize window
2042                                                 OpenIcon( hWnd );
2043
2044                                                 // The window is now iconified
2045                                                 iconified = GL_FALSE;
2046
2047                                                 // Activate window
2048                                                 ShowWindow( hWnd, SW_SHOW );
2049                                                 SetForegroundWindow( hWnd );
2050                                                 SetFocus( hWnd );
2051                                         }
2052
2053                                         ClipMouseToWindow(hWnd);
2054                                         g_focused=true;                 // Program Is No Longer Active
2055                                 }
2056
2057                                 return 0;                                               // Return To The Message Loop
2058                         }
2059
2060                 case WM_KEYDOWN:
2061                 case WM_SYSKEYDOWN:
2062                         {
2063                                 // check for Alt-F4 (exit hotkey)
2064                                 if (wParam == VK_F4)
2065                                 {
2066                                         if (GetKeyState( VK_MENU) & 0x8080)
2067                                         {
2068                                                 gDone = true;
2069                                                 break;
2070                                         }
2071                                 }
2072                                 if (wParam < MAX_WINKEYS)
2073                                 {
2074                                         if (KeyTable[wParam] != 0xffff)
2075                                                 SetKey( KeyTable[wParam]);
2076                                 }
2077                                 return (0);
2078                         }
2079
2080                 case WM_KEYUP:
2081                 case WM_SYSKEYUP:
2082                         {
2083                                 if (wParam < MAX_WINKEYS)
2084                                         if (KeyTable[wParam] != 0xffff)
2085                                                 ClearKey( KeyTable[wParam]);
2086                                 return (0);
2087                         }
2088
2089                 case WM_CHAR:
2090                 case WM_DEADCHAR:
2091                 case WM_SYSCHAR:
2092                 case WM_SYSDEADCHAR:
2093                         return (0);
2094
2095                 case WM_NCLBUTTONDOWN:
2096                 case WM_LBUTTONDOWN:
2097                         {
2098                                 g_button = true;
2099                                 buttons[ 0] = true;
2100                         }
2101                         return (0);
2102
2103                 case WM_NCRBUTTONDOWN:
2104                 case WM_RBUTTONDOWN:
2105                         {
2106                                 buttons[ 1] = true;
2107                         }
2108                         return (0);
2109
2110                 case WM_NCMBUTTONDOWN:
2111                 case WM_MBUTTONDOWN:
2112                         {
2113                                 buttons[ 2] = true;
2114                         }
2115                         return (0);
2116
2117                 case WM_NCLBUTTONUP:
2118                 case WM_LBUTTONUP:
2119                         {
2120                                 g_button = false;
2121                                 buttons[ 0] = false;
2122                         }
2123                         return (0);
2124
2125                 case WM_NCRBUTTONUP:
2126                 case WM_RBUTTONUP:
2127                         {
2128                                 buttons[ 1] = false;
2129                         }
2130                         return (0);
2131
2132                 case WM_NCMBUTTONUP:
2133                 case WM_MBUTTONUP:
2134                         {
2135                                 buttons[ 2] = false;
2136                         }
2137                         return (0);
2138
2139                 case WM_NCLBUTTONDBLCLK:
2140                 case WM_NCRBUTTONDBLCLK:
2141                 case WM_NCMBUTTONDBLCLK:
2142                 case WM_LBUTTONDBLCLK:
2143                         return (0);
2144                 case WM_RBUTTONDBLCLK:
2145                 case WM_MBUTTONDBLCLK:
2146                         return (0);
2147
2148                 case WM_NCMOUSEMOVE:
2149                 case WM_MOUSEMOVE:
2150                         /*                      ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseX = (signed short)(lParam & 0xffff);
2151                         ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseY = (signed short)(lParam >> 16);
2152                         if (g_lastWindow->m_mouseCallbacksEnabled) g_lastWindow->MouseMoveCallback();
2153                         *///                    goto winmessage;
2154                         return (0);
2155
2156                 case WM_SYSCOMMAND:                                             // Intercept System Commands
2157                         {
2158                                 switch (wParam)                                         // Check System Calls
2159                                 {
2160                                 case SC_SCREENSAVE:                             // Screensaver Trying To Start?
2161                                 case SC_MONITORPOWER:                   // Monitor Trying To Enter Powersave?
2162                                         return 0;                                       // Prevent From Happening
2163
2164                                         // User trying to access application menu using ALT?
2165                                 case SC_KEYMENU:
2166                                         return 0;
2167                                 }
2168                         }
2169                         break;
2170
2171                 case WM_MOVE:
2172 //                      {
2173 //                              ReleaseCapture();
2174 //                              ClipMouseToWindow(hWnd);
2175 //                      }
2176                         break;
2177
2178                 case WM_SIZE:
2179                         break;
2180
2181                 case WM_CLOSE:
2182                         {
2183                                 //gDone =  true;
2184                                 //game.tryquit=1;
2185                         }
2186                         //return (0);
2187
2188                 case WM_DESTROY:
2189                         {
2190                                 //ClipCursor(NULL);
2191                                 PostQuitMessage(0);  /* Terminate Application */
2192                         }
2193                         return (0);
2194
2195                 case WM_ERASEBKGND:
2196                         break;
2197
2198                 case WM_PAINT:
2199 //                      BeginPaint( g_windowHandle,&ps);
2200 //                      EndPaint( g_windowHandle,&ps);
2201                         break;
2202
2203                 default:
2204                         break;
2205                 }
2206
2207                 /* We processed the message and there
2208                 * is no processing by Windows necessary */
2209
2210                 /* We didn't process the message so let Windows do it */
2211                 return DefWindowProc(hWnd,msg,wParam,lParam);
2212         }
2213
2214
2215         static BOOL RegisterWindowClasses(HINSTANCE hFirstInstance)
2216         {
2217                 WNDCLASSEX wc;
2218                 memset( &wc, 0, sizeof( wc));
2219
2220                 /* Register the window class. */
2221                 wc.cbSize = sizeof(wc);
2222 #undef style
2223                 wc.style = (CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_OWNDC);  /* Combination of Class Styles */
2224                 wc.lpfnWndProc = AppWndProc;       /* Adress of Window Procedure */
2225                 wc.cbClsExtra = 0;                 /* Extra Bytes allocated for this Class */
2226                 wc.cbWndExtra = 0;                 /* Extra Bytes allocated for each Window */
2227                 wc.hInstance = hFirstInstance;     /* Handle of program instance */
2228                 wc.hIcon = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2229                 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2230                 wc.hbrBackground = NULL;
2231                 wc.lpszMenuName  = NULL;
2232                 wc.lpszClassName = g_wndClassName; /* Name of the Window Class */
2233                 wc.hIconSm = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2234
2235                 if (!RegisterClassEx(&wc)) return FALSE;  /* Register Class failed */
2236
2237                 return TRUE;
2238         }
2239 #endif
2240
2241 #if !USE_SDL
2242         int resolutionID(int width, int height)
2243         {
2244                 int whichres;
2245                 whichres=-1;
2246                 if(width==640 && height==480)whichres=0;
2247                 if(width==800 && height==600)whichres=1;
2248                 if(width==1024 && height==768)whichres=2;
2249                 if(width==1280 && height==1024)whichres=3;
2250                 if(width==1600 && height==1200)whichres=4;
2251                 if(width==840 && height==524)whichres=5;
2252                 if(width==1024 && height==640)whichres=6;
2253                 if(width==1344 && height==840)whichres=7;
2254                 if(width==1920 && height==1200)whichres=8;
2255
2256                 return whichres;
2257         }
2258
2259         int closestResolution(int width, int height)
2260         {
2261                 int whichres;
2262                 whichres=-1;
2263                 if(width>=640 && height>=480)whichres=0;
2264                 if(width>=800 && height>=600)whichres=1;
2265                 if(width>=1024 && height>=768)whichres=2;
2266                 if(width>=1280 && height>=1024)whichres=3;
2267                 if(width>=1600 && height>=1200)whichres=4;
2268                 if(width==840 && height==524)whichres=5;
2269                 if(width==1024 && height==640)whichres=6;
2270                 if(width==1344 && height==840)whichres=7;
2271                 if(width>=1920 && height>=1200)whichres=8;
2272
2273                 return whichres;
2274         }
2275 #endif
2276
2277         bool selectDetail(int & width, int & height, int & bpp, int & detail)
2278         {
2279                 bool res = true;
2280
2281                 // currently with SDL, we just use whatever is requested
2282                 //  and don't care.  --ryan.
2283                 #if !USE_SDL
2284                 int whichres = closestResolution(width, height);
2285
2286                 while (true)
2287                 {
2288                         if(whichres<=0 || whichres>8){
2289                                 whichres = 0;
2290                                 width=640;
2291                                 height=480;
2292                         }
2293                         if(whichres==1){
2294                                 width=800;
2295                                 height=600;
2296                         }
2297                         if(whichres==2){
2298                                 width=1024;
2299                                 height=768;
2300                         }
2301                         if(whichres==3){
2302                                 width=1280;
2303                                 height=1024;
2304                         }
2305                         if(whichres==4){
2306                                 width=1600;
2307                                 height=1200;
2308                         }
2309                         if(whichres==5){
2310                                 width=840;
2311                                 height=524;
2312                         }
2313                         if(whichres==6){
2314                                 width=1024;
2315                                 height=640;
2316                         }
2317                         if(whichres==7){
2318                                 width=1344;
2319                                 height=840;
2320                         }
2321                         if(whichres==8){
2322                                 width=1920;
2323                                 height=1200;
2324                         }
2325
2326                         if ((detail != 0) && (resolutionDepths[whichres][1] != 0))
2327                         {
2328                                 break;
2329                         }
2330                         else if ((detail == 0) && (resolutionDepths[whichres][0] != 0))
2331                         {
2332                                 break;
2333                         }
2334                         else if ((detail != 0) && (resolutionDepths[whichres][0] != 0))
2335                         {
2336                                 res = false;
2337                                 detail = 0;
2338                                 break;
2339                         }
2340                         else
2341
2342             if (0 == whichres)
2343                         {
2344                                 break;
2345                         }
2346
2347                         --whichres;
2348                 }
2349
2350                 bpp = resolutionDepths[whichres][(detail != 0)];
2351                 #endif
2352
2353                 return res;
2354         }
2355
2356     #ifdef WIN32
2357         int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
2358         {
2359                 int argc = 0;
2360                 LPWSTR * cl = CommandLineToArgvW(GetCommandLineW(), &argc);
2361                 if (argc > 1)
2362                 {
2363                         if (0 == _wcsicmp(cl[1], L"-windowed"))
2364                         {
2365                                 fullscreen = false;
2366                         }
2367                 }
2368
2369                 memset( &g_theKeys, 0, sizeof( KeyMap));
2370
2371                 unsigned int i = 0;
2372                 DEVMODE mode;
2373                 memset(&mode, 0, sizeof(mode));
2374                 mode.dmSize = sizeof(mode);
2375                 while (EnumDisplaySettings(NULL, i++, &mode))
2376                 {
2377                         if (mode.dmBitsPerPel < 16)
2378                         {
2379                                 continue;
2380                         }
2381
2382                         int res = resolutionID(mode.dmPelsWidth, mode.dmPelsHeight);
2383
2384                         if (res > -1 && res < 8)
2385                         {
2386                                 if (DISP_CHANGE_SUCCESSFUL != ChangeDisplaySettings(&mode, CDS_TEST))
2387                                 {
2388                                         continue;
2389                                 }
2390
2391                                 switch(mode.dmBitsPerPel)
2392                                 {
2393                                 case 32:
2394                                 case 24:
2395                                         resolutionDepths[res][1] = mode.dmBitsPerPel;
2396                                         break;
2397                                 case 16:
2398                                         resolutionDepths[res][0] = mode.dmBitsPerPel;
2399                                         break;
2400                                 }
2401                         }
2402                 }
2403
2404                 /* if there is no Instance of our program in memory then register the window class */
2405                 if (hPrevInstance == NULL && !RegisterWindowClasses(hInstance))
2406                         return FALSE;  /* registration failed! */
2407
2408                 g_appInstance=hInstance;
2409
2410                 main(0, NULL);
2411
2412                 UnregisterClass( g_wndClassName, hInstance);
2413
2414                 return TRUE;
2415
2416         }
2417     #endif
2418
2419         extern int channels[100];
2420         extern FSOUND_SAMPLE * samp[100];
2421         extern FSOUND_STREAM * strm[20];
2422
2423         extern "C" void PlaySoundEx(int chan, FSOUND_SAMPLE *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2424         {
2425                 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2426                 if (currSample && currSample == samp[chan])
2427                 {
2428                         if (FSOUND_GetPaused(channels[chan]))
2429                         {
2430                                 FSOUND_StopSound(channels[chan]);
2431                                 channels[chan] = FSOUND_FREE;
2432                         }
2433                         else if (FSOUND_IsPlaying(channels[chan]))
2434                         {
2435                                 int loop_mode = FSOUND_GetLoopMode(channels[chan]);
2436                                 if (loop_mode & FSOUND_LOOP_OFF)
2437                                 {
2438                                         channels[chan] = FSOUND_FREE;
2439                                 }
2440                         }
2441                 }
2442                 else
2443                 {
2444                         channels[chan] = FSOUND_FREE;
2445                 }
2446
2447                 channels[chan] = FSOUND_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
2448                 if (channels[chan] < 0)
2449                 {
2450                         channels[chan] = FSOUND_PlaySoundEx(FSOUND_FREE, sptr, dsp, startpaused);
2451                 }
2452         }
2453
2454         extern "C" void PlayStreamEx(int chan, FSOUND_STREAM *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2455         {
2456                 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2457                 if (currSample && currSample == FSOUND_Stream_GetSample(sptr))
2458                 {
2459                                 FSOUND_StopSound(channels[chan]);
2460                                 FSOUND_Stream_Stop(sptr);
2461                 }
2462                 else
2463                 {
2464                         FSOUND_Stream_Stop(sptr);
2465                         channels[chan] = FSOUND_FREE;
2466                 }
2467
2468                 channels[chan] = FSOUND_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
2469                 if (channels[chan] < 0)
2470                 {
2471                         channels[chan] = FSOUND_Stream_PlayEx(FSOUND_FREE, sptr, dsp, startpaused);
2472                 }
2473         }
2474
2475         bool LoadImage(const char * fname, TGAImageRec & tex)
2476         {
2477                 bool res = true;
2478
2479                 if ( tex.data == NULL )
2480                 {
2481                         return false;
2482                 }
2483
2484         #if USE_DEVIL
2485                 ILstring f = strdup(ConvertFileName(fname));
2486                 if (!f)
2487                 {
2488                         return false;
2489                 }
2490
2491                 ILuint iid=0;
2492                 ilGenImages(1, &iid);
2493                 ilBindImage(iid);
2494                 if (ilLoadImage(f))
2495                 {
2496                         //iluFlipImage();
2497                         tex.sizeX = ilGetInteger(IL_IMAGE_WIDTH);
2498                         tex.sizeY = ilGetInteger(IL_IMAGE_HEIGHT);
2499                         tex.bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
2500                         ILuint Bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL),
2501                                 imageSize = tex.sizeX * tex.sizeY * Bpp;
2502                         ILubyte *Data = ilGetData();
2503                         memcpy(tex.data, Data, imageSize);
2504
2505                         // Truvision Targa files are stored as BGR colors
2506                         // We want RGB so Blue and Red bytes are switched
2507                         if (IL_TGA == ilGetInteger(IL_IMAGE_FORMAT))
2508                         {
2509                                 // Loop Through The Image Data
2510                                 for (GLuint i = 0; i < int(imageSize); i += Bpp)
2511                                 {
2512                                         // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
2513                                         GLbyte temp;                                            // Temporary Variable
2514                                         temp = tex.data[i];                                     // Temporarily Store The Value At Image Data 'i'
2515                                         tex.data[i] = tex.data[i + 2];          // Set The 1st Byte To The Value Of The 3rd Byte
2516                                         tex.data[i + 2] = temp;                         // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
2517                                 }
2518                         }
2519                 }
2520                 else
2521                 {
2522                         res = false;
2523                 }
2524                 ilDeleteImages(1, &iid);
2525 /*
2526                 if (tid)
2527                 {
2528                         GLuint texid = ilutGLLoadImage(f);
2529                         *tid = texid;
2530                 }
2531                 else if (mip)
2532                 {
2533                         ilutGLBuildMipmaps()
2534                 }
2535                 else
2536                 {
2537                         ilutGLTexImage(0);
2538                 }
2539 */
2540                 free(f);
2541         #else
2542         res = load_image(fname, tex);
2543         //if (!res) printf("failed to load %s\n", fname);
2544         #endif
2545
2546                 return res;
2547         }
2548
2549         void ScreenShot(const char * fname)
2550         {
2551         #if USE_DEVIL
2552                 ILstring f = strdup(fname);
2553                 if (!f)
2554                 {
2555                         return;
2556                 }
2557
2558                 ILuint iid;
2559                 ilGenImages(1, &iid);
2560                 ilBindImage(iid);
2561                 if (ilutGLScreen())
2562                 {
2563                         ilSaveImage(f);
2564                 }
2565                 ilDeleteImages(1, &iid);
2566
2567                 free(f);
2568         #else
2569         save_image(fname);
2570         #endif
2571         }
2572
2573
2574 #if !USE_DEVIL
2575 static bool load_image(const char *file_name, TGAImageRec &tex)
2576 {
2577     char *ptr = strrchr((char *)file_name, '.');
2578     if (ptr)
2579     {
2580         if (strcasecmp(ptr+1, "png") == 0)
2581             return load_png(file_name, tex);
2582         else if (strcasecmp(ptr+1, "jpg") == 0)
2583             return load_jpg(file_name, tex);
2584     }
2585
2586     STUBBED("Unsupported image type");
2587     return false;
2588 }
2589
2590
2591 struct my_error_mgr {
2592   struct jpeg_error_mgr pub;    /* "public" fields */
2593   jmp_buf setjmp_buffer;        /* for return to caller */
2594 };
2595 typedef struct my_error_mgr * my_error_ptr;
2596
2597
2598 static void my_error_exit(j_common_ptr cinfo)
2599 {
2600         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
2601         longjmp(err->setjmp_buffer, 1);
2602 }
2603
2604 /* stolen from public domain example.c code in libjpg distribution. */
2605 static bool load_jpg(const char *file_name, TGAImageRec &tex)
2606 {
2607     struct jpeg_decompress_struct cinfo;
2608     struct my_error_mgr jerr;
2609     JSAMPROW buffer[1];         /* Output row buffer */
2610     int row_stride;             /* physical row width in output buffer */
2611     FILE *infile = fopen(file_name, "rb");
2612
2613     if (infile == NULL)
2614         return false;
2615
2616     cinfo.err = jpeg_std_error(&jerr.pub);
2617     jerr.pub.error_exit = my_error_exit;
2618     if (setjmp(jerr.setjmp_buffer)) {
2619         jpeg_destroy_decompress(&cinfo);
2620         fclose(infile);
2621         return false;
2622     }
2623
2624     jpeg_create_decompress(&cinfo);
2625     jpeg_stdio_src(&cinfo, infile);
2626     (void) jpeg_read_header(&cinfo, TRUE);
2627
2628     cinfo.out_color_space = JCS_RGB;
2629     cinfo.quantize_colors = 0;
2630     (void) jpeg_calc_output_dimensions(&cinfo);
2631     (void) jpeg_start_decompress(&cinfo);
2632
2633     row_stride = cinfo.output_width * cinfo.output_components;
2634     tex.sizeX = cinfo.output_width;
2635     tex.sizeY = cinfo.output_height;
2636     tex.bpp = 24;
2637
2638     while (cinfo.output_scanline < cinfo.output_height) {
2639         buffer[0] = (JSAMPROW)(char *)tex.data +
2640                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
2641         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
2642     }
2643
2644     (void) jpeg_finish_decompress(&cinfo);
2645     jpeg_destroy_decompress(&cinfo);
2646     fclose(infile);
2647
2648     return true;
2649 }
2650
2651
2652 /* stolen from public domain example.c code in libpng distribution. */
2653 static bool load_png(const char *file_name, TGAImageRec &tex)
2654 {
2655     bool hasalpha = false;
2656     png_structp png_ptr = NULL;
2657     png_infop info_ptr = NULL;
2658     png_uint_32 width, height;
2659     int bit_depth, color_type, interlace_type;
2660     png_byte **rows = NULL;
2661     bool retval = false;
2662     png_byte **row_pointers = NULL;
2663     FILE *fp = fopen(file_name, "rb");
2664
2665     if (fp == NULL)
2666         return(NULL);
2667
2668     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2669     if (png_ptr == NULL)
2670         goto png_done;
2671
2672     info_ptr = png_create_info_struct(png_ptr);
2673     if (info_ptr == NULL)
2674         goto png_done;
2675
2676     if (setjmp(png_jmpbuf(png_ptr)))
2677         goto png_done;
2678
2679     png_init_io(png_ptr, fp);
2680     png_read_png(png_ptr, info_ptr,
2681                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
2682                  NULL);
2683     png_get_IHDR(png_ptr, info_ptr, &width, &height,
2684                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
2685
2686     if (bit_depth != 8)  // transform SHOULD handle this...
2687         goto png_done;
2688
2689     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
2690         goto png_done;
2691
2692     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
2693         goto png_done;
2694
2695     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
2696     row_pointers = png_get_rows(png_ptr, info_ptr);
2697     if (!row_pointers)
2698         goto png_done;
2699
2700     if (!hasalpha)
2701     {
2702         png_byte *dst = tex.data;
2703         for (int i = height-1; i >= 0; i--)
2704         {
2705             png_byte *src = row_pointers[i];
2706             for (int j = 0; j < width; j++)
2707             {
2708                 dst[0] = src[0];
2709                 dst[1] = src[1];
2710                 dst[2] = src[2];
2711                 dst[3] = 0xFF;
2712                 src += 3;
2713                 dst += 4;
2714             }
2715         }
2716     }
2717
2718     else
2719     {
2720         png_byte *dst = tex.data;
2721         int pitch = width * 4;
2722         for (int i = height-1; i >= 0; i--, dst += pitch)
2723             memcpy(dst, row_pointers[i], pitch);
2724     }
2725
2726     tex.sizeX = width;
2727     tex.sizeY = height;
2728     tex.bpp = 32;
2729     retval = true;
2730
2731 png_done:
2732     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
2733     if (fp)
2734         fclose(fp);
2735     return (retval);
2736 }
2737
2738
2739 static bool save_image(const char *file_name)
2740 {
2741     char *ptr = strrchr((char *)file_name, '.');
2742     if (ptr)
2743     {
2744         if (strcasecmp(ptr+1, "png") == 0)
2745             return save_png(file_name);
2746     }
2747
2748     STUBBED("Unsupported image type");
2749     return false;
2750 }
2751
2752
2753 static bool save_png(const char *file_name)
2754 {
2755     FILE *fp = NULL;
2756     png_structp png_ptr = NULL;
2757     png_infop info_ptr = NULL;
2758     bool retval = false;
2759
2760     fp = fopen(file_name, "wb");
2761     if (fp == NULL)
2762         return false;
2763
2764     png_bytep *row_pointers = new png_bytep[kContextHeight];
2765     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
2766     if ((!screenshot) || (!row_pointers))
2767         goto save_png_done;
2768
2769     glGetError();
2770     glReadPixels(0, 0, kContextWidth, kContextHeight,
2771                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
2772     if (glGetError() != GL_NO_ERROR)
2773         goto save_png_done;
2774
2775     for (int i = 0; i < kContextHeight; i++)
2776         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
2777
2778     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2779     if (png_ptr == NULL)
2780         goto save_png_done;
2781
2782     info_ptr = png_create_info_struct(png_ptr);
2783     if (info_ptr == NULL)
2784         goto save_png_done;
2785
2786     if (setjmp(png_jmpbuf(png_ptr)))
2787         goto save_png_done;
2788
2789     png_init_io(png_ptr, fp);
2790
2791     if (setjmp(png_jmpbuf(png_ptr)))
2792         goto save_png_done;
2793
2794     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
2795                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
2796                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2797
2798     png_write_info(png_ptr, info_ptr);
2799
2800     if (setjmp(png_jmpbuf(png_ptr)))
2801         goto save_png_done;
2802
2803         png_write_image(png_ptr, row_pointers);
2804
2805         if (setjmp(png_jmpbuf(png_ptr)))
2806         goto save_png_done;
2807
2808     png_write_end(png_ptr, NULL);
2809     retval = true;
2810
2811 save_png_done:
2812     png_destroy_write_struct(&png_ptr, &info_ptr);
2813     delete[] screenshot;
2814     delete[] row_pointers;
2815     if (fp)
2816         fclose(fp);
2817     if (!retval)
2818         unlink(ConvertFileName(file_name));
2819     return retval;
2820 }
2821
2822 #endif
2823