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