2 Copyright (C) 2003, 2010 - Wolfire Games
3 Copyright (C) 2010-2016 - Lugaru contributors (see AUTHORS file)
5 This file is part of Lugaru.
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.
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.
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/>.
23 #include "Audio/openal_wrapper.hpp"
24 #include "Graphic/gamegl.hpp"
25 #include "MacCompatibility.hpp"
26 #include "User/Settings.hpp"
41 #include "win-res/resource.hpp"
44 extern float multiplier;
45 extern float realmultiplier;
47 extern bool cellophane;
48 extern float texdetail;
51 extern bool stillloading;
54 extern float slomospeed;
55 extern float slomofreq;
57 extern int difficulty;
59 extern SDL_Window *sdlwindow;
63 set<pair<int,int>> resolutions;
65 // statics/globals (internal only) ------------------------------------------
72 //-----------------------------------------------------------------------------------------------------------------------
78 glClear( GL_COLOR_BUFFER_BIT );
82 glDisable( GL_ALPHA_TEST);
84 glDisable( GL_DEPTH_TEST);
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);
100 // set initial rendering states
101 glShadeModel( GL_SMOOTH);
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);
116 if ( CanInitStereo(stereomode) ) {
117 InitStereo(stereomode);
119 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
120 stereomode = stereoNone;
124 void toggleFullscreen()
126 fullscreen = !fullscreen;
127 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
128 if (flags & SDL_WINDOW_FULLSCREEN) {
129 flags &= ~SDL_WINDOW_FULLSCREEN;
131 flags |= SDL_WINDOW_FULLSCREEN;
133 SDL_SetWindowFullscreen(sdlwindow, flags);
136 SDL_bool sdlEventProc(const SDL_Event &e)
142 case SDL_WINDOWEVENT:
143 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
148 case SDL_MOUSEMOTION:
149 deltah += e.motion.xrel;
150 deltav += e.motion.yrel;
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) ) {
169 // --------------------------------------------------------------------------
171 static Point gMidPoint;
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());
189 if (!LoadSettings()) {
190 fprintf(stderr, "Failed to load config, creating default\n");
194 if (SDL_GL_LoadLibrary(NULL) == -1) {
195 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
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)
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);
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);
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);
227 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
228 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
230 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
231 if (commandLineOptions[FULLSCREEN]) {
232 fullscreen = commandLineOptions[FULLSCREEN].last()->type();
235 sdlflags |= SDL_WINDOW_FULLSCREEN;
237 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
238 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
241 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
242 kContextWidth, kContextHeight, sdlflags);
245 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
246 fprintf(stderr, "forcing 640x480...\n");
248 kContextHeight = 480;
249 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
250 kContextWidth, kContextHeight, sdlflags);
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);
259 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
265 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
267 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
272 SDL_GL_MakeCurrent(sdlwindow, glctx);
275 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
277 fprintf(stderr, "Failed to get a double-buffered context.\n");
282 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
283 SDL_GL_SetSwapInterval(1);
286 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
287 SDL_SetRelativeMouseMode(SDL_TRUE);
292 GLint width = kContextWidth;
293 GLint height = kContextHeight;
294 gMidPoint.h = width / 2;
295 gMidPoint.v = height / 2;
297 screenheight = height;
300 newscreenwidth = screenwidth;
301 newscreenheight = screenheight;
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);
315 static void DoMouse()
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;
325 else if (mousecoordh >= kContextWidth)
326 mousecoordh = kContextWidth - 1;
329 else if (mousecoordv >= kContextHeight)
330 mousecoordv = kContextHeight - 1;
335 void DoFrameRate (int update)
337 static long frames = 0;
339 static AbsoluteTime time = {0, 0};
340 static AbsoluteTime frametime = {0, 0};
341 AbsoluteTime currTime = UpTime ();
342 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
344 if (0 > deltaTime) // if negative microseconds
345 deltaTime /= -1000000.0;
346 else // else milliseconds
349 multiplier = deltaTime;
350 if (multiplier < .001)
355 frametime = currTime; // reset for next time interval
357 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
359 if (0 > deltaTime) // if negative microseconds
360 deltaTime /= -1000000.0;
361 else // else milliseconds
364 if (0.001 <= deltaTime) { // has update interval passed
366 time = currTime; // reset for next time interval
375 static float sps = 200;
377 static float oldmult;
383 fps = 1 / multiplier;
385 count = multiplier * sps;
389 realmultiplier = multiplier;
390 multiplier *= gamespeed;
397 multiplier *= .00001;
398 if (slomo && !mainmenu)
399 multiplier *= slomospeed;
400 oldmult = multiplier;
401 multiplier /= (float)count;
407 for (int i = 0; i < count; i++) {
410 multiplier = oldmult;
413 /* - Debug code to test how many channels were active on average per frame
414 static long frames = 0;
416 static AbsoluteTime start = {0,0};
417 AbsoluteTime currTime = UpTime ();
418 static int num_channels = 0;
420 num_channels += OPENAL_GetChannelsPlaying();
421 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
423 if (0 > deltaTime) // if negative microseconds
424 deltaTime /= -1000000.0;
425 else // else milliseconds
433 float avg_channels = (float)num_channels / (float)frames;
435 ofstream opstream("log.txt",ios::app);
436 opstream << "Average frame count: ";
438 opstream << " frames - ";
439 opstream << avg_channels;
440 opstream << " per frame.\n";
447 if ( stereomode == stereoNone ) {
448 DrawGLScene(stereoCenter);
450 DrawGLScene(stereoLeft);
451 DrawGLScene(stereoRight);
455 // --------------------------------------------------------------------------
462 delete[] commandLineOptionsBuffer;
467 // --------------------------------------------------------------------------
469 static bool IsFocused()
471 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
477 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
478 static char *findBinaryInPath(const char *bin, char *envr)
480 size_t alloc_size = 0;
487 ptr = strchr(start, ':'); /* find next $PATH separator. */
491 size = strlen(start) + strlen(bin) + 2;
492 if (size > alloc_size) {
493 char *x = (char *) realloc(exe, size);
504 /* build full binary path... */
506 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
510 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
511 strcpy(exe, start); /* i'm lazy. piss off. */
515 start = ptr + 1; /* start points to beginning of next element. */
516 } while (ptr != NULL);
521 return(NULL); /* doesn't exist in path. */
522 } /* findBinaryInPath */
525 char *calcBaseDir(const char *argv0)
527 /* If there isn't a path on argv0, then look through the $PATH for it. */
531 if (strchr(argv0, '/')) {
532 retval = strdup(argv0);
534 *((char *) strrchr(retval, '/')) = '\0';
538 envr = getenv("PATH");
544 retval = findBinaryInPath(argv0, envr);
549 static inline void chdirToAppPath(const char *argv0)
551 char *dir = calcBaseDir(argv0);
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)
571 const option::Descriptor usage[] =
573 {UNKNOWN, 0, "", "", option::Arg::None, "USAGE: lugaru [options]\n\n"
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, OPENAL_OUTPUT_NOSOUND, "", "nosound", option::Arg::None, " --nosound Disable sound." },
581 {SOUND, OPENAL_OUTPUT_ALSA, "", "force-alsa", option::Arg::None, " --force-alsa Force use of ALSA back-end." },
582 {SOUND, OPENAL_OUTPUT_OSS, "", "force-oss", option::Arg::None, " --force-oss Force use of OSS back-end." },
583 {OPENALINFO, 0, "", "openal-info", option::Arg::None, " --openal-info Print info about OpenAL at launch." },
584 {SHOWRESOLUTIONS, 0, "", "showresolutions", option::Arg::None, " --showresolutions List the resolutions found by SDL at launch." },
585 {DEVTOOLS, 0, "d", "devtools", option::Arg::None, " -d, --devtools Enable dev tools: console, level editor and debug info." },
589 option::Option commandLineOptions[commandLineOptionsNumber];
590 option::Option* commandLineOptionsBuffer;
592 int main(int argc, char **argv)
594 argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
595 option::Stats stats(true, usage, argc, argv);
596 if (commandLineOptionsNumber != stats.options_max) {
597 std::cerr << "Found incorrect command line option number" << std::endl;
600 commandLineOptionsBuffer = new option::Option[stats.buffer_max];
601 option::Parser parse(true, usage, argc, argv, commandLineOptions, commandLineOptionsBuffer);
604 delete[] commandLineOptionsBuffer;
608 if (commandLineOptions[HELP]) {
609 option::printUsage(std::cout, usage);
610 delete[] commandLineOptionsBuffer;
614 if (option::Option* opt = commandLineOptions[UNKNOWN]) {
615 std::cerr << "Unknown option: " << opt->name << "\n";
616 option::printUsage(std::cerr, usage);
617 delete[] commandLineOptionsBuffer;
621 // !!! FIXME: we could use a Win32 API for this. --ryan.
623 chdirToAppPath(argv[0]);
635 delete[] commandLineOptionsBuffer;
639 if (commandLineOptions[DEVTOOLS]) {
643 bool gameDone = false;
644 bool gameFocused = true;
646 while (!gameDone && !tryquit) {
650 // check windows messages
657 while ( SDL_PollEvent( &e ) ) {
658 if (!sdlEventProc(e)) {
669 // allow game chance to pause
674 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
686 } catch (const std::exception& error) {
689 std::string e = "Caught exception: ";
694 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Exception catched", error.what(), NULL);