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/>.
29 #include "openal_wrapper.h"
31 extern float multiplier;
33 extern float realmultiplier;
35 extern bool cellophane;
36 extern float texdetail;
40 extern bool stillloading;
43 extern float slomospeed;
44 extern float slomofreq;
45 extern bool visibleloading;
55 #include "MacCompatibility.h"
60 #include "win-res/resource.h"
63 extern SDL_Window *sdlwindow;
67 set<pair<int,int>> resolutions;
74 // statics/globals (internal only) ------------------------------------------
78 #pragma warning(disable: 4273)
81 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
82 #define GL_FUNC(ret,fn,params,call,rt) \
84 static ret (GLAPIENTRY *p##fn) params = NULL; \
85 ret GLAPIENTRY fn params { rt p##fn call; } \
95 static bool lookup_glsym(const char *funcname, void **func)
97 *func = SDL_GL_GetProcAddress(funcname);
99 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
105 static bool lookup_all_glsyms(void)
108 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
109 #define GL_FUNC(ret,fn,params,call,rt) \
110 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
113 #endif // __MINGW32__
117 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
118 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
122 #endif // __MINGW32__
127 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
137 static int _argc = 0;
138 static char **_argv = NULL;
140 bool cmdline(const char *cmd)
142 for (int i = 1; i < _argc; i++) {
143 char *arg = _argv[i];
146 if (strcasecmp(arg, cmd) == 0)
153 //-----------------------------------------------------------------------------------------------------------------------
159 glClear( GL_COLOR_BUFFER_BIT );
163 glDisable( GL_ALPHA_TEST);
164 glDisable( GL_BLEND);
165 glDisable( GL_DEPTH_TEST);
167 glDisable( GL_LIGHTING);
168 glDisable( GL_LOGIC_OP);
169 glDisable( GL_TEXTURE_1D);
170 glDisable( GL_TEXTURE_2D);
171 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
172 glPixelTransferi( GL_RED_SCALE, 1);
173 glPixelTransferi( GL_RED_BIAS, 0);
174 glPixelTransferi( GL_GREEN_SCALE, 1);
175 glPixelTransferi( GL_GREEN_BIAS, 0);
176 glPixelTransferi( GL_BLUE_SCALE, 1);
177 glPixelTransferi( GL_BLUE_BIAS, 0);
178 glPixelTransferi( GL_ALPHA_SCALE, 1);
179 glPixelTransferi( GL_ALPHA_BIAS, 0);
181 // set initial rendering states
182 glShadeModel( GL_SMOOTH);
184 glDepthFunc( GL_LEQUAL);
185 glDepthMask( GL_TRUE);
186 glEnable( GL_DEPTH_TEST);
187 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
188 glCullFace( GL_FRONT);
189 glEnable( GL_CULL_FACE);
190 glEnable( GL_LIGHTING);
191 glEnable( GL_DITHER);
192 glEnable( GL_COLOR_MATERIAL);
193 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
194 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
195 glAlphaFunc( GL_GREATER, 0.5f);
197 if ( CanInitStereo(stereomode) ) {
198 InitStereo(stereomode);
200 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
201 stereomode = stereoNone;
205 void toggleFullscreen()
207 fullscreen = !fullscreen;
208 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
209 if (flags & SDL_WINDOW_FULLSCREEN) {
210 flags &= ~SDL_WINDOW_FULLSCREEN;
212 flags |= SDL_WINDOW_FULLSCREEN;
214 SDL_SetWindowFullscreen(sdlwindow, flags);
217 static SDL_bool sdlEventProc(const SDL_Event &e)
223 case SDL_WINDOWEVENT:
224 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
229 case SDL_MOUSEMOTION:
230 deltah += e.motion.xrel;
231 deltav += e.motion.yrel;
235 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
236 (e.key.keysym.mod & KMOD_CTRL)) {
237 SDL_bool mode = SDL_TRUE;
238 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
239 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
240 SDL_SetWindowGrab(sdlwindow, mode);
241 SDL_SetRelativeMouseMode(mode);
242 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
252 // --------------------------------------------------------------------------
254 static Point gMidPoint;
268 if (!SDL_WasInit(SDL_INIT_VIDEO))
269 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
270 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
273 if (!LoadSettings()) {
274 fprintf(stderr, "Failed to load config, creating default\n");
277 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
281 if (SDL_GL_LoadLibrary(NULL) == -1) {
282 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
287 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
288 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
289 SDL_DisplayMode mode;
290 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
292 if ((mode.w < 640) || (mode.h < 480))
293 continue; // sane lower limit.
294 pair<int,int> resolution(mode.w, mode.h);
295 resolutions.insert(resolution);
299 if (resolutions.empty()) {
300 const std::string error = "No suitable video resolutions found.";
301 cerr << error << endl;
302 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
307 if (cmdline("showresolutions")) {
308 printf("Available resolutions:\n");
309 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
310 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
314 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
315 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
317 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
318 if ((fullscreen || cmdline("fullscreen")) && !cmdline("windowed")) {
320 sdlflags |= SDL_WINDOW_FULLSCREEN;
322 if (!cmdline("nomousegrab"))
323 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
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());
330 fprintf(stderr, "forcing 640x480...\n");
332 kContextHeight = 480;
333 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
334 kContextWidth, kContextHeight, sdlflags);
336 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
337 fprintf(stderr, "forcing 640x480 windowed mode...\n");
338 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
339 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
340 kContextWidth, kContextHeight, sdlflags);
343 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
349 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
351 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
356 SDL_GL_MakeCurrent(sdlwindow, glctx);
358 if (!lookup_all_glsyms()) {
359 fprintf(stderr, "Missing required OpenGL functions.\n");
365 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
367 fprintf(stderr, "Failed to get a double-buffered context.\n");
372 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
373 SDL_GL_SetSwapInterval(1);
376 if (!cmdline("nomousegrab"))
377 SDL_SetRelativeMouseMode(SDL_TRUE);
381 GLint width = kContextWidth;
382 GLint height = kContextHeight;
383 gMidPoint.h = width / 2;
384 gMidPoint.v = height / 2;
386 screenheight = height;
389 newscreenwidth = screenwidth;
390 newscreenheight = screenheight;
392 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
393 pair<int,int> startresolution(width,height);
394 if (resolutions.find(startresolution) == resolutions.end()) {
395 resolutions.insert(startresolution);
404 static void DoMouse()
407 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
408 deltah *= usermousesensitivity;
409 deltav *= usermousesensitivity;
410 mousecoordh += deltah;
411 mousecoordv += deltav;
414 else if (mousecoordh >= kContextWidth)
415 mousecoordh = kContextWidth - 1;
418 else if (mousecoordv >= kContextHeight)
419 mousecoordv = kContextHeight - 1;
424 void DoFrameRate (int update)
426 static long frames = 0;
428 static AbsoluteTime time = {0, 0};
429 static AbsoluteTime frametime = {0, 0};
430 AbsoluteTime currTime = UpTime ();
431 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
433 if (0 > deltaTime) // if negative microseconds
434 deltaTime /= -1000000.0;
435 else // else milliseconds
438 multiplier = deltaTime;
439 if (multiplier < .001)
444 frametime = currTime; // reset for next time interval
446 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
448 if (0 > deltaTime) // if negative microseconds
449 deltaTime /= -1000000.0;
450 else // else milliseconds
453 if (0.001 <= deltaTime) { // has update interval passed
455 time = currTime; // reset for next time interval
464 static float sps = 200;
466 static float oldmult;
472 fps = 1 / multiplier;
474 count = multiplier * sps;
478 realmultiplier = multiplier;
479 multiplier *= gamespeed;
486 multiplier *= .00001;
487 if (slomo && !mainmenu)
488 multiplier *= slomospeed;
489 oldmult = multiplier;
490 multiplier /= (float)count;
496 for (int i = 0; i < count; i++) {
499 multiplier = oldmult;
502 /* - Debug code to test how many channels were active on average per frame
503 static long frames = 0;
505 static AbsoluteTime start = {0,0};
506 AbsoluteTime currTime = UpTime ();
507 static int num_channels = 0;
509 num_channels += OPENAL_GetChannelsPlaying();
510 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
512 if (0 > deltaTime) // if negative microseconds
513 deltaTime /= -1000000.0;
514 else // else milliseconds
522 float avg_channels = (float)num_channels / (float)frames;
524 ofstream opstream("log.txt",ios::app);
525 opstream << "Average frame count: ";
527 opstream << " frames - ";
528 opstream << avg_channels;
529 opstream << " per frame.\n";
536 if ( stereomode == stereoNone ) {
537 DrawGLScene(stereoCenter);
539 DrawGLScene(stereoLeft);
540 DrawGLScene(stereoRight);
544 // --------------------------------------------------------------------------
552 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
553 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
556 // cheat here...static destructors are calling glDeleteTexture() after
557 // the context is destroyed and libGL unloaded by SDL_Quit().
558 pglDeleteTextures = glDeleteTextures_doNothing;
559 #endif // __MINGW32__
563 // --------------------------------------------------------------------------
565 static bool IsFocused()
567 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
573 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
574 static char *findBinaryInPath(const char *bin, char *envr)
576 size_t alloc_size = 0;
583 ptr = strchr(start, ':'); /* find next $PATH separator. */
587 size = strlen(start) + strlen(bin) + 2;
588 if (size > alloc_size) {
589 char *x = (char *) realloc(exe, size);
600 /* build full binary path... */
602 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
606 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
607 strcpy(exe, start); /* i'm lazy. piss off. */
611 start = ptr + 1; /* start points to beginning of next element. */
612 } while (ptr != NULL);
617 return(NULL); /* doesn't exist in path. */
618 } /* findBinaryInPath */
621 char *calcBaseDir(const char *argv0)
623 /* If there isn't a path on argv0, then look through the $PATH for it. */
627 if (strchr(argv0, '/')) {
628 retval = strdup(argv0);
630 *((char *) strrchr(retval, '/')) = '\0';
634 envr = getenv("PATH");
640 retval = findBinaryInPath(argv0, envr);
645 static inline void chdirToAppPath(const char *argv0)
647 char *dir = calcBaseDir(argv0);
649 #if (defined(__APPLE__) && defined(__MACH__))
650 // Chop off /Contents/MacOS if it's at the end of the string, so we
651 // land in the base of the app bundle.
652 const size_t len = strlen(dir);
653 const char *bundledirs = "/Contents/MacOS";
654 const size_t bundledirslen = strlen(bundledirs);
655 if (len > bundledirslen) {
656 char *ptr = (dir + len) - bundledirslen;
657 if (strcasecmp(ptr, bundledirs) == 0)
668 int main(int argc, char **argv)
673 // !!! FIXME: we could use a Win32 API for this. --ryan.
675 chdirToAppPath(argv[0]);
687 while (!gDone && !tryquit) {
691 // check windows messages
698 while ( SDL_PollEvent( &e ) ) {
699 if (!sdlEventProc(e)) {
710 // allow game chance to pause
715 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
726 } catch (const std::exception& error) {
729 std::string e = "Caught exception: ";
734 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);