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/>.
29 #include "MacCompatibility.h"
36 #include "openal_wrapper.h"
41 #include "win-res/resource.h"
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;
56 extern bool visibleloading;
58 extern SDL_Window *sdlwindow;
62 set<pair<int,int>> resolutions;
64 // statics/globals (internal only) ------------------------------------------
71 //-----------------------------------------------------------------------------------------------------------------------
77 glClear( GL_COLOR_BUFFER_BIT );
81 glDisable( GL_ALPHA_TEST);
83 glDisable( GL_DEPTH_TEST);
85 glDisable( GL_LIGHTING);
86 glDisable( GL_LOGIC_OP);
87 glDisable( GL_TEXTURE_1D);
88 glDisable( GL_TEXTURE_2D);
89 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
90 glPixelTransferi( GL_RED_SCALE, 1);
91 glPixelTransferi( GL_RED_BIAS, 0);
92 glPixelTransferi( GL_GREEN_SCALE, 1);
93 glPixelTransferi( GL_GREEN_BIAS, 0);
94 glPixelTransferi( GL_BLUE_SCALE, 1);
95 glPixelTransferi( GL_BLUE_BIAS, 0);
96 glPixelTransferi( GL_ALPHA_SCALE, 1);
97 glPixelTransferi( GL_ALPHA_BIAS, 0);
99 // set initial rendering states
100 glShadeModel( GL_SMOOTH);
102 glDepthFunc( GL_LEQUAL);
103 glDepthMask( GL_TRUE);
104 glEnable( GL_DEPTH_TEST);
105 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
106 glCullFace( GL_FRONT);
107 glEnable( GL_CULL_FACE);
108 glEnable( GL_LIGHTING);
109 glEnable( GL_DITHER);
110 glEnable( GL_COLOR_MATERIAL);
111 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
112 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
113 glAlphaFunc( GL_GREATER, 0.5f);
115 if ( CanInitStereo(stereomode) ) {
116 InitStereo(stereomode);
118 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
119 stereomode = stereoNone;
123 void toggleFullscreen()
125 fullscreen = !fullscreen;
126 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
127 if (flags & SDL_WINDOW_FULLSCREEN) {
128 flags &= ~SDL_WINDOW_FULLSCREEN;
130 flags |= SDL_WINDOW_FULLSCREEN;
132 SDL_SetWindowFullscreen(sdlwindow, flags);
135 SDL_bool sdlEventProc(const SDL_Event &e)
141 case SDL_WINDOWEVENT:
142 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
147 case SDL_MOUSEMOTION:
148 deltah += e.motion.xrel;
149 deltav += e.motion.yrel;
153 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
154 (e.key.keysym.mod & KMOD_CTRL)) {
155 SDL_bool mode = SDL_TRUE;
156 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
157 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
158 SDL_SetWindowGrab(sdlwindow, mode);
159 SDL_SetRelativeMouseMode(mode);
160 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
168 // --------------------------------------------------------------------------
170 static Point gMidPoint;
183 if (!SDL_WasInit(SDL_INIT_VIDEO))
184 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
185 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
188 if (!LoadSettings()) {
189 fprintf(stderr, "Failed to load config, creating default\n");
193 if (SDL_GL_LoadLibrary(NULL) == -1) {
194 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
199 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
200 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
201 SDL_DisplayMode mode;
202 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
204 if ((mode.w < 640) || (mode.h < 480))
205 continue; // sane lower limit.
206 pair<int,int> resolution(mode.w, mode.h);
207 resolutions.insert(resolution);
211 if (resolutions.empty()) {
212 const std::string error = "No suitable video resolutions found.";
213 cerr << error << endl;
214 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
219 if (commandLineOptions[SHOWRESOLUTIONS]) {
220 printf("Available resolutions:\n");
221 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
222 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
226 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
227 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
229 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
230 if (commandLineOptions[FULLSCREEN]) {
231 fullscreen = commandLineOptions[FULLSCREEN].last()->type();
234 sdlflags |= SDL_WINDOW_FULLSCREEN;
236 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
237 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
240 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
241 kContextWidth, kContextHeight, sdlflags);
244 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
245 fprintf(stderr, "forcing 640x480...\n");
247 kContextHeight = 480;
248 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
249 kContextWidth, kContextHeight, sdlflags);
251 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
252 fprintf(stderr, "forcing 640x480 windowed mode...\n");
253 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
254 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
255 kContextWidth, kContextHeight, sdlflags);
258 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
264 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
266 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
271 SDL_GL_MakeCurrent(sdlwindow, glctx);
274 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
276 fprintf(stderr, "Failed to get a double-buffered context.\n");
281 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
282 SDL_GL_SetSwapInterval(1);
285 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
286 SDL_SetRelativeMouseMode(SDL_TRUE);
291 GLint width = kContextWidth;
292 GLint height = kContextHeight;
293 gMidPoint.h = width / 2;
294 gMidPoint.v = height / 2;
296 screenheight = height;
299 newscreenwidth = screenwidth;
300 newscreenheight = screenheight;
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);
314 static void DoMouse()
317 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
318 deltah *= usermousesensitivity;
319 deltav *= usermousesensitivity;
320 mousecoordh += deltah;
321 mousecoordv += deltav;
324 else if (mousecoordh >= kContextWidth)
325 mousecoordh = kContextWidth - 1;
328 else if (mousecoordv >= kContextHeight)
329 mousecoordv = kContextHeight - 1;
334 void DoFrameRate (int update)
336 static long frames = 0;
338 static AbsoluteTime time = {0, 0};
339 static AbsoluteTime frametime = {0, 0};
340 AbsoluteTime currTime = UpTime ();
341 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
343 if (0 > deltaTime) // if negative microseconds
344 deltaTime /= -1000000.0;
345 else // else milliseconds
348 multiplier = deltaTime;
349 if (multiplier < .001)
354 frametime = currTime; // reset for next time interval
356 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
358 if (0 > deltaTime) // if negative microseconds
359 deltaTime /= -1000000.0;
360 else // else milliseconds
363 if (0.001 <= deltaTime) { // has update interval passed
365 time = currTime; // reset for next time interval
374 static float sps = 200;
376 static float oldmult;
382 fps = 1 / multiplier;
384 count = multiplier * sps;
388 realmultiplier = multiplier;
389 multiplier *= gamespeed;
396 multiplier *= .00001;
397 if (slomo && !mainmenu)
398 multiplier *= slomospeed;
399 oldmult = multiplier;
400 multiplier /= (float)count;
406 for (int i = 0; i < count; i++) {
409 multiplier = oldmult;
412 /* - Debug code to test how many channels were active on average per frame
413 static long frames = 0;
415 static AbsoluteTime start = {0,0};
416 AbsoluteTime currTime = UpTime ();
417 static int num_channels = 0;
419 num_channels += OPENAL_GetChannelsPlaying();
420 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
422 if (0 > deltaTime) // if negative microseconds
423 deltaTime /= -1000000.0;
424 else // else milliseconds
432 float avg_channels = (float)num_channels / (float)frames;
434 ofstream opstream("log.txt",ios::app);
435 opstream << "Average frame count: ";
437 opstream << " frames - ";
438 opstream << avg_channels;
439 opstream << " per frame.\n";
446 if ( stereomode == stereoNone ) {
447 DrawGLScene(stereoCenter);
449 DrawGLScene(stereoLeft);
450 DrawGLScene(stereoRight);
454 // --------------------------------------------------------------------------
461 delete[] commandLineOptionsBuffer;
466 // --------------------------------------------------------------------------
468 static bool IsFocused()
470 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
476 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
477 static char *findBinaryInPath(const char *bin, char *envr)
479 size_t alloc_size = 0;
486 ptr = strchr(start, ':'); /* find next $PATH separator. */
490 size = strlen(start) + strlen(bin) + 2;
491 if (size > alloc_size) {
492 char *x = (char *) realloc(exe, size);
503 /* build full binary path... */
505 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
509 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
510 strcpy(exe, start); /* i'm lazy. piss off. */
514 start = ptr + 1; /* start points to beginning of next element. */
515 } while (ptr != NULL);
520 return(NULL); /* doesn't exist in path. */
521 } /* findBinaryInPath */
524 char *calcBaseDir(const char *argv0)
526 /* If there isn't a path on argv0, then look through the $PATH for it. */
530 if (strchr(argv0, '/')) {
531 retval = strdup(argv0);
533 *((char *) strrchr(retval, '/')) = '\0';
537 envr = getenv("PATH");
543 retval = findBinaryInPath(argv0, envr);
548 static inline void chdirToAppPath(const char *argv0)
550 char *dir = calcBaseDir(argv0);
552 #if (defined(__APPLE__) && defined(__MACH__))
553 // Chop off /Contents/MacOS if it's at the end of the string, so we
554 // land in the base of the app bundle.
555 const size_t len = strlen(dir);
556 const char *bundledirs = "/Contents/MacOS";
557 const size_t bundledirslen = strlen(bundledirs);
558 if (len > bundledirslen) {
559 char *ptr = (dir + len) - bundledirslen;
560 if (strcasecmp(ptr, bundledirs) == 0)
570 const option::Descriptor usage[] =
572 {UNKNOWN, 0, "", "", option::Arg::None, "USAGE: lugaru [options]\n\n"
574 {HELP, 0, "h", "help", option::Arg::None, " -h, --help Print usage and exit." },
575 {FULLSCREEN, 1, "f", "fullscreen", option::Arg::None, " -f, --fullscreen Start the game in fullscreen mode." },
576 {FULLSCREEN, 0, "w", "windowed", option::Arg::None, " -w, --windowed Start the game in windowed mode (default)." },
577 {NOMOUSEGRAB, 1, "", "nomousegrab", option::Arg::None, " --nomousegrab Disable mousegrab." },
578 {NOMOUSEGRAB, 0, "", "mousegrab", option::Arg::None, " --mousegrab Enable mousegrab (default)." },
579 {SOUND, OPENAL_OUTPUT_NOSOUND, "", "nosound", option::Arg::None, " --nosound Disable sound." },
580 {SOUND, OPENAL_OUTPUT_ALSA, "", "force-alsa", option::Arg::None, " --force-alsa Force use of ALSA back-end." },
581 {SOUND, OPENAL_OUTPUT_OSS, "", "force-oss", option::Arg::None, " --force-oss Force use of OSS back-end." },
582 {OPENALINFO, 0, "", "openal-info", option::Arg::None, " --openal-info Print info about OpenAL at launch." },
583 {SHOWRESOLUTIONS, 0, "", "showresolutions", option::Arg::None, " --showresolutions List the resolutions found by SDL at launch." },
587 option::Option commandLineOptions[commandLineOptionsNumber];
588 option::Option* commandLineOptionsBuffer;
590 int main(int argc, char **argv)
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;
598 commandLineOptionsBuffer = new option::Option[stats.buffer_max];
599 option::Parser parse(true, usage, argc, argv, commandLineOptions, commandLineOptionsBuffer);
602 delete[] commandLineOptionsBuffer;
606 if (commandLineOptions[HELP]) {
607 option::printUsage(std::cout, usage);
608 delete[] commandLineOptionsBuffer;
612 if (option::Option* opt = commandLineOptions[UNKNOWN]) {
613 std::cerr << "Unknown option: " << opt->name << "\n";
614 option::printUsage(std::cerr, usage);
615 delete[] commandLineOptionsBuffer;
619 // !!! FIXME: we could use a Win32 API for this. --ryan.
621 chdirToAppPath(argv[0]);
631 delete[] commandLineOptionsBuffer;
635 bool gameDone = false;
636 bool gameFocused = true;
638 while (!gameDone && !tryquit) {
642 // check windows messages
649 while ( SDL_PollEvent( &e ) ) {
650 if (!sdlEventProc(e)) {
661 // allow game chance to pause
666 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
677 } catch (const std::exception& error) {
680 std::string e = "Caught exception: ";
685 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Exception catched", error.what(), NULL);