2 Copyright (C) 2003, 2010 - Wolfire Games
3 Copyright (C) 2010-2017 - 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 "Platform/Platform.hpp"
26 #include "User/Settings.hpp"
27 #include "Version.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);
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);
160 SDL_SetWindowGrab(sdlwindow, mode);
161 SDL_SetRelativeMouseMode(mode);
162 } else if ((e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT)) {
170 // --------------------------------------------------------------------------
172 static Point gMidPoint;
185 if (!SDL_WasInit(SDL_INIT_VIDEO)) {
186 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
187 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
191 if (!LoadSettings()) {
192 fprintf(stderr, "Failed to load config, creating default\n");
196 if (SDL_GL_LoadLibrary(NULL) == -1) {
197 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
202 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
203 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
204 SDL_DisplayMode mode;
205 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1) {
208 if ((mode.w < 640) || (mode.h < 480)) {
209 continue; // sane lower limit.
211 pair<int, int> resolution(mode.w, mode.h);
212 resolutions.insert(resolution);
216 if (resolutions.empty()) {
217 const std::string error = "No suitable video resolutions found.";
218 cerr << error << endl;
219 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
224 if (commandLineOptions[SHOWRESOLUTIONS]) {
225 printf("Available resolutions:\n");
226 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
227 printf(" %d x %d\n", (int)resolution->first, (int)resolution->second);
231 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
232 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
234 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
235 if (commandLineOptions[FULLSCREEN]) {
236 fullscreen = commandLineOptions[FULLSCREEN].last()->type();
239 sdlflags |= SDL_WINDOW_FULLSCREEN;
241 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
242 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
245 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
246 kContextWidth, kContextHeight, sdlflags);
249 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
250 fprintf(stderr, "forcing 640x480...\n");
252 kContextHeight = 480;
253 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
254 kContextWidth, kContextHeight, sdlflags);
256 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
257 fprintf(stderr, "forcing 640x480 windowed mode...\n");
258 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
259 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
260 kContextWidth, kContextHeight, sdlflags);
263 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
269 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
271 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
276 SDL_GL_MakeCurrent(sdlwindow, glctx);
279 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf)) {
280 fprintf(stderr, "Failed to get a double-buffered context.\n");
285 if (SDL_GL_SetSwapInterval(-1) == -1) { // try swap_tear first.
286 SDL_GL_SetSwapInterval(1);
290 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
291 SDL_SetRelativeMouseMode(SDL_TRUE);
296 GLint width = kContextWidth;
297 GLint height = kContextHeight;
298 gMidPoint.h = width / 2;
299 gMidPoint.v = height / 2;
301 screenheight = height;
304 newscreenwidth = screenwidth;
305 newscreenheight = screenheight;
307 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
308 pair<int, int> startresolution(width, height);
309 if (resolutions.find(startresolution) == resolutions.end()) {
310 resolutions.insert(startresolution);
318 static void DoMouse()
321 if (mainmenu || ((abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000))) {
322 deltah *= usermousesensitivity;
323 deltav *= usermousesensitivity;
324 mousecoordh += deltah;
325 mousecoordv += deltav;
326 if (mousecoordh < 0) {
328 } else if (mousecoordh >= kContextWidth) {
329 mousecoordh = kContextWidth - 1;
331 if (mousecoordv < 0) {
333 } else if (mousecoordv >= kContextHeight) {
334 mousecoordv = kContextHeight - 1;
339 void DoFrameRate(int update)
341 static long frames = 0;
343 static AbsoluteTime time = { 0, 0 };
344 static AbsoluteTime frametime = { 0, 0 };
345 AbsoluteTime currTime = UpTime();
346 double deltaTime = (float)AbsoluteDeltaToDuration(currTime, frametime);
348 if (0 > deltaTime) { // if negative microseconds
349 deltaTime /= -1000000.0;
350 } else { // else milliseconds
354 multiplier = deltaTime;
355 if (multiplier < .001) {
358 if (multiplier > 10) {
362 frametime = currTime; // reset for next time interval
365 deltaTime = (float)AbsoluteDeltaToDuration(currTime, time);
367 if (0 > deltaTime) { // if negative microseconds
368 deltaTime /= -1000000.0;
369 } else { // else milliseconds
373 if (0.001 <= deltaTime) { // has update interval passed
375 time = currTime; // reset for next time interval
383 static float sps = 200;
385 static float oldmult;
388 if (multiplier > .6) {
392 fps = 1 / multiplier;
394 count = multiplier * sps;
399 realmultiplier = multiplier;
400 multiplier *= gamespeed;
401 if (difficulty == 1) {
404 if (difficulty == 0) {
409 multiplier *= .00001;
411 if (slomo && !mainmenu) {
412 multiplier *= slomospeed;
414 oldmult = multiplier;
415 multiplier /= (float)count;
421 for (int i = 0; i < count; i++) {
424 multiplier = oldmult;
427 /* - Debug code to test how many channels were active on average per frame
428 static long frames = 0;
430 static AbsoluteTime start = {0,0};
431 AbsoluteTime currTime = UpTime ();
432 static int num_channels = 0;
434 num_channels += OPENAL_GetChannelsPlaying();
435 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
437 if (0 > deltaTime) // if negative microseconds
438 deltaTime /= -1000000.0;
439 else // else milliseconds
447 float avg_channels = (float)num_channels / (float)frames;
449 ofstream opstream("log.txt",ios::app);
450 opstream << "Average frame count: ";
452 opstream << " frames - ";
453 opstream << avg_channels;
454 opstream << " per frame.\n";
461 if (stereomode == stereoNone) {
462 DrawGLScene(stereoCenter);
464 DrawGLScene(stereoLeft);
465 DrawGLScene(stereoRight);
469 // --------------------------------------------------------------------------
475 delete[] commandLineOptionsBuffer;
480 // --------------------------------------------------------------------------
482 static bool IsFocused()
484 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
488 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
489 static char* findBinaryInPath(const char* bin, char* envr)
491 size_t alloc_size = 0;
498 ptr = strchr(start, ':'); /* find next $PATH separator. */
502 size = strlen(start) + strlen(bin) + 2;
503 if (size > alloc_size) {
504 char* x = (char*)realloc(exe, size);
516 /* build full binary path... */
518 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/')) {
523 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
524 strcpy(exe, start); /* i'm lazy. piss off. */
528 start = ptr + 1; /* start points to beginning of next element. */
529 } while (ptr != NULL);
535 return (NULL); /* doesn't exist in path. */
536 } /* findBinaryInPath */
538 char* calcBaseDir(const char* argv0)
540 /* If there isn't a path on argv0, then look through the $PATH for it. */
544 if (strchr(argv0, '/')) {
545 retval = strdup(argv0);
547 *((char*)strrchr(retval, '/')) = '\0';
552 envr = getenv("PATH");
560 retval = findBinaryInPath(argv0, envr);
565 static inline void chdirToAppPath(const char* argv0)
567 char* dir = calcBaseDir(argv0);
569 #if (defined(__APPLE__) && defined(__MACH__))
570 // Chop off /Contents/MacOS if it's at the end of the string, so we
571 // land in the base of the app bundle.
572 const size_t len = strlen(dir);
573 const char* bundledirs = "/Contents/MacOS";
574 const size_t bundledirslen = strlen(bundledirs);
575 if (len > bundledirslen) {
576 char* ptr = (dir + len) - bundledirslen;
577 if (strcasecmp(ptr, bundledirs) == 0)
587 const option::Descriptor usage[] =
589 { UNKNOWN, 0, "", "", option::Arg::None, "USAGE: lugaru [options]\n\n"
591 { VERSION, 0, "v", "version", option::Arg::None, " -v, --version Print version and exit." },
592 { HELP, 0, "h", "help", option::Arg::None, " -h, --help Print usage and exit." },
593 { FULLSCREEN, 1, "f", "fullscreen", option::Arg::None, " -f, --fullscreen Start the game in fullscreen mode." },
594 { FULLSCREEN, 0, "w", "windowed", option::Arg::None, " -w, --windowed Start the game in windowed mode (default)." },
595 { NOMOUSEGRAB, 1, "", "nomousegrab", option::Arg::None, " --nomousegrab Disable mousegrab." },
596 { NOMOUSEGRAB, 0, "", "mousegrab", option::Arg::None, " --mousegrab Enable mousegrab (default)." },
597 { SOUND, 1, "", "nosound", option::Arg::None, " --nosound Disable sound." },
598 { OPENALINFO, 0, "", "openal-info", option::Arg::None, " --openal-info Print info about OpenAL at launch." },
599 { SHOWRESOLUTIONS, 0, "", "showresolutions", option::Arg::None, " --showresolutions List the resolutions found by SDL at launch." },
600 { DEVTOOLS, 0, "d", "devtools", option::Arg::None, " -d, --devtools Enable dev tools: console, level editor and debug info." },
604 option::Option commandLineOptions[commandLineOptionsNumber];
605 option::Option* commandLineOptionsBuffer;
607 int main(int argc, char** argv)
610 argv += (argc > 0); // skip program name argv[0] if present
611 option::Stats stats(true, usage, argc, argv);
612 if (commandLineOptionsNumber != stats.options_max) {
613 std::cerr << "Found incorrect command line option number" << std::endl;
616 commandLineOptionsBuffer = new option::Option[stats.buffer_max];
617 option::Parser parse(true, usage, argc, argv, commandLineOptions, commandLineOptionsBuffer);
620 delete[] commandLineOptionsBuffer;
624 // Always start by printing the version and info to the stdout
625 std::cout << "--------------------------------------------------------------------------\n"
626 << "Lugaru HD: The Rabbit's Foot, by Wolfire Games and the OSS Lugaru project.\n\n"
627 << "Licensed under the GPL 2.0+ and CC-BY-SA 3.0 and 4.0 licenses.\n"
628 << "More information, updates and bug reports at http://osslugaru.gitlab.io\n"
631 std::cout << "Version " + VERSION_STRING + " -- " + VERSION_BUILD_TYPE + " build\n"
632 << "--------------------------------------------------------------------------\n"
635 if (commandLineOptions[VERSION]) {
636 // That was enough, quit.
637 delete[] commandLineOptionsBuffer;
641 if (commandLineOptions[HELP]) {
642 option::printUsage(std::cout, usage);
643 delete[] commandLineOptionsBuffer;
647 if (option::Option* opt = commandLineOptions[UNKNOWN]) {
648 std::cerr << "Unknown option: " << opt->name << "\n";
649 option::printUsage(std::cerr, usage);
650 delete[] commandLineOptionsBuffer;
654 // !!! FIXME: we could use a Win32 API for this. --ryan.
656 chdirToAppPath(argv[0]);
668 delete[] commandLineOptionsBuffer;
672 if (commandLineOptions[DEVTOOLS]) {
676 bool gameDone = false;
677 bool gameFocused = true;
679 while (!gameDone && !tryquit) {
683 // check windows messages
690 while (SDL_PollEvent(&e)) {
691 if (!sdlEventProc(e)) {
702 // allow game chance to pause
707 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
719 } catch (const std::exception& error) {
722 std::string e = "Caught exception: ";
727 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Exception catched", error.what(), NULL);