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