]> git.jsancho.org Git - lugaru.git/blob - Source/main.cpp
169809ac8d46771b83f16b68d6f16023c92d95ed
[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 "win-res/resource.hpp"
40 #include <shellapi.h>
41 #include <windows.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
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         fprintf(stderr, "Failed to get a double-buffered context.\n");
277         SDL_Quit();
278         return false;
279     }
280
281     if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
282         SDL_GL_SetSwapInterval(1);
283
284     SDL_ShowCursor(0);
285     if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
286         SDL_SetRelativeMouseMode(SDL_TRUE);
287     }
288
289     initGL();
290
291     GLint width = kContextWidth;
292     GLint height = kContextHeight;
293     gMidPoint.h = width / 2;
294     gMidPoint.v = height / 2;
295     screenwidth = width;
296     screenheight = height;
297
298     newdetail = detail;
299     newscreenwidth = screenwidth;
300     newscreenheight = screenheight;
301
302     /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
303     pair<int, int> startresolution(width, height);
304     if (resolutions.find(startresolution) == resolutions.end()) {
305         resolutions.insert(startresolution);
306     }
307
308     InitGame();
309
310     return true;
311 }
312
313 static void DoMouse()
314 {
315
316     if (mainmenu || ((abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000))) {
317         deltah *= usermousesensitivity;
318         deltav *= usermousesensitivity;
319         mousecoordh += deltah;
320         mousecoordv += deltav;
321         if (mousecoordh < 0)
322             mousecoordh = 0;
323         else if (mousecoordh >= kContextWidth)
324             mousecoordh = kContextWidth - 1;
325         if (mousecoordv < 0)
326             mousecoordv = 0;
327         else if (mousecoordv >= kContextHeight)
328             mousecoordv = kContextHeight - 1;
329     }
330 }
331
332 void DoFrameRate(int update)
333 {
334     static long frames = 0;
335
336     static AbsoluteTime time = { 0, 0 };
337     static AbsoluteTime frametime = { 0, 0 };
338     AbsoluteTime currTime = UpTime();
339     double deltaTime = (float)AbsoluteDeltaToDuration(currTime, frametime);
340
341     if (0 > deltaTime) // if negative microseconds
342         deltaTime /= -1000000.0;
343     else // else milliseconds
344         deltaTime /= 1000.0;
345
346     multiplier = deltaTime;
347     if (multiplier < .001)
348         multiplier = .001;
349     if (multiplier > 10)
350         multiplier = 10;
351     if (update)
352         frametime = currTime; // reset for next time interval
353
354     deltaTime = (float)AbsoluteDeltaToDuration(currTime, time);
355
356     if (0 > deltaTime) // if negative microseconds
357         deltaTime /= -1000000.0;
358     else // else milliseconds
359         deltaTime /= 1000.0;
360     frames++;
361     if (0.001 <= deltaTime) { // has update interval passed
362         if (update) {
363             time = currTime; // reset for next time interval
364             frames = 0;
365         }
366     }
367 }
368
369 void DoUpdate()
370 {
371     static float sps = 200;
372     static int count;
373     static float oldmult;
374
375     DoFrameRate(1);
376     if (multiplier > .6)
377         multiplier = .6;
378
379     fps = 1 / multiplier;
380
381     count = multiplier * sps;
382     if (count < 2)
383         count = 2;
384
385     realmultiplier = multiplier;
386     multiplier *= gamespeed;
387     if (difficulty == 1)
388         multiplier *= .9;
389     if (difficulty == 0)
390         multiplier *= .8;
391
392     if (loading == 4)
393         multiplier *= .00001;
394     if (slomo && !mainmenu)
395         multiplier *= slomospeed;
396     oldmult = multiplier;
397     multiplier /= (float)count;
398
399     DoMouse();
400
401     TickOnce();
402
403     for (int i = 0; i < count; i++) {
404         Tick();
405     }
406     multiplier = oldmult;
407
408     TickOnceAfter();
409     /* - Debug code to test how many channels were active on average per frame
410         static long frames = 0;
411
412         static AbsoluteTime start = {0,0};
413         AbsoluteTime currTime = UpTime ();
414         static int num_channels = 0;
415
416         num_channels += OPENAL_GetChannelsPlaying();
417         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
418
419         if (0 > deltaTime)  // if negative microseconds
420             deltaTime /= -1000000.0;
421         else                // else milliseconds
422             deltaTime /= 1000.0;
423
424         ++frames;
425
426         if (deltaTime >= 1)
427         {
428             start = currTime;
429             float avg_channels = (float)num_channels / (float)frames;
430
431             ofstream opstream("log.txt",ios::app);
432             opstream << "Average frame count: ";
433             opstream << frames;
434             opstream << " frames - ";
435             opstream << avg_channels;
436             opstream << " per frame.\n";
437             opstream.close();
438
439             frames = 0;
440             num_channels = 0;
441         }
442     */
443     if (stereomode == stereoNone) {
444         DrawGLScene(stereoCenter);
445     } else {
446         DrawGLScene(stereoLeft);
447         DrawGLScene(stereoRight);
448     }
449 }
450
451 // --------------------------------------------------------------------------
452
453 void CleanUp(void)
454 {
455     LOGFUNC;
456
457     delete[] commandLineOptionsBuffer;
458
459     SDL_Quit();
460 }
461
462 // --------------------------------------------------------------------------
463
464 static bool IsFocused()
465 {
466     return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
467 }
468
469 #ifndef WIN32
470 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
471 static char* findBinaryInPath(const char* bin, char* envr)
472 {
473     size_t alloc_size = 0;
474     char* exe = NULL;
475     char* start = envr;
476     char* ptr;
477
478     do {
479         size_t size;
480         ptr = strchr(start, ':'); /* find next $PATH separator. */
481         if (ptr)
482             *ptr = '\0';
483
484         size = strlen(start) + strlen(bin) + 2;
485         if (size > alloc_size) {
486             char* x = (char*)realloc(exe, size);
487             if (x == NULL) {
488                 if (exe != NULL)
489                     free(exe);
490                 return (NULL);
491             } /* if */
492
493             alloc_size = size;
494             exe = x;
495         } /* if */
496
497         /* build full binary path... */
498         strcpy(exe, start);
499         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
500             strcat(exe, "/");
501         strcat(exe, bin);
502
503         if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
504             strcpy(exe, start);       /* i'm lazy. piss off. */
505             return (exe);
506         } /* if */
507
508         start = ptr + 1; /* start points to beginning of next element. */
509     } while (ptr != NULL);
510
511     if (exe != NULL)
512         free(exe);
513
514     return (NULL); /* doesn't exist in path. */
515 } /* findBinaryInPath */
516
517 char* calcBaseDir(const char* argv0)
518 {
519     /* If there isn't a path on argv0, then look through the $PATH for it. */
520     char* retval;
521     char* envr;
522
523     if (strchr(argv0, '/')) {
524         retval = strdup(argv0);
525         if (retval)
526             *((char*)strrchr(retval, '/')) = '\0';
527         return (retval);
528     }
529
530     envr = getenv("PATH");
531     if (!envr)
532         return NULL;
533     envr = strdup(envr);
534     if (!envr)
535         return NULL;
536     retval = findBinaryInPath(argv0, envr);
537     free(envr);
538     return (retval);
539 }
540
541 static inline void chdirToAppPath(const char* argv0)
542 {
543     char* dir = calcBaseDir(argv0);
544     if (dir) {
545 #if (defined(__APPLE__) && defined(__MACH__))
546         // Chop off /Contents/MacOS if it's at the end of the string, so we
547         //  land in the base of the app bundle.
548         const size_t len = strlen(dir);
549         const char* bundledirs = "/Contents/MacOS";
550         const size_t bundledirslen = strlen(bundledirs);
551         if (len > bundledirslen) {
552             char* ptr = (dir + len) - bundledirslen;
553             if (strcasecmp(ptr, bundledirs) == 0)
554                 *ptr = '\0';
555         }
556 #endif
557         chdir(dir);
558         free(dir);
559     }
560 }
561 #endif
562
563 const option::Descriptor usage[] =
564     {
565       { UNKNOWN, 0, "", "", option::Arg::None, "USAGE: lugaru [options]\n\n"
566                                                "Options:" },
567       { HELP, 0, "h", "help", option::Arg::None, " -h, --help        Print usage and exit." },
568       { FULLSCREEN, 1, "f", "fullscreen", option::Arg::None, " -f, --fullscreen  Start the game in fullscreen mode." },
569       { FULLSCREEN, 0, "w", "windowed", option::Arg::None, " -w, --windowed    Start the game in windowed mode (default)." },
570       { NOMOUSEGRAB, 1, "", "nomousegrab", option::Arg::None, " --nomousegrab     Disable mousegrab." },
571       { NOMOUSEGRAB, 0, "", "mousegrab", option::Arg::None, " --mousegrab       Enable mousegrab (default)." },
572       { SOUND, 1, "", "nosound", option::Arg::None, " --nosound         Disable sound." },
573       { OPENALINFO, 0, "", "openal-info", option::Arg::None, " --openal-info     Print info about OpenAL at launch." },
574       { SHOWRESOLUTIONS, 0, "", "showresolutions", option::Arg::None, " --showresolutions List the resolutions found by SDL at launch." },
575       { DEVTOOLS, 0, "d", "devtools", option::Arg::None, " -d, --devtools    Enable dev tools: console, level editor and debug info." },
576       { 0, 0, 0, 0, 0, 0 }
577     };
578
579 option::Option commandLineOptions[commandLineOptionsNumber];
580 option::Option* commandLineOptionsBuffer;
581
582 int main(int argc, char** argv)
583 {
584     argc -= (argc > 0);
585     argv += (argc > 0); // skip program name argv[0] if present
586     option::Stats stats(true, usage, argc, argv);
587     if (commandLineOptionsNumber != stats.options_max) {
588         std::cerr << "Found incorrect command line option number" << std::endl;
589         return 1;
590     }
591     commandLineOptionsBuffer = new option::Option[stats.buffer_max];
592     option::Parser parse(true, usage, argc, argv, commandLineOptions, commandLineOptionsBuffer);
593
594     if (parse.error()) {
595         delete[] commandLineOptionsBuffer;
596         return 1;
597     }
598
599     if (commandLineOptions[HELP]) {
600         option::printUsage(std::cout, usage);
601         delete[] commandLineOptionsBuffer;
602         return 0;
603     }
604
605     if (option::Option* opt = commandLineOptions[UNKNOWN]) {
606         std::cerr << "Unknown option: " << opt->name << "\n";
607         option::printUsage(std::cerr, usage);
608         delete[] commandLineOptionsBuffer;
609         return 1;
610     }
611
612 // !!! FIXME: we could use a Win32 API for this.  --ryan.
613 #ifndef WIN32
614     chdirToAppPath(argv[0]);
615 #endif
616
617     LOGFUNC;
618
619 #ifdef NDEBUG
620     try {
621 #endif
622         {
623             newGame();
624
625             if (!SetUp()) {
626                 delete[] commandLineOptionsBuffer;
627                 return 42;
628             }
629
630             if (commandLineOptions[DEVTOOLS]) {
631                 devtools = true;
632             }
633
634             bool gameDone = false;
635             bool gameFocused = true;
636
637             while (!gameDone && !tryquit) {
638                 if (IsFocused()) {
639                     gameFocused = true;
640
641                     // check windows messages
642
643                     deltah = 0;
644                     deltav = 0;
645                     SDL_Event e;
646                     if (!waiting) {
647                         // message pump
648                         while (SDL_PollEvent(&e)) {
649                             if (!sdlEventProc(e)) {
650                                 gameDone = true;
651                                 break;
652                             }
653                         }
654                     }
655
656                     // game
657                     DoUpdate();
658                 } else {
659                     if (gameFocused) {
660                         // allow game chance to pause
661                         gameFocused = false;
662                         DoUpdate();
663                     }
664
665                     // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
666                     SDL_WaitEvent(0);
667                 }
668             }
669
670             deleteGame();
671         }
672
673         CleanUp();
674
675         return 0;
676 #ifdef NDEBUG
677     } catch (const std::exception& error) {
678         CleanUp();
679
680         std::string e = "Caught exception: ";
681         e += error.what();
682
683         LOG(e);
684
685         SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Exception catched", error.what(), NULL);
686
687         return -1;
688     }
689 #endif
690 }