2 Copyright (C) 2003, 2010 - Wolfire Games
4 This file is part of Lugaru.
6 Lugaru is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 Lugaru is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Lugaru. If not, see <http://www.gnu.org/licenses/>.
28 #include "MacCompatibility.h"
35 #include "openal_wrapper.h"
40 #include "win-res/resource.h"
43 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__
117 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
124 static int _argc = 0;
125 static char **_argv = NULL;
127 bool cmdline(const char *cmd)
129 for (int i = 1; i < _argc; i++) {
130 char *arg = _argv[i];
133 if (strcasecmp(arg, cmd) == 0)
140 //-----------------------------------------------------------------------------------------------------------------------
146 glClear( GL_COLOR_BUFFER_BIT );
150 glDisable( GL_ALPHA_TEST);
151 glDisable( GL_BLEND);
152 glDisable( GL_DEPTH_TEST);
154 glDisable( GL_LIGHTING);
155 glDisable( GL_LOGIC_OP);
156 glDisable( GL_TEXTURE_1D);
157 glDisable( GL_TEXTURE_2D);
158 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
159 glPixelTransferi( GL_RED_SCALE, 1);
160 glPixelTransferi( GL_RED_BIAS, 0);
161 glPixelTransferi( GL_GREEN_SCALE, 1);
162 glPixelTransferi( GL_GREEN_BIAS, 0);
163 glPixelTransferi( GL_BLUE_SCALE, 1);
164 glPixelTransferi( GL_BLUE_BIAS, 0);
165 glPixelTransferi( GL_ALPHA_SCALE, 1);
166 glPixelTransferi( GL_ALPHA_BIAS, 0);
168 // set initial rendering states
169 glShadeModel( GL_SMOOTH);
171 glDepthFunc( GL_LEQUAL);
172 glDepthMask( GL_TRUE);
173 glEnable( GL_DEPTH_TEST);
174 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
175 glCullFace( GL_FRONT);
176 glEnable( GL_CULL_FACE);
177 glEnable( GL_LIGHTING);
178 glEnable( GL_DITHER);
179 glEnable( GL_COLOR_MATERIAL);
180 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
181 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
182 glAlphaFunc( GL_GREATER, 0.5f);
184 if ( CanInitStereo(stereomode) ) {
185 InitStereo(stereomode);
187 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
188 stereomode = stereoNone;
192 void toggleFullscreen()
194 fullscreen = !fullscreen;
195 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
196 if (flags & SDL_WINDOW_FULLSCREEN) {
197 flags &= ~SDL_WINDOW_FULLSCREEN;
199 flags |= SDL_WINDOW_FULLSCREEN;
201 SDL_SetWindowFullscreen(sdlwindow, flags);
204 static SDL_bool sdlEventProc(const SDL_Event &e)
210 case SDL_WINDOWEVENT:
211 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
216 case SDL_MOUSEMOTION:
217 deltah += e.motion.xrel;
218 deltav += e.motion.yrel;
222 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
223 (e.key.keysym.mod & KMOD_CTRL)) {
224 SDL_bool mode = SDL_TRUE;
225 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
226 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
227 SDL_SetWindowGrab(sdlwindow, mode);
228 SDL_SetRelativeMouseMode(mode);
229 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
239 // --------------------------------------------------------------------------
241 static Point gMidPoint;
254 if (!SDL_WasInit(SDL_INIT_VIDEO))
255 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
256 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
259 if (!LoadSettings()) {
260 fprintf(stderr, "Failed to load config, creating default\n");
263 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
267 if (SDL_GL_LoadLibrary(NULL) == -1) {
268 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
273 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
274 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
275 SDL_DisplayMode mode;
276 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
278 if ((mode.w < 640) || (mode.h < 480))
279 continue; // sane lower limit.
280 pair<int,int> resolution(mode.w, mode.h);
281 resolutions.insert(resolution);
285 if (resolutions.empty()) {
286 const std::string error = "No suitable video resolutions found.";
287 cerr << error << endl;
288 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
293 if (cmdline("showresolutions")) {
294 printf("Available resolutions:\n");
295 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
296 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
300 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
301 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
303 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
304 if ((fullscreen || cmdline("fullscreen")) && !cmdline("windowed")) {
306 sdlflags |= SDL_WINDOW_FULLSCREEN;
308 if (!cmdline("nomousegrab"))
309 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
311 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
312 kContextWidth, kContextHeight, sdlflags);
315 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
316 fprintf(stderr, "forcing 640x480...\n");
318 kContextHeight = 480;
319 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
320 kContextWidth, kContextHeight, sdlflags);
322 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
323 fprintf(stderr, "forcing 640x480 windowed mode...\n");
324 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
325 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
326 kContextWidth, kContextHeight, sdlflags);
329 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
335 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
337 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
342 SDL_GL_MakeCurrent(sdlwindow, glctx);
344 if (!lookup_all_glsyms()) {
345 fprintf(stderr, "Missing required OpenGL functions.\n");
351 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
353 fprintf(stderr, "Failed to get a double-buffered context.\n");
358 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
359 SDL_GL_SetSwapInterval(1);
362 if (!cmdline("nomousegrab"))
363 SDL_SetRelativeMouseMode(SDL_TRUE);
367 GLint width = kContextWidth;
368 GLint height = kContextHeight;
369 gMidPoint.h = width / 2;
370 gMidPoint.v = height / 2;
372 screenheight = height;
375 newscreenwidth = screenwidth;
376 newscreenheight = screenheight;
378 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
379 pair<int,int> startresolution(width,height);
380 if (resolutions.find(startresolution) == resolutions.end()) {
381 resolutions.insert(startresolution);
390 static void DoMouse()
393 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
394 deltah *= usermousesensitivity;
395 deltav *= usermousesensitivity;
396 mousecoordh += deltah;
397 mousecoordv += deltav;
400 else if (mousecoordh >= kContextWidth)
401 mousecoordh = kContextWidth - 1;
404 else if (mousecoordv >= kContextHeight)
405 mousecoordv = kContextHeight - 1;
410 void DoFrameRate (int update)
412 static long frames = 0;
414 static AbsoluteTime time = {0, 0};
415 static AbsoluteTime frametime = {0, 0};
416 AbsoluteTime currTime = UpTime ();
417 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
419 if (0 > deltaTime) // if negative microseconds
420 deltaTime /= -1000000.0;
421 else // else milliseconds
424 multiplier = deltaTime;
425 if (multiplier < .001)
430 frametime = currTime; // reset for next time interval
432 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
434 if (0 > deltaTime) // if negative microseconds
435 deltaTime /= -1000000.0;
436 else // else milliseconds
439 if (0.001 <= deltaTime) { // has update interval passed
441 time = currTime; // reset for next time interval
450 static float sps = 200;
452 static float oldmult;
458 fps = 1 / multiplier;
460 count = multiplier * sps;
464 realmultiplier = multiplier;
465 multiplier *= gamespeed;
472 multiplier *= .00001;
473 if (slomo && !mainmenu)
474 multiplier *= slomospeed;
475 oldmult = multiplier;
476 multiplier /= (float)count;
482 for (int i = 0; i < count; i++) {
485 multiplier = oldmult;
488 /* - Debug code to test how many channels were active on average per frame
489 static long frames = 0;
491 static AbsoluteTime start = {0,0};
492 AbsoluteTime currTime = UpTime ();
493 static int num_channels = 0;
495 num_channels += OPENAL_GetChannelsPlaying();
496 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
498 if (0 > deltaTime) // if negative microseconds
499 deltaTime /= -1000000.0;
500 else // else milliseconds
508 float avg_channels = (float)num_channels / (float)frames;
510 ofstream opstream("log.txt",ios::app);
511 opstream << "Average frame count: ";
513 opstream << " frames - ";
514 opstream << avg_channels;
515 opstream << " per frame.\n";
522 if ( stereomode == stereoNone ) {
523 DrawGLScene(stereoCenter);
525 DrawGLScene(stereoLeft);
526 DrawGLScene(stereoRight);
530 // --------------------------------------------------------------------------
538 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
539 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
542 // cheat here...static destructors are calling glDeleteTexture() after
543 // the context is destroyed and libGL unloaded by SDL_Quit().
544 pglDeleteTextures = glDeleteTextures_doNothing;
545 #endif // __MINGW32__
549 // --------------------------------------------------------------------------
551 static bool IsFocused()
553 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
559 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
560 static char *findBinaryInPath(const char *bin, char *envr)
562 size_t alloc_size = 0;
569 ptr = strchr(start, ':'); /* find next $PATH separator. */
573 size = strlen(start) + strlen(bin) + 2;
574 if (size > alloc_size) {
575 char *x = (char *) realloc(exe, size);
586 /* build full binary path... */
588 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
592 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
593 strcpy(exe, start); /* i'm lazy. piss off. */
597 start = ptr + 1; /* start points to beginning of next element. */
598 } while (ptr != NULL);
603 return(NULL); /* doesn't exist in path. */
604 } /* findBinaryInPath */
607 char *calcBaseDir(const char *argv0)
609 /* If there isn't a path on argv0, then look through the $PATH for it. */
613 if (strchr(argv0, '/')) {
614 retval = strdup(argv0);
616 *((char *) strrchr(retval, '/')) = '\0';
620 envr = getenv("PATH");
626 retval = findBinaryInPath(argv0, envr);
631 static inline void chdirToAppPath(const char *argv0)
633 char *dir = calcBaseDir(argv0);
635 #if (defined(__APPLE__) && defined(__MACH__))
636 // Chop off /Contents/MacOS if it's at the end of the string, so we
637 // land in the base of the app bundle.
638 const size_t len = strlen(dir);
639 const char *bundledirs = "/Contents/MacOS";
640 const size_t bundledirslen = strlen(bundledirs);
641 if (len > bundledirslen) {
642 char *ptr = (dir + len) - bundledirslen;
643 if (strcasecmp(ptr, bundledirs) == 0)
654 int main(int argc, char **argv)
659 // !!! FIXME: we could use a Win32 API for this. --ryan.
661 chdirToAppPath(argv[0]);
673 bool gameDone = false;
674 bool gameFocused = true;
676 while (!gameDone && !tryquit) {
680 // check windows messages
687 while ( SDL_PollEvent( &e ) ) {
688 if (!sdlEventProc(e)) {
699 // allow game chance to pause
704 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
715 } catch (const std::exception& error) {
718 std::string e = "Caught exception: ";
723 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);