]> git.jsancho.org Git - lugaru.git/blob - Source/main.cpp
Switch to using «The Lean Mean C++ Option Parser»
[lugaru.git] / Source / main.cpp
1 /*
2 Copyright (C) 2003, 2010 - Wolfire Games
3 Copyright (C) 2010-2016 - Lugaru contributors (see AUTHORS file)
4
5 This file is part of Lugaru.
6
7 Lugaru is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 Lugaru is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Lugaru.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <math.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <fstream>
25 #include <iostream>
26 #include <zlib.h>
27 #include <set>
28 #include "gamegl.h"
29 #include "MacCompatibility.h"
30 #include "Settings.h"
31
32 #include "Game.h"
33
34 using namespace Game;
35
36 #include "openal_wrapper.h"
37
38 #ifdef WIN32
39 #include <windows.h>
40 #include <shellapi.h>
41 #include "win-res/resource.h"
42 #endif
43
44 extern float multiplier;
45 extern float sps;
46 extern float realmultiplier;
47 extern int slomo;
48 extern bool cellophane;
49 extern float texdetail;
50
51 extern bool freeze;
52 extern bool stillloading;
53 extern int mainmenu;
54
55 extern float slomospeed;
56 extern float slomofreq;
57 extern bool visibleloading;
58
59 extern SDL_Window *sdlwindow;
60
61 using namespace std;
62
63 set<pair<int,int>> resolutions;
64
65 // statics/globals (internal only) ------------------------------------------
66
67 #ifdef _MSC_VER
68 #pragma warning(push)
69 #pragma warning(disable: 4273)
70 #endif
71
72 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
73 #define GL_FUNC(ret,fn,params,call,rt) \
74     extern "C" { \
75         static ret (GLAPIENTRY *p##fn) params = NULL; \
76         ret GLAPIENTRY fn params { rt p##fn call; } \
77     }
78 #include "glstubs.h"
79 #undef GL_FUNC
80 #endif // __MINGW32__
81
82 #ifdef _MSC_VER
83 #pragma warning(pop)
84 #endif
85
86 static bool lookup_glsym(const char *funcname, void **func)
87 {
88     *func = SDL_GL_GetProcAddress(funcname);
89     if (*func == NULL) {
90         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
91         return false;
92     }
93     return true;
94 }
95
96 static bool lookup_all_glsyms(void)
97 {
98     bool retval = true;
99 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
100 #define GL_FUNC(ret,fn,params,call,rt) \
101         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
102 #include "glstubs.h"
103 #undef GL_FUNC
104 #endif // __MINGW32__
105     return retval;
106 }
107
108 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
109 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
110 {
111     // no-op.
112 }
113 #endif // __MINGW32__
114
115 #ifdef MessageBox
116 #undef MessageBox
117 #endif
118 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
119
120 // Menu defs
121
122 int kContextWidth;
123 int kContextHeight;
124
125 //-----------------------------------------------------------------------------------------------------------------------
126
127 // OpenGL Drawing
128
129 void initGL()
130 {
131     glClear( GL_COLOR_BUFFER_BIT );
132     swap_gl_buffers();
133
134     // clear all states
135     glDisable( GL_ALPHA_TEST);
136     glDisable( GL_BLEND);
137     glDisable( GL_DEPTH_TEST);
138     glDisable( GL_FOG);
139     glDisable( GL_LIGHTING);
140     glDisable( GL_LOGIC_OP);
141     glDisable( GL_TEXTURE_1D);
142     glDisable( GL_TEXTURE_2D);
143     glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
144     glPixelTransferi( GL_RED_SCALE, 1);
145     glPixelTransferi( GL_RED_BIAS, 0);
146     glPixelTransferi( GL_GREEN_SCALE, 1);
147     glPixelTransferi( GL_GREEN_BIAS, 0);
148     glPixelTransferi( GL_BLUE_SCALE, 1);
149     glPixelTransferi( GL_BLUE_BIAS, 0);
150     glPixelTransferi( GL_ALPHA_SCALE, 1);
151     glPixelTransferi( GL_ALPHA_BIAS, 0);
152
153     // set initial rendering states
154     glShadeModel( GL_SMOOTH);
155     glClearDepth( 1.0f);
156     glDepthFunc( GL_LEQUAL);
157     glDepthMask( GL_TRUE);
158     glEnable( GL_DEPTH_TEST);
159     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
160     glCullFace( GL_FRONT);
161     glEnable( GL_CULL_FACE);
162     glEnable( GL_LIGHTING);
163     glEnable( GL_DITHER);
164     glEnable( GL_COLOR_MATERIAL);
165     glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
166     glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
167     glAlphaFunc( GL_GREATER, 0.5f);
168
169     if ( CanInitStereo(stereomode) ) {
170         InitStereo(stereomode);
171     } else {
172         fprintf(stderr, "Failed to initialize stereo, disabling.\n");
173         stereomode = stereoNone;
174     }
175 }
176
177 void toggleFullscreen()
178 {
179     fullscreen = !fullscreen;
180     Uint32 flags = SDL_GetWindowFlags(sdlwindow);
181     if (flags & SDL_WINDOW_FULLSCREEN) {
182         flags &= ~SDL_WINDOW_FULLSCREEN;
183     } else {
184         flags |= SDL_WINDOW_FULLSCREEN;
185     }
186     SDL_SetWindowFullscreen(sdlwindow, flags);
187 }
188
189 SDL_bool sdlEventProc(const SDL_Event &e)
190 {
191     switch (e.type) {
192         case SDL_QUIT:
193             return SDL_FALSE;
194
195         case SDL_WINDOWEVENT:
196             if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
197                 return SDL_FALSE;
198             }
199         break;
200
201         case SDL_MOUSEMOTION:
202             deltah += e.motion.xrel;
203             deltav += e.motion.yrel;
204         break;
205
206         case SDL_KEYDOWN:
207             if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
208                 (e.key.keysym.mod & KMOD_CTRL)) {
209                 SDL_bool mode = SDL_TRUE;
210                 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
211                     mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
212                 SDL_SetWindowGrab(sdlwindow, mode);
213                 SDL_SetRelativeMouseMode(mode);
214             } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
215                 toggleFullscreen();
216             }
217         break;
218     }
219     return SDL_TRUE;
220 }
221
222 // --------------------------------------------------------------------------
223
224 static Point gMidPoint;
225
226 bool SetUp ()
227 {
228     LOGFUNC;
229
230     cellophane = 0;
231     texdetail = 4;
232     slomospeed = 0.25;
233     slomofreq = 8012;
234
235     DefaultSettings();
236
237     if (!SDL_WasInit(SDL_INIT_VIDEO))
238         if (SDL_Init(SDL_INIT_VIDEO) == -1) {
239             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
240             return false;
241         }
242     if (!LoadSettings()) {
243         fprintf(stderr, "Failed to load config, creating default\n");
244         SaveSettings();
245     }
246     if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
247         kBitsPerPixel = 16;
248     }
249
250     if (SDL_GL_LoadLibrary(NULL) == -1) {
251         fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
252         SDL_Quit();
253         return false;
254     }
255
256     for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
257         for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
258             SDL_DisplayMode mode;
259             if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
260                 continue;
261             if ((mode.w < 640) || (mode.h < 480))
262                 continue;  // sane lower limit.
263             pair<int,int> resolution(mode.w, mode.h);
264             resolutions.insert(resolution);
265         }
266     }
267
268     if (resolutions.empty()) {
269         const std::string error = "No suitable video resolutions found.";
270         cerr << error << endl;
271         SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
272         SDL_Quit();
273         return false;
274     }
275
276     if (commandLineOptions[SHOWRESOLUTIONS]) {
277         printf("Available resolutions:\n");
278         for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
279             printf("  %d x %d\n", (int) resolution->first, (int) resolution->second);
280         }
281     }
282
283     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
284     SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
285
286     Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
287     if (commandLineOptions[FULLSCREEN]) {
288         fullscreen = commandLineOptions[FULLSCREEN].last()->type();
289     }
290     if (fullscreen) {
291         sdlflags |= SDL_WINDOW_FULLSCREEN;
292     }
293     if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
294         sdlflags |= SDL_WINDOW_INPUT_GRABBED;
295     }
296
297     sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
298                                  kContextWidth, kContextHeight, sdlflags);
299
300     if (!sdlwindow) {
301         fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
302         fprintf(stderr, "forcing 640x480...\n");
303         kContextWidth = 640;
304         kContextHeight = 480;
305         sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
306                                      kContextWidth, kContextHeight, sdlflags);
307         if (!sdlwindow) {
308             fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
309             fprintf(stderr, "forcing 640x480 windowed mode...\n");
310             sdlflags &= ~SDL_WINDOW_FULLSCREEN;
311             sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
312                                          kContextWidth, kContextHeight, sdlflags);
313
314             if (!sdlwindow) {
315                 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
316                 return false;
317             }
318         }
319     }
320
321     SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
322     if (!glctx) {
323         fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
324         SDL_Quit();
325         return false;
326     }
327
328     SDL_GL_MakeCurrent(sdlwindow, glctx);
329
330     if (!lookup_all_glsyms()) {
331         fprintf(stderr, "Missing required OpenGL functions.\n");
332         SDL_Quit();
333         return false;
334     }
335
336     int dblbuf = 0;
337     if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
338     {
339         fprintf(stderr, "Failed to get a double-buffered context.\n");
340         SDL_Quit();
341         return false;
342     }
343
344     if (SDL_GL_SetSwapInterval(-1) == -1)  // try swap_tear first.
345         SDL_GL_SetSwapInterval(1);
346
347     SDL_ShowCursor(0);
348     if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
349         SDL_SetRelativeMouseMode(SDL_TRUE);
350     }
351
352     initGL();
353
354     GLint width = kContextWidth;
355     GLint height = kContextHeight;
356     gMidPoint.h = width / 2;
357     gMidPoint.v = height / 2;
358     screenwidth = width;
359     screenheight = height;
360
361     newdetail = detail;
362     newscreenwidth = screenwidth;
363     newscreenheight = screenheight;
364
365     /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
366     pair<int,int> startresolution(width,height);
367     if (resolutions.find(startresolution) == resolutions.end()) {
368         resolutions.insert(startresolution);
369     }
370
371     InitGame();
372
373     return true;
374 }
375
376
377 static void DoMouse()
378 {
379
380     if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
381         deltah *= usermousesensitivity;
382         deltav *= usermousesensitivity;
383         mousecoordh += deltah;
384         mousecoordv += deltav;
385         if (mousecoordh < 0)
386             mousecoordh = 0;
387         else if (mousecoordh >= kContextWidth)
388             mousecoordh = kContextWidth - 1;
389         if (mousecoordv < 0)
390             mousecoordv = 0;
391         else if (mousecoordv >= kContextHeight)
392             mousecoordv = kContextHeight - 1;
393     }
394
395 }
396
397 void DoFrameRate (int update)
398 {
399     static long frames = 0;
400
401     static AbsoluteTime time = {0, 0};
402     static AbsoluteTime frametime = {0, 0};
403     AbsoluteTime currTime = UpTime ();
404     double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
405
406     if (0 > deltaTime) // if negative microseconds
407         deltaTime /= -1000000.0;
408     else // else milliseconds
409         deltaTime /= 1000.0;
410
411     multiplier = deltaTime;
412     if (multiplier < .001)
413         multiplier = .001;
414     if (multiplier > 10)
415         multiplier = 10;
416     if (update)
417         frametime = currTime; // reset for next time interval
418
419     deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
420
421     if (0 > deltaTime) // if negative microseconds
422         deltaTime /= -1000000.0;
423     else // else milliseconds
424         deltaTime /= 1000.0;
425     frames++;
426     if (0.001 <= deltaTime) { // has update interval passed
427         if (update) {
428             time = currTime; // reset for next time interval
429             frames = 0;
430         }
431     }
432 }
433
434
435 void DoUpdate ()
436 {
437     static float sps = 200;
438     static int count;
439     static float oldmult;
440
441     DoFrameRate(1);
442     if (multiplier > .6)
443         multiplier = .6;
444
445     fps = 1 / multiplier;
446
447     count = multiplier * sps;
448     if (count < 2)
449         count = 2;
450
451     realmultiplier = multiplier;
452     multiplier *= gamespeed;
453     if (difficulty == 1)
454         multiplier *= .9;
455     if (difficulty == 0)
456         multiplier *= .8;
457
458     if (loading == 4)
459         multiplier *= .00001;
460     if (slomo && !mainmenu)
461         multiplier *= slomospeed;
462     oldmult = multiplier;
463     multiplier /= (float)count;
464
465     DoMouse();
466
467     TickOnce();
468
469     for (int i = 0; i < count; i++) {
470         Tick();
471     }
472     multiplier = oldmult;
473
474     TickOnceAfter();
475     /* - Debug code to test how many channels were active on average per frame
476         static long frames = 0;
477
478         static AbsoluteTime start = {0,0};
479         AbsoluteTime currTime = UpTime ();
480         static int num_channels = 0;
481
482         num_channels += OPENAL_GetChannelsPlaying();
483         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
484
485         if (0 > deltaTime)  // if negative microseconds
486             deltaTime /= -1000000.0;
487         else                // else milliseconds
488             deltaTime /= 1000.0;
489
490         ++frames;
491
492         if (deltaTime >= 1)
493         {
494             start = currTime;
495             float avg_channels = (float)num_channels / (float)frames;
496
497             ofstream opstream("log.txt",ios::app);
498             opstream << "Average frame count: ";
499             opstream << frames;
500             opstream << " frames - ";
501             opstream << avg_channels;
502             opstream << " per frame.\n";
503             opstream.close();
504
505             frames = 0;
506             num_channels = 0;
507         }
508     */
509     if ( stereomode == stereoNone ) {
510         DrawGLScene(stereoCenter);
511     } else {
512         DrawGLScene(stereoLeft);
513         DrawGLScene(stereoRight);
514     }
515 }
516
517 // --------------------------------------------------------------------------
518
519
520 void CleanUp (void)
521 {
522     LOGFUNC;
523
524     SDL_Quit();
525 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
526 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
527 #include "glstubs.h"
528 #undef GL_FUNC
529     // cheat here...static destructors are calling glDeleteTexture() after
530     //  the context is destroyed and libGL unloaded by SDL_Quit().
531     pglDeleteTextures = glDeleteTextures_doNothing;
532 #endif // __MINGW32__
533
534 }
535
536 // --------------------------------------------------------------------------
537
538 static bool IsFocused()
539 {
540     return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
541 }
542
543
544
545 #ifndef WIN32
546 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
547 static char *findBinaryInPath(const char *bin, char *envr)
548 {
549     size_t alloc_size = 0;
550     char *exe = NULL;
551     char *start = envr;
552     char *ptr;
553
554     do {
555         size_t size;
556         ptr = strchr(start, ':');  /* find next $PATH separator. */
557         if (ptr)
558             *ptr = '\0';
559
560         size = strlen(start) + strlen(bin) + 2;
561         if (size > alloc_size) {
562             char *x = (char *) realloc(exe, size);
563             if (x == NULL) {
564                 if (exe != NULL)
565                     free(exe);
566                 return(NULL);
567             } /* if */
568
569             alloc_size = size;
570             exe = x;
571         } /* if */
572
573         /* build full binary path... */
574         strcpy(exe, start);
575         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
576             strcat(exe, "/");
577         strcat(exe, bin);
578
579         if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
580             strcpy(exe, start);  /* i'm lazy. piss off. */
581             return(exe);
582         } /* if */
583
584         start = ptr + 1;  /* start points to beginning of next element. */
585     } while (ptr != NULL);
586
587     if (exe != NULL)
588         free(exe);
589
590     return(NULL);  /* doesn't exist in path. */
591 } /* findBinaryInPath */
592
593
594 char *calcBaseDir(const char *argv0)
595 {
596     /* If there isn't a path on argv0, then look through the $PATH for it. */
597     char *retval;
598     char *envr;
599
600     if (strchr(argv0, '/')) {
601         retval = strdup(argv0);
602         if (retval)
603             *((char *) strrchr(retval, '/')) = '\0';
604         return(retval);
605     }
606
607     envr = getenv("PATH");
608     if (!envr)
609         return NULL;
610     envr = strdup(envr);
611     if (!envr)
612         return NULL;
613     retval = findBinaryInPath(argv0, envr);
614     free(envr);
615     return(retval);
616 }
617
618 static inline void chdirToAppPath(const char *argv0)
619 {
620     char *dir = calcBaseDir(argv0);
621     if (dir) {
622 #if (defined(__APPLE__) && defined(__MACH__))
623         // Chop off /Contents/MacOS if it's at the end of the string, so we
624         //  land in the base of the app bundle.
625         const size_t len = strlen(dir);
626         const char *bundledirs = "/Contents/MacOS";
627         const size_t bundledirslen = strlen(bundledirs);
628         if (len > bundledirslen) {
629             char *ptr = (dir + len) - bundledirslen;
630             if (strcasecmp(ptr, bundledirs) == 0)
631                 *ptr = '\0';
632         }
633 #endif
634         chdir(dir);
635         free(dir);
636     }
637 }
638 #endif
639
640 const option::Descriptor usage[] =
641 {
642     {UNKNOWN,           0,                      "",     "",                 option::Arg::None,  "USAGE: lugaru [options]\n\n"
643                                                                                                 "Options:" },
644     {HELP,              0,                      "h",    "help",             option::Arg::None,  " -h, --help        Print usage and exit." },
645     {FULLSCREEN,        1,                      "f",    "fullscreen",       option::Arg::None,  " -f, --fullscreen  Start the game in fullscreen mode." },
646     {FULLSCREEN,        0,                      "w",    "windowed",         option::Arg::None,  " -w, --windowed    Start the game in windowed mode (default)." },
647     {NOMOUSEGRAB,       1,                      "",     "nomousegrab",      option::Arg::None,  " --nomousegrab     Disable mousegrab." },
648     {NOMOUSEGRAB,       0,                      "",     "mousegrab",        option::Arg::None,  " --mousegrab       Enable mousegrab (default)." },
649     {SOUND,             OPENAL_OUTPUT_NOSOUND,  "",     "nosound",          option::Arg::None,  " --nosound         Disable sound." },
650     {SOUND,             OPENAL_OUTPUT_ALSA,     "",     "force-alsa",       option::Arg::None,  " --force-alsa      Force use of ALSA back-end." },
651     {SOUND,             OPENAL_OUTPUT_OSS,      "",     "force-oss",        option::Arg::None,  " --force-oss       Force use of OSS back-end." },
652     {OPENALINFO,        0,                      "",     "openal-info",      option::Arg::None,  " --openal-info     Print info about OpenAL at launch." },
653     {SHOWRESOLUTIONS,   0,                      "",     "showresolutions",  option::Arg::None,  " --showresolutions List the resolutions found by SDL at launch." },
654     {0,0,0,0,0,0}
655 };
656
657 option::Option commandLineOptions[commandLineOptionsNumber];
658
659 int main(int argc, char **argv)
660 {
661     argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
662     option::Stats  stats(true, usage, argc, argv);
663     if (commandLineOptionsNumber != stats.options_max) {
664         std::cerr << "Found incorrect command line option number" << std::endl;
665         return 1;
666     }
667     option::Option buffer[stats.buffer_max];
668     option::Parser parse(true, usage, argc, argv, commandLineOptions, buffer);
669
670     if (parse.error()) {
671         return 1;
672     }
673
674     if (commandLineOptions[HELP]) {
675         option::printUsage(std::cout, usage);
676         return 0;
677     }
678
679     if (option::Option* opt = commandLineOptions[UNKNOWN]) {
680         std::cerr << "Unknown option: " << opt->name << "\n";
681         option::printUsage(std::cerr, usage);
682         return 1;
683     }
684
685     // !!! FIXME: we could use a Win32 API for this.  --ryan.
686 #ifndef WIN32
687     chdirToAppPath(argv[0]);
688 #endif
689
690     LOGFUNC;
691
692     try {
693         {
694             newGame();
695
696             if (!SetUp ())
697                 return 42;
698
699             bool gameDone = false;
700             bool gameFocused = true;
701
702             while (!gameDone && !tryquit) {
703                 if (IsFocused()) {
704                     gameFocused = true;
705
706                     // check windows messages
707
708                     deltah = 0;
709                     deltav = 0;
710                     SDL_Event e;
711                     if (!waiting) {
712                         // message pump
713                         while ( SDL_PollEvent( &e ) ) {
714                             if (!sdlEventProc(e)) {
715                                 gameDone = true;
716                                 break;
717                             }
718                         }
719                     }
720
721                     // game
722                     DoUpdate();
723                 } else {
724                     if (gameFocused) {
725                         // allow game chance to pause
726                         gameFocused = false;
727                         DoUpdate();
728                     }
729
730                     // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
731                     SDL_WaitEvent(0);
732                 }
733             }
734
735             deleteGame();
736         }
737
738         CleanUp ();
739
740         return 0;
741     } catch (const std::exception& error) {
742         CleanUp();
743
744         std::string e = "Caught exception: ";
745         e += error.what();
746
747         LOG(e);
748
749         MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
750
751         return -1;
752     }
753 }