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