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