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