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
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program 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.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
35 static bool load_image(const char * fname, TGAImageRec & tex);
36 static bool load_png(const char * fname, TGAImageRec & tex);
37 static bool load_jpg(const char * fname, TGAImageRec & tex);
38 bool save_image(const char * fname);
39 static bool save_png(const char * fname);
42 #include "openal_wrapper.h"
44 extern float multiplier;
46 extern float realmultiplier;
48 extern bool cellophane;
49 extern float texdetail;
53 extern bool stillloading;
58 extern float slomospeed;
59 extern float slomofreq;
69 #include "MacCompatibility.h"
74 #include "win-res/resource.h"
77 extern SDL_Window *sdlwindow;
81 SDL_Rect **resolutions = NULL;
88 // statics/globals (internal only) ------------------------------------------
92 #pragma warning(disable: 4273)
95 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
96 #define GL_FUNC(ret,fn,params,call,rt) \
98 static ret (GLAPIENTRY *p##fn) params = NULL; \
99 ret GLAPIENTRY fn params { rt p##fn call; } \
103 #endif // __MINGW32__
109 static bool lookup_glsym(const char *funcname, void **func)
111 *func = SDL_GL_GetProcAddress(funcname);
113 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
119 static bool lookup_all_glsyms(void)
122 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
123 #define GL_FUNC(ret,fn,params,call,rt) \
124 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
127 #endif // __MINGW32__
131 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
139 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
146 Boolean gDone = false;
148 static int _argc = 0;
149 static char **_argv = NULL;
151 bool cmdline(const char *cmd)
153 for (int i = 1; i < _argc; i++) {
154 char *arg = _argv[i];
157 if (strcasecmp(arg, cmd) == 0)
164 //-----------------------------------------------------------------------------------------------------------------------
170 glClear( GL_COLOR_BUFFER_BIT );
174 glDisable( GL_ALPHA_TEST);
175 glDisable( GL_BLEND);
176 glDisable( GL_DEPTH_TEST);
177 //glDisable( GL_DITHER);
179 glDisable( GL_LIGHTING);
180 glDisable( GL_LOGIC_OP);
181 glDisable( GL_TEXTURE_1D);
182 glDisable( GL_TEXTURE_2D);
183 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
184 glPixelTransferi( GL_RED_SCALE, 1);
185 glPixelTransferi( GL_RED_BIAS, 0);
186 glPixelTransferi( GL_GREEN_SCALE, 1);
187 glPixelTransferi( GL_GREEN_BIAS, 0);
188 glPixelTransferi( GL_BLUE_SCALE, 1);
189 glPixelTransferi( GL_BLUE_BIAS, 0);
190 glPixelTransferi( GL_ALPHA_SCALE, 1);
191 glPixelTransferi( GL_ALPHA_BIAS, 0);
193 // set initial rendering states
194 glShadeModel( GL_SMOOTH);
196 glDepthFunc( GL_LEQUAL);
197 glDepthMask( GL_TRUE);
198 //glDepthRange( FRONT_CLIP, BACK_CLIP);
199 glEnable( GL_DEPTH_TEST);
200 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
201 glCullFace( GL_FRONT);
202 glEnable( GL_CULL_FACE);
203 glEnable( GL_LIGHTING);
204 //glEnable( GL_LIGHT_MODEL_AMBIENT);
205 glEnable( GL_DITHER);
206 glEnable( GL_COLOR_MATERIAL);
207 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
208 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
209 glAlphaFunc( GL_GREATER, 0.5f);
211 if ( CanInitStereo(stereomode) ) {
212 InitStereo(stereomode);
214 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
215 stereomode = stereoNone;
219 static void toggleFullscreen()
221 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
222 if (flags & SDL_WINDOW_FULLSCREEN) {
223 flags &= ~SDL_WINDOW_FULLSCREEN;
225 flags |= SDL_WINDOW_FULLSCREEN;
227 SDL_SetWindowFullscreen(sdlwindow, flags);
230 static SDL_bool sdlEventProc(const SDL_Event &e)
236 case SDL_WINDOWEVENT:
237 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
242 case SDL_MOUSEMOTION:
243 deltah += e.motion.xrel;
244 deltav += e.motion.yrel;
248 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
249 (e.key.keysym.mod & KMOD_CTRL)) {
250 SDL_bool mode = SDL_TRUE;
251 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
252 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
253 SDL_SetWindowGrab(sdlwindow, mode);
254 SDL_SetRelativeMouseMode(mode);
255 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
265 // --------------------------------------------------------------------------
267 static Point gMidPoint;
283 const int displayIdx = 0; // !!! FIXME: other monitors?
285 if (!SDL_WasInit(SDL_INIT_VIDEO))
286 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
287 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
290 if (!LoadSettings()) {
291 fprintf(stderr, "Failed to load config, creating default\n");
294 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
298 if (SDL_GL_LoadLibrary(NULL) == -1) {
299 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
305 const int nummodes = SDL_GetNumDisplayModes(displayIdx);
306 for (int i = 0; i < nummodes; i++)
308 SDL_DisplayMode mode;
309 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
311 if ((mode.w < 640) || (mode.h < 480))
312 continue; // sane lower limit.
317 const std::string error = "No suitable video resolutions found.";
318 cerr << error << endl;
319 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
324 static SDL_Rect *resolutions_block = NULL;
325 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
326 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
327 if ((resolutions_block == NULL) || (resolutions == NULL)) {
329 fprintf(stderr, "Out of memory!\n");
333 resolutions[count--] = NULL;
334 for (int i = 0; count >= 0; i++, count--) {
335 /* FIXME - Pretty sure this should use nummodes and not count */
336 SDL_DisplayMode mode;
337 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
339 if ((mode.w < 640) || (mode.h < 480))
340 continue; // sane lower limit.
341 resolutions_block[count].x = resolutions_block[count].y = 0;
342 resolutions_block[count].w = mode.w;
343 resolutions_block[count].h = mode.h;
344 resolutions[count] = &resolutions_block[count];
347 if (cmdline("showresolutions")) {
348 printf("Resolutions we think are okay:\n");
349 for (int i = 0; resolutions[i]; i++)
350 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
353 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
354 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
356 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
357 if (!cmdline("windowed"))
358 sdlflags |= SDL_WINDOW_FULLSCREEN;
359 if (!cmdline("nomousegrab"))
360 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
362 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx),
363 kContextWidth, kContextHeight, sdlflags);
366 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
367 fprintf(stderr, "forcing 640x480...\n");
369 kContextHeight = 480;
370 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx),
371 kContextWidth, kContextHeight, sdlflags);
373 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
374 fprintf(stderr, "forcing 640x480 windowed mode...\n");
375 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
376 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx),
377 kContextWidth, kContextHeight, sdlflags);
380 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
386 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
388 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
393 SDL_GL_MakeCurrent(sdlwindow, glctx);
395 if (!lookup_all_glsyms()) {
396 fprintf(stderr, "Missing required OpenGL functions.\n");
402 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
404 fprintf(stderr, "Failed to get a double-buffered context.\n");
409 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
410 SDL_GL_SetSwapInterval(1);
413 if (!cmdline("nomousegrab"))
414 SDL_SetRelativeMouseMode(SDL_TRUE);
418 GLint width = kContextWidth;
419 GLint height = kContextHeight;
420 gMidPoint.h = width / 2;
421 gMidPoint.v = height / 2;
423 screenheight = height;
426 newscreenwidth = screenwidth;
427 newscreenheight = screenheight;
435 static void DoMouse()
438 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
439 deltah *= usermousesensitivity;
440 deltav *= usermousesensitivity;
441 mousecoordh += deltah;
442 mousecoordv += deltav;
445 else if (mousecoordh >= kContextWidth)
446 mousecoordh = kContextWidth - 1;
449 else if (mousecoordv >= kContextHeight)
450 mousecoordv = kContextHeight - 1;
455 void DoFrameRate (int update)
457 static long frames = 0;
459 static AbsoluteTime time = {0, 0};
460 static AbsoluteTime frametime = {0, 0};
461 AbsoluteTime currTime = UpTime ();
462 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
464 if (0 > deltaTime) // if negative microseconds
465 deltaTime /= -1000000.0;
466 else // else milliseconds
469 multiplier = deltaTime;
470 if (multiplier < .001)
475 frametime = currTime; // reset for next time interval
477 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
479 if (0 > deltaTime) // if negative microseconds
480 deltaTime /= -1000000.0;
481 else // else milliseconds
484 if (0.001 <= deltaTime) { // has update interval passed
486 time = currTime; // reset for next time interval
495 static float sps = 200;
497 static float oldmult;
503 fps = 1 / multiplier;
505 count = multiplier * sps;
509 realmultiplier = multiplier;
510 multiplier *= gamespeed;
517 multiplier *= .00001;
518 if (slomo && !mainmenu)
519 multiplier *= slomospeed;
520 oldmult = multiplier;
521 multiplier /= (float)count;
527 for (int i = 0; i < count; i++) {
530 multiplier = oldmult;
533 /* - Debug code to test how many channels were active on average per frame
534 static long frames = 0;
536 static AbsoluteTime start = {0,0};
537 AbsoluteTime currTime = UpTime ();
538 static int num_channels = 0;
540 num_channels += OPENAL_GetChannelsPlaying();
541 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
543 if (0 > deltaTime) // if negative microseconds
544 deltaTime /= -1000000.0;
545 else // else milliseconds
553 float avg_channels = (float)num_channels / (float)frames;
555 ofstream opstream("log.txt",ios::app);
556 opstream << "Average frame count: ";
558 opstream << " frames - ";
559 opstream << avg_channels;
560 opstream << " per frame.\n";
567 if ( stereomode == stereoNone ) {
568 DrawGLScene(stereoCenter);
570 DrawGLScene(stereoLeft);
571 DrawGLScene(stereoRight);
575 // --------------------------------------------------------------------------
583 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
584 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
587 // cheat here...static destructors are calling glDeleteTexture() after
588 // the context is destroyed and libGL unloaded by SDL_Quit().
589 pglDeleteTextures = glDeleteTextures_doNothing;
590 #endif // __MINGW32__
594 // --------------------------------------------------------------------------
596 static bool IsFocused()
598 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
604 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
605 static char *findBinaryInPath(const char *bin, char *envr)
607 size_t alloc_size = 0;
614 ptr = strchr(start, ':'); /* find next $PATH separator. */
618 size = strlen(start) + strlen(bin) + 2;
619 if (size > alloc_size) {
620 char *x = (char *) realloc(exe, size);
631 /* build full binary path... */
633 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
637 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
638 strcpy(exe, start); /* i'm lazy. piss off. */
642 start = ptr + 1; /* start points to beginning of next element. */
643 } while (ptr != NULL);
648 return(NULL); /* doesn't exist in path. */
649 } /* findBinaryInPath */
652 char *calcBaseDir(const char *argv0)
654 /* If there isn't a path on argv0, then look through the $PATH for it. */
658 const char *ptr = strrchr((char *)argv0, '/');
659 if (strchr(argv0, '/')) {
660 retval = strdup(argv0);
662 *((char *) strrchr(retval, '/')) = '\0';
666 envr = getenv("PATH");
672 retval = findBinaryInPath(argv0, envr);
677 static inline void chdirToAppPath(const char *argv0)
679 char *dir = calcBaseDir(argv0);
681 #if (defined(__APPLE__) && defined(__MACH__))
682 // Chop off /Contents/MacOS if it's at the end of the string, so we
683 // land in the base of the app bundle.
684 const size_t len = strlen(dir);
685 const char *bundledirs = "/Contents/MacOS";
686 const size_t bundledirslen = strlen(bundledirs);
687 if (len > bundledirslen) {
688 char *ptr = (dir + len) - bundledirslen;
689 if (strcasecmp(ptr, bundledirs) == 0)
700 int main(int argc, char **argv)
705 // !!! FIXME: we could use a Win32 API for this. --ryan.
707 chdirToAppPath(argv[0]);
716 //ofstream os("error.txt");
718 //ofstream os("log.txt");
724 while (!gDone && !tryquit) {
728 // check windows messages
735 while ( SDL_PollEvent( &e ) ) {
736 if (!sdlEventProc(e)) {
747 // allow game chance to pause
752 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
763 } catch (const std::exception& error) {
766 std::string e = "Caught exception: ";
771 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
781 // --------------------------------------------------------------------------
784 bool LoadImage(const char * fname, TGAImageRec & tex)
786 if ( tex.data == NULL )
789 return load_image(fname, tex);
792 void ScreenShot(const char * fname)
799 static bool load_image(const char *file_name, TGAImageRec &tex)
801 const char *ptr = strrchr((char *)file_name, '.');
803 if (strcasecmp(ptr + 1, "png") == 0)
804 return load_png(file_name, tex);
805 else if (strcasecmp(ptr + 1, "jpg") == 0)
806 return load_jpg(file_name, tex);
809 STUBBED("Unsupported image type");
814 struct my_error_mgr {
815 struct jpeg_error_mgr pub; /* "public" fields */
816 jmp_buf setjmp_buffer; /* for return to caller */
818 typedef struct my_error_mgr * my_error_ptr;
821 static void my_error_exit(j_common_ptr cinfo)
823 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
824 longjmp(err->setjmp_buffer, 1);
827 /* stolen from public domain example.c code in libjpg distribution. */
828 static bool load_jpg(const char *file_name, TGAImageRec &tex)
830 struct jpeg_decompress_struct cinfo;
831 struct my_error_mgr jerr;
832 JSAMPROW buffer[1]; /* Output row buffer */
833 int row_stride; /* physical row width in output buffer */
834 FILE *infile = fopen(file_name, "rb");
839 cinfo.err = jpeg_std_error(&jerr.pub);
840 jerr.pub.error_exit = my_error_exit;
841 if (setjmp(jerr.setjmp_buffer)) {
842 jpeg_destroy_decompress(&cinfo);
847 jpeg_create_decompress(&cinfo);
848 jpeg_stdio_src(&cinfo, infile);
849 (void) jpeg_read_header(&cinfo, TRUE);
851 cinfo.out_color_space = JCS_RGB;
852 cinfo.quantize_colors = 0;
853 (void) jpeg_calc_output_dimensions(&cinfo);
854 (void) jpeg_start_decompress(&cinfo);
856 row_stride = cinfo.output_width * cinfo.output_components;
857 tex.sizeX = cinfo.output_width;
858 tex.sizeY = cinfo.output_height;
861 while (cinfo.output_scanline < cinfo.output_height) {
862 buffer[0] = (JSAMPROW)(char *)tex.data +
863 ((cinfo.output_height - 1) - cinfo.output_scanline) * row_stride;
864 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
867 (void) jpeg_finish_decompress(&cinfo);
868 jpeg_destroy_decompress(&cinfo);
875 /* stolen from public domain example.c code in libpng distribution. */
876 static bool load_png(const char *file_name, TGAImageRec &tex)
878 bool hasalpha = false;
879 png_structp png_ptr = NULL;
880 png_infop info_ptr = NULL;
881 png_uint_32 width, height;
882 int bit_depth, color_type, interlace_type;
883 png_byte **rows = NULL;
885 png_byte **row_pointers = NULL;
886 FILE *fp = fopen(file_name, "rb");
889 cerr << file_name << " not found" << endl;
893 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
897 info_ptr = png_create_info_struct(png_ptr);
898 if (info_ptr == NULL)
901 if (setjmp(png_jmpbuf(png_ptr)))
904 png_init_io(png_ptr, fp);
905 png_read_png(png_ptr, info_ptr,
906 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
908 png_get_IHDR(png_ptr, info_ptr, &width, &height,
909 &bit_depth, &color_type, &interlace_type, NULL, NULL);
911 if (bit_depth != 8) // transform SHOULD handle this...
914 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
917 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
920 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
921 row_pointers = png_get_rows(png_ptr, info_ptr);
926 png_byte *dst = tex.data;
927 for (int i = height - 1; i >= 0; i--) {
928 png_byte *src = row_pointers[i];
929 for (int j = 0; j < width; j++) {
941 png_byte *dst = tex.data;
942 int pitch = width * 4;
943 for (int i = height - 1; i >= 0; i--, dst += pitch)
944 memcpy(dst, row_pointers[i], pitch);
954 cerr << "There was a problem loading " << file_name << endl;
956 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
963 bool save_image(const char *file_name)
965 const char *ptr = strrchr((char *)file_name, '.');
967 if (strcasecmp(ptr + 1, "png") == 0)
968 return save_png(file_name);
971 STUBBED("Unsupported image type");
976 static bool save_png(const char *file_name)
979 png_structp png_ptr = NULL;
980 png_infop info_ptr = NULL;
983 fp = fopen(file_name, "wb");
987 png_bytep *row_pointers = new png_bytep[kContextHeight];
988 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
989 if ((!screenshot) || (!row_pointers))
993 glReadPixels(0, 0, kContextWidth, kContextHeight,
994 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
995 if (glGetError() != GL_NO_ERROR)
998 for (int i = 0; i < kContextHeight; i++)
999 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight - 1) - i)) * 3);
1001 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1002 if (png_ptr == NULL)
1005 info_ptr = png_create_info_struct(png_ptr);
1006 if (info_ptr == NULL)
1009 if (setjmp(png_jmpbuf(png_ptr)))
1012 png_init_io(png_ptr, fp);
1014 if (setjmp(png_jmpbuf(png_ptr)))
1017 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1018 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1019 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1021 png_write_info(png_ptr, info_ptr);
1023 if (setjmp(png_jmpbuf(png_ptr)))
1026 png_write_image(png_ptr, row_pointers);
1028 if (setjmp(png_jmpbuf(png_ptr)))
1031 png_write_end(png_ptr, NULL);
1035 png_destroy_write_struct(&png_ptr, &info_ptr);
1036 delete[] screenshot;
1037 delete[] row_pointers;
1041 unlink(ConvertFileName(file_name));