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.
24 #define UINT8 WIN32API_UINT8
25 #define UINT16 WIN32API_UINT16
26 #define boolean WIN32API_boolean
40 #define INT32 INT32_jpeg
48 static bool load_image(const char * fname, TGAImageRec & tex);
49 static bool load_png(const char * fname, TGAImageRec & tex);
50 static bool load_jpg(const char * fname, TGAImageRec & tex);
51 bool save_image(const char * fname);
52 static bool save_png(const char * fname);
55 #include "openal_wrapper.h"
59 #pragma comment(lib, "opengl32.lib")
60 #pragma comment(lib, "glu32.lib")
61 #pragma comment(lib, "glaux.lib")
64 extern float multiplier;
66 extern float realmultiplier;
68 extern bool cellophane;
69 extern float terraindetail;
70 extern float texdetail;
73 extern int numplayers;
75 extern Person player[maxplayers];
76 extern bool stillloading;
78 /*extern*/ bool gameFocused;
80 extern float slomospeed;
81 extern float slomofreq;
91 #include "MacCompatibility.h"
96 #include "win-res/resource.h"
101 SDL_Rect **resolutions = NULL;
102 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
103 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
104 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
105 static SDL_Rect *hardcoded_resolutions[] = {
112 void DrawGL(Game & game);
114 Boolean SetUp (Game & game);
115 void DoUpdate (Game & game);
119 // statics/globals (internal only) ------------------------------------------
122 #pragma warning(push)
123 #pragma warning(disable: 4273)
126 #define GL_FUNC(ret,fn,params,call,rt) \
128 static ret (GLAPIENTRY *p##fn) params = NULL; \
129 ret GLAPIENTRY fn params { rt p##fn call; } \
138 static bool lookup_glsym(const char *funcname, void **func)
140 *func = SDL_GL_GetProcAddress(funcname);
143 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
149 static bool lookup_all_glsyms(void)
152 #define GL_FUNC(ret,fn,params,call,rt) \
153 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
159 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
167 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
174 Boolean gDone = false;
179 static int _argc = 0;
180 static char **_argv = NULL;
183 bool cmdline(const char *cmd)
185 for (int i = 1; i < _argc; i++)
187 char *arg = _argv[i];
190 if (strcasecmp(arg, cmd) == 0)
197 //-----------------------------------------------------------------------------------------------------------------------
201 static void sdlEventProc(const SDL_Event &e, Game &game)
205 case SDL_MOUSEMOTION:
206 game.deltah += e.motion.xrel;
207 game.deltav += e.motion.yrel;
211 if ((e.key.keysym.sym == SDLK_g) &&
212 (e.key.keysym.mod & KMOD_CTRL) &&
213 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
214 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
215 } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
216 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
223 // --------------------------------------------------------------------------
225 static Point gMidPoint;
227 Boolean SetUp (Game & game)
241 DefaultSettings(game);
243 if (!SDL_WasInit(SDL_INIT_VIDEO))
244 if (SDL_Init(SDL_INIT_VIDEO) == -1)
246 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
249 if(!LoadSettings(game)) {
250 fprintf(stderr, "Failed to load config, creating default\n");
253 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
257 if (SDL_GL_LoadLibrary(NULL) == -1)
259 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
264 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
265 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
266 res = hardcoded_resolutions;
268 // reverse list (it was sorted biggest to smallest by SDL)...
270 for (count = 0; res[count]; count++)
272 if ((res[count]->w < 640) || (res[count]->h < 480))
273 break; // sane lower limit.
276 static SDL_Rect *resolutions_block = NULL;
277 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
278 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
279 if ((resolutions_block == NULL) || (resolutions == NULL))
282 fprintf(stderr, "Out of memory!\n");
286 resolutions[count--] = NULL;
287 for (int i = 0; count >= 0; i++, count--)
289 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
290 resolutions[count] = &resolutions_block[count];
293 if (cmdline("showresolutions"))
295 printf("Resolutions we think are okay:\n");
296 for (int i = 0; resolutions[i]; i++)
297 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
300 Uint32 sdlflags = SDL_OPENGL;
301 if (!cmdline("windowed"))
302 sdlflags |= SDL_FULLSCREEN;
304 SDL_WM_SetCaption("Lugaru", "Lugaru");
308 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
309 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
311 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
313 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
314 fprintf(stderr, "forcing 640x480...\n");
316 kContextHeight = 480;
317 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
319 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
320 fprintf(stderr, "forcing 640x480 windowed mode...\n");
321 sdlflags &= ~SDL_FULLSCREEN;
322 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
324 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
331 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
333 fprintf(stderr, "Failed to get double buffered GL context!\n");
338 if (!lookup_all_glsyms())
344 if (!cmdline("nomousegrab"))
345 SDL_WM_GrabInput(SDL_GRAB_ON);
348 glClear( GL_COLOR_BUFFER_BIT );
352 glDisable( GL_ALPHA_TEST);
353 glDisable( GL_BLEND);
354 glDisable( GL_DEPTH_TEST);
355 // glDisable( GL_DITHER);
357 glDisable( GL_LIGHTING);
358 glDisable( GL_LOGIC_OP);
359 glDisable( GL_TEXTURE_1D);
360 glDisable( GL_TEXTURE_2D);
361 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
362 glPixelTransferi( GL_RED_SCALE, 1);
363 glPixelTransferi( GL_RED_BIAS, 0);
364 glPixelTransferi( GL_GREEN_SCALE, 1);
365 glPixelTransferi( GL_GREEN_BIAS, 0);
366 glPixelTransferi( GL_BLUE_SCALE, 1);
367 glPixelTransferi( GL_BLUE_BIAS, 0);
368 glPixelTransferi( GL_ALPHA_SCALE, 1);
369 glPixelTransferi( GL_ALPHA_BIAS, 0);
371 // set initial rendering states
372 glShadeModel( GL_SMOOTH);
374 glDepthFunc( GL_LEQUAL);
375 glDepthMask( GL_TRUE);
376 // glDepthRange( FRONT_CLIP, BACK_CLIP);
377 glEnable( GL_DEPTH_TEST);
378 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
379 glCullFace( GL_FRONT);
380 glEnable( GL_CULL_FACE);
381 glEnable( GL_LIGHTING);
382 // glEnable( GL_LIGHT_MODEL_AMBIENT);
383 glEnable( GL_DITHER);
384 glEnable( GL_COLOR_MATERIAL);
385 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
386 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
387 glAlphaFunc( GL_GREATER, 0.5f);
389 GLint width = kContextWidth;
390 GLint height = kContextHeight;
391 gMidPoint.h = width / 2;
392 gMidPoint.v = height / 2;
396 game.newdetail=detail;
397 game.newscreenwidth=screenwidth;
398 game.newscreenheight=screenheight;
400 if ( CanInitStereo(stereomode) ) {
401 InitStereo(stereomode);
403 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
404 stereomode = stereoNone;
413 static void DoMouse(Game & game)
416 if(mainmenu|| ( (abs(game.deltah)<10*realmultiplier*1000) && (abs(game.deltav)<10*realmultiplier*1000) ))
418 game.deltah *= usermousesensitivity;
419 game.deltav *= usermousesensitivity;
420 game.mousecoordh += game.deltah;
421 game.mousecoordv += game.deltav;
422 if (game.mousecoordh < 0)
423 game.mousecoordh = 0;
424 else if (game.mousecoordh >= kContextWidth)
425 game.mousecoordh = kContextWidth - 1;
426 if (game.mousecoordv < 0)
427 game.mousecoordv = 0;
428 else if (game.mousecoordv >= kContextHeight)
429 game.mousecoordv = kContextHeight - 1;
434 void DoFrameRate (int update)
436 static long frames = 0;
438 static AbsoluteTime time = {0,0};
439 static AbsoluteTime frametime = {0,0};
440 AbsoluteTime currTime = UpTime ();
441 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
443 if (0 > deltaTime) // if negative microseconds
444 deltaTime /= -1000000.0;
445 else // else milliseconds
448 multiplier=deltaTime;
449 if(multiplier<.001) multiplier=.001;
450 if(multiplier>10) multiplier=10;
451 if(update) frametime = currTime; // reset for next time interval
453 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
455 if (0 > deltaTime) // if negative microseconds
456 deltaTime /= -1000000.0;
457 else // else milliseconds
460 if (0.001 <= deltaTime) // has update interval passed
463 time = currTime; // reset for next time interval
470 void DoUpdate (Game & game)
472 static float sps=200;
474 static float oldmult;
477 if(multiplier>.6)multiplier=.6;
479 game.fps=1/multiplier;
481 count = multiplier*sps;
484 realmultiplier=multiplier;
485 multiplier*=gamespeed;
486 if(difficulty==1)multiplier*=.9;
487 if(difficulty==0)multiplier*=.8;
489 if(game.loading==4)multiplier*=.00001;
490 if(slomo&&!mainmenu)multiplier*=slomospeed;
492 multiplier/=(float)count;
498 for(int i=0;i<count;i++)
504 game.TickOnceAfter();
505 /* - Debug code to test how many channels were active on average per frame
506 static long frames = 0;
508 static AbsoluteTime start = {0,0};
509 AbsoluteTime currTime = UpTime ();
510 static int num_channels = 0;
512 num_channels += OPENAL_GetChannelsPlaying();
513 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
515 if (0 > deltaTime) // if negative microseconds
516 deltaTime /= -1000000.0;
517 else // else milliseconds
525 float avg_channels = (float)num_channels / (float)frames;
527 ofstream opstream("log.txt",ios::app);
528 opstream << "Average frame count: ";
530 opstream << " frames - ";
531 opstream << avg_channels;
532 opstream << " per frame.\n";
542 // --------------------------------------------------------------------------
550 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
553 // cheat here...static destructors are calling glDeleteTexture() after
554 // the context is destroyed and libGL unloaded by SDL_Quit().
555 pglDeleteTextures = glDeleteTextures_doNothing;
559 // --------------------------------------------------------------------------
561 static bool IsFocused()
563 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
569 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
570 static char *findBinaryInPath(const char *bin, char *envr)
572 size_t alloc_size = 0;
580 ptr = strchr(start, ':'); /* find next $PATH separator. */
584 size = strlen(start) + strlen(bin) + 2;
585 if (size > alloc_size)
587 char *x = (char *) realloc(exe, size);
599 /* build full binary path... */
601 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
605 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 const char *ptr = strrchr((char *)argv0, '/');
628 if (strchr(argv0, '/'))
630 retval = strdup(argv0);
632 *((char *) strrchr(retval, '/')) = '\0';
636 envr = getenv("PATH");
637 if (!envr) return NULL;
639 if (!envr) return NULL;
640 retval = findBinaryInPath(argv0, envr);
645 static inline void chdirToAppPath(const char *argv0)
647 char *dir = calcBaseDir(argv0);
650 #if (defined(__APPLE__) && defined(__MACH__))
651 // Chop off /Contents/MacOS if it's at the end of the string, so we
652 // land in the base of the app bundle.
653 const size_t len = strlen(dir);
654 const char *bundledirs = "/Contents/MacOS";
655 const size_t bundledirslen = strlen(bundledirs);
656 if (len > bundledirslen)
658 char *ptr = (dir + len) - bundledirslen;
659 if (strcasecmp(ptr, bundledirs) == 0)
670 int main(int argc, char **argv)
677 // !!! FIXME: we could use a Win32 API for this. --ryan.
679 chdirToAppPath(argv[0]);
691 //ofstream os("error.txt");
693 //ofstream os("log.txt");
699 while (!gDone&&!game.quit&&(!game.tryquit))
705 // check windows messages
710 if(!game.isWaiting()) {
712 while( SDL_PollEvent( &e ) )
714 if( e.type == SDL_QUIT )
719 sdlEventProc(e, game);
730 // allow game chance to pause
735 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
737 SDL_WaitEvent((SDL_Event*)&evt);
738 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
740 else if (evt.type == SDL_QUIT)
745 regnow = game.registernow;
753 catch (const std::exception& error)
757 std::string e = "Caught exception: ";
762 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
772 // --------------------------------------------------------------------------
775 bool LoadImage(const char * fname, TGAImageRec & tex)
777 if ( tex.data == NULL )
780 return load_image(fname, tex);
783 void ScreenShot(const char * fname)
790 static bool load_image(const char *file_name, TGAImageRec &tex)
792 const char *ptr = strrchr((char *)file_name, '.');
795 if (strcasecmp(ptr+1, "png") == 0)
796 return load_png(file_name, tex);
797 else if (strcasecmp(ptr+1, "jpg") == 0)
798 return load_jpg(file_name, tex);
801 STUBBED("Unsupported image type");
806 struct my_error_mgr {
807 struct jpeg_error_mgr pub; /* "public" fields */
808 jmp_buf setjmp_buffer; /* for return to caller */
810 typedef struct my_error_mgr * my_error_ptr;
813 static void my_error_exit(j_common_ptr cinfo)
815 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
816 longjmp(err->setjmp_buffer, 1);
819 /* stolen from public domain example.c code in libjpg distribution. */
820 static bool load_jpg(const char *file_name, TGAImageRec &tex)
822 struct jpeg_decompress_struct cinfo;
823 struct my_error_mgr jerr;
824 JSAMPROW buffer[1]; /* Output row buffer */
825 int row_stride; /* physical row width in output buffer */
826 FILE *infile = fopen(file_name, "rb");
831 cinfo.err = jpeg_std_error(&jerr.pub);
832 jerr.pub.error_exit = my_error_exit;
833 if (setjmp(jerr.setjmp_buffer)) {
834 jpeg_destroy_decompress(&cinfo);
839 jpeg_create_decompress(&cinfo);
840 jpeg_stdio_src(&cinfo, infile);
841 (void) jpeg_read_header(&cinfo, TRUE);
843 cinfo.out_color_space = JCS_RGB;
844 cinfo.quantize_colors = 0;
845 (void) jpeg_calc_output_dimensions(&cinfo);
846 (void) jpeg_start_decompress(&cinfo);
848 row_stride = cinfo.output_width * cinfo.output_components;
849 tex.sizeX = cinfo.output_width;
850 tex.sizeY = cinfo.output_height;
853 while (cinfo.output_scanline < cinfo.output_height) {
854 buffer[0] = (JSAMPROW)(char *)tex.data +
855 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
856 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
859 (void) jpeg_finish_decompress(&cinfo);
860 jpeg_destroy_decompress(&cinfo);
867 /* stolen from public domain example.c code in libpng distribution. */
868 static bool load_png(const char *file_name, TGAImageRec &tex)
870 bool hasalpha = false;
871 png_structp png_ptr = NULL;
872 png_infop info_ptr = NULL;
873 png_uint_32 width, height;
874 int bit_depth, color_type, interlace_type;
875 png_byte **rows = NULL;
877 png_byte **row_pointers = NULL;
878 FILE *fp = fopen(file_name, "rb");
883 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
887 info_ptr = png_create_info_struct(png_ptr);
888 if (info_ptr == NULL)
891 if (setjmp(png_jmpbuf(png_ptr)))
894 png_init_io(png_ptr, fp);
895 png_read_png(png_ptr, info_ptr,
896 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
898 png_get_IHDR(png_ptr, info_ptr, &width, &height,
899 &bit_depth, &color_type, &interlace_type, NULL, NULL);
901 if (bit_depth != 8) // transform SHOULD handle this...
904 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
907 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
910 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
911 row_pointers = png_get_rows(png_ptr, info_ptr);
917 png_byte *dst = tex.data;
918 for (int i = height-1; i >= 0; i--)
920 png_byte *src = row_pointers[i];
921 for (int j = 0; j < width; j++)
935 png_byte *dst = tex.data;
936 int pitch = width * 4;
937 for (int i = height-1; i >= 0; i--, dst += pitch)
938 memcpy(dst, row_pointers[i], pitch);
947 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
954 bool save_image(const char *file_name)
956 const char *ptr = strrchr((char *)file_name, '.');
959 if (strcasecmp(ptr+1, "png") == 0)
960 return save_png(file_name);
963 STUBBED("Unsupported image type");
968 static bool save_png(const char *file_name)
971 png_structp png_ptr = NULL;
972 png_infop info_ptr = NULL;
975 fp = fopen(file_name, "wb");
979 png_bytep *row_pointers = new png_bytep[kContextHeight];
980 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
981 if ((!screenshot) || (!row_pointers))
985 glReadPixels(0, 0, kContextWidth, kContextHeight,
986 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
987 if (glGetError() != GL_NO_ERROR)
990 for (int i = 0; i < kContextHeight; i++)
991 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
993 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
997 info_ptr = png_create_info_struct(png_ptr);
998 if (info_ptr == NULL)
1001 if (setjmp(png_jmpbuf(png_ptr)))
1004 png_init_io(png_ptr, fp);
1006 if (setjmp(png_jmpbuf(png_ptr)))
1009 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1010 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1011 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1013 png_write_info(png_ptr, info_ptr);
1015 if (setjmp(png_jmpbuf(png_ptr)))
1018 png_write_image(png_ptr, row_pointers);
1020 if (setjmp(png_jmpbuf(png_ptr)))
1023 png_write_end(png_ptr, NULL);
1027 png_destroy_write_struct(&png_ptr, &info_ptr);
1028 delete[] screenshot;
1029 delete[] row_pointers;
1033 unlink(ConvertFileName(file_name));