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