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