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