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