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) ------------------------------------------
68 #pragma warning(disable: 4273)
71 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
72 #define GL_FUNC(ret,fn,params,call,rt) \
74 static ret (GLAPIENTRY *p##fn) params = NULL; \
75 ret GLAPIENTRY fn params { rt p##fn call; } \
85 static bool lookup_glsym(const char *funcname, void **func)
87 *func = SDL_GL_GetProcAddress(funcname);
89 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
95 static bool lookup_all_glsyms(void)
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;
103 #endif // __MINGW32__
107 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
108 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
112 #endif // __MINGW32__
119 //-----------------------------------------------------------------------------------------------------------------------
125 glClear( GL_COLOR_BUFFER_BIT );
129 glDisable( GL_ALPHA_TEST);
130 glDisable( GL_BLEND);
131 glDisable( GL_DEPTH_TEST);
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);
147 // set initial rendering states
148 glShadeModel( GL_SMOOTH);
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);
163 if ( CanInitStereo(stereomode) ) {
164 InitStereo(stereomode);
166 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
167 stereomode = stereoNone;
171 void toggleFullscreen()
173 fullscreen = !fullscreen;
174 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
175 if (flags & SDL_WINDOW_FULLSCREEN) {
176 flags &= ~SDL_WINDOW_FULLSCREEN;
178 flags |= SDL_WINDOW_FULLSCREEN;
180 SDL_SetWindowFullscreen(sdlwindow, flags);
183 SDL_bool sdlEventProc(const SDL_Event &e)
189 case SDL_WINDOWEVENT:
190 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
195 case SDL_MOUSEMOTION:
196 deltah += e.motion.xrel;
197 deltav += e.motion.yrel;
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) ) {
216 // --------------------------------------------------------------------------
218 static Point gMidPoint;
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());
236 if (!LoadSettings()) {
237 fprintf(stderr, "Failed to load config, creating default\n");
241 if (SDL_GL_LoadLibrary(NULL) == -1) {
242 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
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)
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);
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);
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);
274 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
275 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
277 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
278 if (commandLineOptions[FULLSCREEN]) {
279 fullscreen = commandLineOptions[FULLSCREEN].last()->type();
282 sdlflags |= SDL_WINDOW_FULLSCREEN;
284 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
285 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
288 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
289 kContextWidth, kContextHeight, sdlflags);
292 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
293 fprintf(stderr, "forcing 640x480...\n");
295 kContextHeight = 480;
296 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
297 kContextWidth, kContextHeight, sdlflags);
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);
306 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
312 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
314 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
319 SDL_GL_MakeCurrent(sdlwindow, glctx);
321 if (!lookup_all_glsyms()) {
322 fprintf(stderr, "Missing required OpenGL functions.\n");
328 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
330 fprintf(stderr, "Failed to get a double-buffered context.\n");
335 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
336 SDL_GL_SetSwapInterval(1);
339 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
340 SDL_SetRelativeMouseMode(SDL_TRUE);
345 GLint width = kContextWidth;
346 GLint height = kContextHeight;
347 gMidPoint.h = width / 2;
348 gMidPoint.v = height / 2;
350 screenheight = height;
353 newscreenwidth = screenwidth;
354 newscreenheight = screenheight;
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);
368 static void DoMouse()
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;
378 else if (mousecoordh >= kContextWidth)
379 mousecoordh = kContextWidth - 1;
382 else if (mousecoordv >= kContextHeight)
383 mousecoordv = kContextHeight - 1;
388 void DoFrameRate (int update)
390 static long frames = 0;
392 static AbsoluteTime time = {0, 0};
393 static AbsoluteTime frametime = {0, 0};
394 AbsoluteTime currTime = UpTime ();
395 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
397 if (0 > deltaTime) // if negative microseconds
398 deltaTime /= -1000000.0;
399 else // else milliseconds
402 multiplier = deltaTime;
403 if (multiplier < .001)
408 frametime = currTime; // reset for next time interval
410 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
412 if (0 > deltaTime) // if negative microseconds
413 deltaTime /= -1000000.0;
414 else // else milliseconds
417 if (0.001 <= deltaTime) { // has update interval passed
419 time = currTime; // reset for next time interval
428 static float sps = 200;
430 static float oldmult;
436 fps = 1 / multiplier;
438 count = multiplier * sps;
442 realmultiplier = multiplier;
443 multiplier *= gamespeed;
450 multiplier *= .00001;
451 if (slomo && !mainmenu)
452 multiplier *= slomospeed;
453 oldmult = multiplier;
454 multiplier /= (float)count;
460 for (int i = 0; i < count; i++) {
463 multiplier = oldmult;
466 /* - Debug code to test how many channels were active on average per frame
467 static long frames = 0;
469 static AbsoluteTime start = {0,0};
470 AbsoluteTime currTime = UpTime ();
471 static int num_channels = 0;
473 num_channels += OPENAL_GetChannelsPlaying();
474 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
476 if (0 > deltaTime) // if negative microseconds
477 deltaTime /= -1000000.0;
478 else // else milliseconds
486 float avg_channels = (float)num_channels / (float)frames;
488 ofstream opstream("log.txt",ios::app);
489 opstream << "Average frame count: ";
491 opstream << " frames - ";
492 opstream << avg_channels;
493 opstream << " per frame.\n";
500 if ( stereomode == stereoNone ) {
501 DrawGLScene(stereoCenter);
503 DrawGLScene(stereoLeft);
504 DrawGLScene(stereoRight);
508 // --------------------------------------------------------------------------
515 delete[] commandLineOptionsBuffer;
518 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
519 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
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__
528 // --------------------------------------------------------------------------
530 static bool IsFocused()
532 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
538 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
539 static char *findBinaryInPath(const char *bin, char *envr)
541 size_t alloc_size = 0;
548 ptr = strchr(start, ':'); /* find next $PATH separator. */
552 size = strlen(start) + strlen(bin) + 2;
553 if (size > alloc_size) {
554 char *x = (char *) realloc(exe, size);
565 /* build full binary path... */
567 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
571 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
572 strcpy(exe, start); /* i'm lazy. piss off. */
576 start = ptr + 1; /* start points to beginning of next element. */
577 } while (ptr != NULL);
582 return(NULL); /* doesn't exist in path. */
583 } /* findBinaryInPath */
586 char *calcBaseDir(const char *argv0)
588 /* If there isn't a path on argv0, then look through the $PATH for it. */
592 if (strchr(argv0, '/')) {
593 retval = strdup(argv0);
595 *((char *) strrchr(retval, '/')) = '\0';
599 envr = getenv("PATH");
605 retval = findBinaryInPath(argv0, envr);
610 static inline void chdirToAppPath(const char *argv0)
612 char *dir = calcBaseDir(argv0);
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)
632 const option::Descriptor usage[] =
634 {UNKNOWN, 0, "", "", option::Arg::None, "USAGE: lugaru [options]\n\n"
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." },
649 option::Option commandLineOptions[commandLineOptionsNumber];
650 option::Option* commandLineOptionsBuffer;
652 int main(int argc, char **argv)
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;
660 commandLineOptionsBuffer = new option::Option[stats.buffer_max];
661 option::Parser parse(true, usage, argc, argv, commandLineOptions, commandLineOptionsBuffer);
664 delete[] commandLineOptionsBuffer;
668 if (commandLineOptions[HELP]) {
669 option::printUsage(std::cout, usage);
670 delete[] commandLineOptionsBuffer;
674 if (option::Option* opt = commandLineOptions[UNKNOWN]) {
675 std::cerr << "Unknown option: " << opt->name << "\n";
676 option::printUsage(std::cerr, usage);
677 delete[] commandLineOptionsBuffer;
681 // !!! FIXME: we could use a Win32 API for this. --ryan.
683 chdirToAppPath(argv[0]);
693 delete[] commandLineOptionsBuffer;
697 bool gameDone = false;
698 bool gameFocused = true;
700 while (!gameDone && !tryquit) {
704 // check windows messages
711 while ( SDL_PollEvent( &e ) ) {
712 if (!sdlEventProc(e)) {
723 // allow game chance to pause
728 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
739 } catch (const std::exception& error) {
742 std::string e = "Caught exception: ";
747 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Exception catched", error.what(), NULL);