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 #define GL_FUNC(ret,fn,params,call,rt) \
97 static ret (GLAPIENTRY *p##fn) params = NULL; \
98 ret GLAPIENTRY fn params { rt p##fn call; } \
107 static bool lookup_glsym(const char *funcname, void **func)
109 *func = SDL_GL_GetProcAddress(funcname);
111 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
117 static bool lookup_all_glsyms(void)
120 #define GL_FUNC(ret,fn,params,call,rt) \
121 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
127 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
135 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
142 Boolean gDone = false;
144 static int _argc = 0;
145 static char **_argv = NULL;
147 bool cmdline(const char *cmd)
149 for (int i = 1; i < _argc; i++) {
150 char *arg = _argv[i];
153 if (strcasecmp(arg, cmd) == 0)
160 //-----------------------------------------------------------------------------------------------------------------------
166 glClear( GL_COLOR_BUFFER_BIT );
170 glDisable( GL_ALPHA_TEST);
171 glDisable( GL_BLEND);
172 glDisable( GL_DEPTH_TEST);
173 //glDisable( GL_DITHER);
175 glDisable( GL_LIGHTING);
176 glDisable( GL_LOGIC_OP);
177 glDisable( GL_TEXTURE_1D);
178 glDisable( GL_TEXTURE_2D);
179 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
180 glPixelTransferi( GL_RED_SCALE, 1);
181 glPixelTransferi( GL_RED_BIAS, 0);
182 glPixelTransferi( GL_GREEN_SCALE, 1);
183 glPixelTransferi( GL_GREEN_BIAS, 0);
184 glPixelTransferi( GL_BLUE_SCALE, 1);
185 glPixelTransferi( GL_BLUE_BIAS, 0);
186 glPixelTransferi( GL_ALPHA_SCALE, 1);
187 glPixelTransferi( GL_ALPHA_BIAS, 0);
189 // set initial rendering states
190 glShadeModel( GL_SMOOTH);
192 glDepthFunc( GL_LEQUAL);
193 glDepthMask( GL_TRUE);
194 //glDepthRange( FRONT_CLIP, BACK_CLIP);
195 glEnable( GL_DEPTH_TEST);
196 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
197 glCullFace( GL_FRONT);
198 glEnable( GL_CULL_FACE);
199 glEnable( GL_LIGHTING);
200 //glEnable( GL_LIGHT_MODEL_AMBIENT);
201 glEnable( GL_DITHER);
202 glEnable( GL_COLOR_MATERIAL);
203 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
204 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
205 glAlphaFunc( GL_GREATER, 0.5f);
207 if ( CanInitStereo(stereomode) ) {
208 InitStereo(stereomode);
210 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
211 stereomode = stereoNone;
215 static void toggleFullscreen()
217 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
218 if (flags & SDL_WINDOW_FULLSCREEN) {
219 flags &= ~SDL_WINDOW_FULLSCREEN;
221 flags |= SDL_WINDOW_FULLSCREEN;
223 SDL_SetWindowFullscreen(sdlwindow, flags);
226 static SDL_bool sdlEventProc(const SDL_Event &e)
232 case SDL_WINDOWEVENT:
233 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
238 case SDL_MOUSEMOTION:
239 deltah += e.motion.xrel;
240 deltav += e.motion.yrel;
244 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
245 (e.key.keysym.mod & KMOD_CTRL)) {
246 SDL_bool mode = SDL_TRUE;
247 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
248 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
249 SDL_SetWindowGrab(sdlwindow, mode);
250 SDL_SetRelativeMouseMode(mode);
251 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
261 // --------------------------------------------------------------------------
263 static Point gMidPoint;
279 const int displayIdx = 0; // !!! FIXME: other monitors?
281 if (!SDL_WasInit(SDL_INIT_VIDEO))
282 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
283 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
286 if (!LoadSettings()) {
287 fprintf(stderr, "Failed to load config, creating default\n");
290 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
294 if (SDL_GL_LoadLibrary(NULL) == -1) {
295 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
301 const int nummodes = SDL_GetNumDisplayModes(displayIdx);
302 for (int i = 0; i < nummodes; i++)
304 SDL_DisplayMode mode;
305 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
307 if ((mode.w < 640) || (mode.h < 480))
308 continue; // sane lower limit.
313 const std::string error = "No suitable video resolutions found.";
314 cerr << error << endl;
315 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
320 static SDL_Rect *resolutions_block = NULL;
321 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
322 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
323 if ((resolutions_block == NULL) || (resolutions == NULL)) {
325 fprintf(stderr, "Out of memory!\n");
329 resolutions[count--] = NULL;
330 for (int i = 0; count >= 0; i++, count--) {
331 /* FIXME - Pretty sure this should use nummodes and not count */
332 SDL_DisplayMode mode;
333 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
335 if ((mode.w < 640) || (mode.h < 480))
336 continue; // sane lower limit.
337 resolutions_block[count].x = resolutions_block[count].y = 0;
338 resolutions_block[count].w = mode.w;
339 resolutions_block[count].h = mode.h;
340 resolutions[count] = &resolutions_block[count];
343 if (cmdline("showresolutions")) {
344 printf("Resolutions we think are okay:\n");
345 for (int i = 0; resolutions[i]; i++)
346 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
349 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
350 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
352 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
353 if (!cmdline("windowed"))
354 sdlflags |= SDL_WINDOW_FULLSCREEN;
355 if (!cmdline("nomousegrab"))
356 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
358 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx),
359 kContextWidth, kContextHeight, sdlflags);
362 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
363 fprintf(stderr, "forcing 640x480...\n");
365 kContextHeight = 480;
366 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx),
367 kContextWidth, kContextHeight, sdlflags);
369 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
370 fprintf(stderr, "forcing 640x480 windowed mode...\n");
371 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
372 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx),
373 kContextWidth, kContextHeight, sdlflags);
376 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
382 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
384 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
389 SDL_GL_MakeCurrent(sdlwindow, glctx);
391 if (!lookup_all_glsyms()) {
392 fprintf(stderr, "Missing required OpenGL functions.\n");
398 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
400 fprintf(stderr, "Failed to get a double-buffered context.\n");
405 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
406 SDL_GL_SetSwapInterval(1);
409 SDL_SetWindowGrab(sdlwindow, SDL_TRUE);
410 SDL_SetRelativeMouseMode(SDL_TRUE);
415 GLint width = kContextWidth;
416 GLint height = kContextHeight;
417 gMidPoint.h = width / 2;
418 gMidPoint.v = height / 2;
420 screenheight = height;
423 newscreenwidth = screenwidth;
424 newscreenheight = screenheight;
432 static void DoMouse()
435 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
436 deltah *= usermousesensitivity;
437 deltav *= usermousesensitivity;
438 mousecoordh += deltah;
439 mousecoordv += deltav;
442 else if (mousecoordh >= kContextWidth)
443 mousecoordh = kContextWidth - 1;
446 else if (mousecoordv >= kContextHeight)
447 mousecoordv = kContextHeight - 1;
452 void DoFrameRate (int update)
454 static long frames = 0;
456 static AbsoluteTime time = {0, 0};
457 static AbsoluteTime frametime = {0, 0};
458 AbsoluteTime currTime = UpTime ();
459 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
461 if (0 > deltaTime) // if negative microseconds
462 deltaTime /= -1000000.0;
463 else // else milliseconds
466 multiplier = deltaTime;
467 if (multiplier < .001)
472 frametime = currTime; // reset for next time interval
474 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
476 if (0 > deltaTime) // if negative microseconds
477 deltaTime /= -1000000.0;
478 else // else milliseconds
481 if (0.001 <= deltaTime) { // has update interval passed
483 time = currTime; // reset for next time interval
492 static float sps = 200;
494 static float oldmult;
500 fps = 1 / multiplier;
502 count = multiplier * sps;
506 realmultiplier = multiplier;
507 multiplier *= gamespeed;
514 multiplier *= .00001;
515 if (slomo && !mainmenu)
516 multiplier *= slomospeed;
517 oldmult = multiplier;
518 multiplier /= (float)count;
524 for (int i = 0; i < count; i++) {
527 multiplier = oldmult;
530 /* - Debug code to test how many channels were active on average per frame
531 static long frames = 0;
533 static AbsoluteTime start = {0,0};
534 AbsoluteTime currTime = UpTime ();
535 static int num_channels = 0;
537 num_channels += OPENAL_GetChannelsPlaying();
538 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
540 if (0 > deltaTime) // if negative microseconds
541 deltaTime /= -1000000.0;
542 else // else milliseconds
550 float avg_channels = (float)num_channels / (float)frames;
552 ofstream opstream("log.txt",ios::app);
553 opstream << "Average frame count: ";
555 opstream << " frames - ";
556 opstream << avg_channels;
557 opstream << " per frame.\n";
564 if ( stereomode == stereoNone ) {
565 DrawGLScene(stereoCenter);
567 DrawGLScene(stereoLeft);
568 DrawGLScene(stereoRight);
572 // --------------------------------------------------------------------------
580 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
583 // cheat here...static destructors are calling glDeleteTexture() after
584 // the context is destroyed and libGL unloaded by SDL_Quit().
585 pglDeleteTextures = glDeleteTextures_doNothing;
589 // --------------------------------------------------------------------------
591 static bool IsFocused()
593 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
599 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
600 static char *findBinaryInPath(const char *bin, char *envr)
602 size_t alloc_size = 0;
609 ptr = strchr(start, ':'); /* find next $PATH separator. */
613 size = strlen(start) + strlen(bin) + 2;
614 if (size > alloc_size) {
615 char *x = (char *) realloc(exe, size);
626 /* build full binary path... */
628 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
632 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
633 strcpy(exe, start); /* i'm lazy. piss off. */
637 start = ptr + 1; /* start points to beginning of next element. */
638 } while (ptr != NULL);
643 return(NULL); /* doesn't exist in path. */
644 } /* findBinaryInPath */
647 char *calcBaseDir(const char *argv0)
649 /* If there isn't a path on argv0, then look through the $PATH for it. */
653 const char *ptr = strrchr((char *)argv0, '/');
654 if (strchr(argv0, '/')) {
655 retval = strdup(argv0);
657 *((char *) strrchr(retval, '/')) = '\0';
661 envr = getenv("PATH");
667 retval = findBinaryInPath(argv0, envr);
672 static inline void chdirToAppPath(const char *argv0)
674 char *dir = calcBaseDir(argv0);
676 #if (defined(__APPLE__) && defined(__MACH__))
677 // Chop off /Contents/MacOS if it's at the end of the string, so we
678 // land in the base of the app bundle.
679 const size_t len = strlen(dir);
680 const char *bundledirs = "/Contents/MacOS";
681 const size_t bundledirslen = strlen(bundledirs);
682 if (len > bundledirslen) {
683 char *ptr = (dir + len) - bundledirslen;
684 if (strcasecmp(ptr, bundledirs) == 0)
695 int main(int argc, char **argv)
700 // !!! FIXME: we could use a Win32 API for this. --ryan.
702 chdirToAppPath(argv[0]);
711 //ofstream os("error.txt");
713 //ofstream os("log.txt");
719 while (!gDone && !tryquit) {
723 // check windows messages
730 while ( SDL_PollEvent( &e ) ) {
731 if (!sdlEventProc(e)) {
742 // allow game chance to pause
747 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
758 } catch (const std::exception& error) {
761 std::string e = "Caught exception: ";
766 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
776 // --------------------------------------------------------------------------
779 bool LoadImage(const char * fname, TGAImageRec & tex)
781 if ( tex.data == NULL )
784 return load_image(fname, tex);
787 void ScreenShot(const char * fname)
794 static bool load_image(const char *file_name, TGAImageRec &tex)
796 const char *ptr = strrchr((char *)file_name, '.');
798 if (strcasecmp(ptr + 1, "png") == 0)
799 return load_png(file_name, tex);
800 else if (strcasecmp(ptr + 1, "jpg") == 0)
801 return load_jpg(file_name, tex);
804 STUBBED("Unsupported image type");
809 struct my_error_mgr {
810 struct jpeg_error_mgr pub; /* "public" fields */
811 jmp_buf setjmp_buffer; /* for return to caller */
813 typedef struct my_error_mgr * my_error_ptr;
816 static void my_error_exit(j_common_ptr cinfo)
818 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
819 longjmp(err->setjmp_buffer, 1);
822 /* stolen from public domain example.c code in libjpg distribution. */
823 static bool load_jpg(const char *file_name, TGAImageRec &tex)
825 struct jpeg_decompress_struct cinfo;
826 struct my_error_mgr jerr;
827 JSAMPROW buffer[1]; /* Output row buffer */
828 int row_stride; /* physical row width in output buffer */
829 FILE *infile = fopen(file_name, "rb");
834 cinfo.err = jpeg_std_error(&jerr.pub);
835 jerr.pub.error_exit = my_error_exit;
836 if (setjmp(jerr.setjmp_buffer)) {
837 jpeg_destroy_decompress(&cinfo);
842 jpeg_create_decompress(&cinfo);
843 jpeg_stdio_src(&cinfo, infile);
844 (void) jpeg_read_header(&cinfo, TRUE);
846 cinfo.out_color_space = JCS_RGB;
847 cinfo.quantize_colors = 0;
848 (void) jpeg_calc_output_dimensions(&cinfo);
849 (void) jpeg_start_decompress(&cinfo);
851 row_stride = cinfo.output_width * cinfo.output_components;
852 tex.sizeX = cinfo.output_width;
853 tex.sizeY = cinfo.output_height;
856 while (cinfo.output_scanline < cinfo.output_height) {
857 buffer[0] = (JSAMPROW)(char *)tex.data +
858 ((cinfo.output_height - 1) - cinfo.output_scanline) * row_stride;
859 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
862 (void) jpeg_finish_decompress(&cinfo);
863 jpeg_destroy_decompress(&cinfo);
870 /* stolen from public domain example.c code in libpng distribution. */
871 static bool load_png(const char *file_name, TGAImageRec &tex)
873 bool hasalpha = false;
874 png_structp png_ptr = NULL;
875 png_infop info_ptr = NULL;
876 png_uint_32 width, height;
877 int bit_depth, color_type, interlace_type;
878 png_byte **rows = NULL;
880 png_byte **row_pointers = NULL;
881 FILE *fp = fopen(file_name, "rb");
884 cerr << file_name << " not found" << endl;
888 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
892 info_ptr = png_create_info_struct(png_ptr);
893 if (info_ptr == NULL)
896 if (setjmp(png_jmpbuf(png_ptr)))
899 png_init_io(png_ptr, fp);
900 png_read_png(png_ptr, info_ptr,
901 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
903 png_get_IHDR(png_ptr, info_ptr, &width, &height,
904 &bit_depth, &color_type, &interlace_type, NULL, NULL);
906 if (bit_depth != 8) // transform SHOULD handle this...
909 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
912 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
915 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
916 row_pointers = png_get_rows(png_ptr, info_ptr);
921 png_byte *dst = tex.data;
922 for (int i = height - 1; i >= 0; i--) {
923 png_byte *src = row_pointers[i];
924 for (int j = 0; j < width; j++) {
936 png_byte *dst = tex.data;
937 int pitch = width * 4;
938 for (int i = height - 1; i >= 0; i--, dst += pitch)
939 memcpy(dst, row_pointers[i], pitch);
949 cerr << "There was a problem loading " << file_name << endl;
951 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
958 bool save_image(const char *file_name)
960 const char *ptr = strrchr((char *)file_name, '.');
962 if (strcasecmp(ptr + 1, "png") == 0)
963 return save_png(file_name);
966 STUBBED("Unsupported image type");
971 static bool save_png(const char *file_name)
974 png_structp png_ptr = NULL;
975 png_infop info_ptr = NULL;
978 fp = fopen(file_name, "wb");
982 png_bytep *row_pointers = new png_bytep[kContextHeight];
983 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
984 if ((!screenshot) || (!row_pointers))
988 glReadPixels(0, 0, kContextWidth, kContextHeight,
989 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
990 if (glGetError() != GL_NO_ERROR)
993 for (int i = 0; i < kContextHeight; i++)
994 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight - 1) - i)) * 3);
996 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1000 info_ptr = png_create_info_struct(png_ptr);
1001 if (info_ptr == NULL)
1004 if (setjmp(png_jmpbuf(png_ptr)))
1007 png_init_io(png_ptr, fp);
1009 if (setjmp(png_jmpbuf(png_ptr)))
1012 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1013 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1014 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1016 png_write_info(png_ptr, info_ptr);
1018 if (setjmp(png_jmpbuf(png_ptr)))
1021 png_write_image(png_ptr, row_pointers);
1023 if (setjmp(png_jmpbuf(png_ptr)))
1026 png_write_end(png_ptr, NULL);
1030 png_destroy_write_struct(&png_ptr, &info_ptr);
1031 delete[] screenshot;
1032 delete[] row_pointers;
1036 unlink(ConvertFileName(file_name));