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"
57 extern float multiplier;
59 extern float realmultiplier;
61 extern bool cellophane;
62 extern float texdetail;
66 extern bool stillloading;
68 /*extern*/ bool gameFocused;
70 extern float slomospeed;
71 extern float slomofreq;
81 #include "MacCompatibility.h"
86 #include "win-res/resource.h"
91 SDL_Rect **resolutions = NULL;
92 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
93 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
94 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
95 static SDL_Rect *hardcoded_resolutions[] = {
102 void DrawGL(Game & game);
104 Boolean SetUp (Game & game);
105 void DoUpdate (Game & game);
109 // statics/globals (internal only) ------------------------------------------
112 #pragma warning(push)
113 #pragma warning(disable: 4273)
116 #define GL_FUNC(ret,fn,params,call,rt) \
118 static ret (GLAPIENTRY *p##fn) params = NULL; \
119 ret GLAPIENTRY fn params { rt p##fn call; } \
128 static bool lookup_glsym(const char *funcname, void **func)
130 *func = SDL_GL_GetProcAddress(funcname);
133 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
139 static bool lookup_all_glsyms(void)
142 #define GL_FUNC(ret,fn,params,call,rt) \
143 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
149 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
157 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
164 Boolean gDone = false;
169 static int _argc = 0;
170 static char **_argv = NULL;
173 bool cmdline(const char *cmd)
175 for (int i = 1; i < _argc; i++)
177 char *arg = _argv[i];
180 if (strcasecmp(arg, cmd) == 0)
187 //-----------------------------------------------------------------------------------------------------------------------
191 static void sdlEventProc(const SDL_Event &e, Game &game)
195 case SDL_MOUSEMOTION:
196 game.deltah += e.motion.xrel;
197 game.deltav += e.motion.yrel;
201 if ((e.key.keysym.sym == SDLK_g) &&
202 (e.key.keysym.mod & KMOD_CTRL) &&
203 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
204 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
205 } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
206 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
213 // --------------------------------------------------------------------------
215 static Point gMidPoint;
217 Boolean SetUp (Game & game)
230 DefaultSettings(game);
232 if (!SDL_WasInit(SDL_INIT_VIDEO))
233 if (SDL_Init(SDL_INIT_VIDEO) == -1)
235 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
238 if(!LoadSettings(game)) {
239 fprintf(stderr, "Failed to load config, creating default\n");
242 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
246 if (SDL_GL_LoadLibrary(NULL) == -1)
248 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
253 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
254 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
255 res = hardcoded_resolutions;
257 // reverse list (it was sorted biggest to smallest by SDL)...
259 for (count = 0; res[count]; count++)
261 if ((res[count]->w < 640) || (res[count]->h < 480))
262 break; // sane lower limit.
265 static SDL_Rect *resolutions_block = NULL;
266 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
267 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
268 if ((resolutions_block == NULL) || (resolutions == NULL))
271 fprintf(stderr, "Out of memory!\n");
275 resolutions[count--] = NULL;
276 for (int i = 0; count >= 0; i++, count--)
278 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
279 resolutions[count] = &resolutions_block[count];
282 if (cmdline("showresolutions"))
284 printf("Resolutions we think are okay:\n");
285 for (int i = 0; resolutions[i]; i++)
286 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
289 Uint32 sdlflags = SDL_OPENGL;
290 if (!cmdline("windowed"))
291 sdlflags |= SDL_FULLSCREEN;
293 SDL_WM_SetCaption("Lugaru", "Lugaru");
297 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
298 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
299 #if SDL_VERSION_ATLEAST(1, 2, 10)
300 SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, vblsync);
303 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
305 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
306 fprintf(stderr, "forcing 640x480...\n");
308 kContextHeight = 480;
309 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
311 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
312 fprintf(stderr, "forcing 640x480 windowed mode...\n");
313 sdlflags &= ~SDL_FULLSCREEN;
314 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
316 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
323 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
325 fprintf(stderr, "Failed to get double buffered GL context!\n");
330 if (!lookup_all_glsyms())
336 if (!cmdline("nomousegrab"))
337 SDL_WM_GrabInput(SDL_GRAB_ON);
340 glClear( GL_COLOR_BUFFER_BIT );
344 glDisable( GL_ALPHA_TEST);
345 glDisable( GL_BLEND);
346 glDisable( GL_DEPTH_TEST);
347 // glDisable( GL_DITHER);
349 glDisable( GL_LIGHTING);
350 glDisable( GL_LOGIC_OP);
351 glDisable( GL_TEXTURE_1D);
352 glDisable( GL_TEXTURE_2D);
353 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
354 glPixelTransferi( GL_RED_SCALE, 1);
355 glPixelTransferi( GL_RED_BIAS, 0);
356 glPixelTransferi( GL_GREEN_SCALE, 1);
357 glPixelTransferi( GL_GREEN_BIAS, 0);
358 glPixelTransferi( GL_BLUE_SCALE, 1);
359 glPixelTransferi( GL_BLUE_BIAS, 0);
360 glPixelTransferi( GL_ALPHA_SCALE, 1);
361 glPixelTransferi( GL_ALPHA_BIAS, 0);
363 // set initial rendering states
364 glShadeModel( GL_SMOOTH);
366 glDepthFunc( GL_LEQUAL);
367 glDepthMask( GL_TRUE);
368 // glDepthRange( FRONT_CLIP, BACK_CLIP);
369 glEnable( GL_DEPTH_TEST);
370 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
371 glCullFace( GL_FRONT);
372 glEnable( GL_CULL_FACE);
373 glEnable( GL_LIGHTING);
374 // glEnable( GL_LIGHT_MODEL_AMBIENT);
375 glEnable( GL_DITHER);
376 glEnable( GL_COLOR_MATERIAL);
377 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
378 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
379 glAlphaFunc( GL_GREATER, 0.5f);
381 GLint width = kContextWidth;
382 GLint height = kContextHeight;
383 gMidPoint.h = width / 2;
384 gMidPoint.v = height / 2;
388 game.newdetail=detail;
389 game.newscreenwidth=screenwidth;
390 game.newscreenheight=screenheight;
392 if ( CanInitStereo(stereomode) ) {
393 InitStereo(stereomode);
395 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
396 stereomode = stereoNone;
405 static void DoMouse(Game & game)
408 if(mainmenu|| ( (abs(game.deltah)<10*realmultiplier*1000) && (abs(game.deltav)<10*realmultiplier*1000) ))
410 game.deltah *= usermousesensitivity;
411 game.deltav *= usermousesensitivity;
412 game.mousecoordh += game.deltah;
413 game.mousecoordv += game.deltav;
414 if (game.mousecoordh < 0)
415 game.mousecoordh = 0;
416 else if (game.mousecoordh >= kContextWidth)
417 game.mousecoordh = kContextWidth - 1;
418 if (game.mousecoordv < 0)
419 game.mousecoordv = 0;
420 else if (game.mousecoordv >= kContextHeight)
421 game.mousecoordv = kContextHeight - 1;
426 void DoFrameRate (int update)
428 static long frames = 0;
430 static AbsoluteTime time = {0,0};
431 static AbsoluteTime frametime = {0,0};
432 AbsoluteTime currTime = UpTime ();
433 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
435 if (0 > deltaTime) // if negative microseconds
436 deltaTime /= -1000000.0;
437 else // else milliseconds
440 multiplier=deltaTime;
441 if(multiplier<.001) multiplier=.001;
442 if(multiplier>10) multiplier=10;
443 if(update) frametime = currTime; // reset for next time interval
445 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
447 if (0 > deltaTime) // if negative microseconds
448 deltaTime /= -1000000.0;
449 else // else milliseconds
452 if (0.001 <= deltaTime) // has update interval passed
455 time = currTime; // reset for next time interval
462 void DoUpdate (Game & game)
464 static float sps=200;
466 static float oldmult;
469 if(multiplier>.6)multiplier=.6;
471 game.fps=1/multiplier;
473 count = multiplier*sps;
476 realmultiplier=multiplier;
477 multiplier*=gamespeed;
478 if(difficulty==1)multiplier*=.9;
479 if(difficulty==0)multiplier*=.8;
481 if(game.loading==4)multiplier*=.00001;
482 if(slomo&&!mainmenu)multiplier*=slomospeed;
484 multiplier/=(float)count;
490 for(int i=0;i<count;i++)
496 game.TickOnceAfter();
497 /* - Debug code to test how many channels were active on average per frame
498 static long frames = 0;
500 static AbsoluteTime start = {0,0};
501 AbsoluteTime currTime = UpTime ();
502 static int num_channels = 0;
504 num_channels += OPENAL_GetChannelsPlaying();
505 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
507 if (0 > deltaTime) // if negative microseconds
508 deltaTime /= -1000000.0;
509 else // else milliseconds
517 float avg_channels = (float)num_channels / (float)frames;
519 ofstream opstream("log.txt",ios::app);
520 opstream << "Average frame count: ";
522 opstream << " frames - ";
523 opstream << avg_channels;
524 opstream << " per frame.\n";
534 // --------------------------------------------------------------------------
542 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
545 // cheat here...static destructors are calling glDeleteTexture() after
546 // the context is destroyed and libGL unloaded by SDL_Quit().
547 pglDeleteTextures = glDeleteTextures_doNothing;
551 // --------------------------------------------------------------------------
553 static bool IsFocused()
555 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
561 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
562 static char *findBinaryInPath(const char *bin, char *envr)
564 size_t alloc_size = 0;
572 ptr = strchr(start, ':'); /* find next $PATH separator. */
576 size = strlen(start) + strlen(bin) + 2;
577 if (size > alloc_size)
579 char *x = (char *) realloc(exe, size);
591 /* build full binary path... */
593 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
597 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
599 strcpy(exe, start); /* i'm lazy. piss off. */
603 start = ptr + 1; /* start points to beginning of next element. */
604 } while (ptr != NULL);
609 return(NULL); /* doesn't exist in path. */
610 } /* findBinaryInPath */
613 char *calcBaseDir(const char *argv0)
615 /* If there isn't a path on argv0, then look through the $PATH for it. */
619 const char *ptr = strrchr((char *)argv0, '/');
620 if (strchr(argv0, '/'))
622 retval = strdup(argv0);
624 *((char *) strrchr(retval, '/')) = '\0';
628 envr = getenv("PATH");
629 if (!envr) return NULL;
631 if (!envr) return NULL;
632 retval = findBinaryInPath(argv0, envr);
637 static inline void chdirToAppPath(const char *argv0)
639 char *dir = calcBaseDir(argv0);
642 #if (defined(__APPLE__) && defined(__MACH__))
643 // Chop off /Contents/MacOS if it's at the end of the string, so we
644 // land in the base of the app bundle.
645 const size_t len = strlen(dir);
646 const char *bundledirs = "/Contents/MacOS";
647 const size_t bundledirslen = strlen(bundledirs);
648 if (len > bundledirslen)
650 char *ptr = (dir + len) - bundledirslen;
651 if (strcasecmp(ptr, bundledirs) == 0)
662 int main(int argc, char **argv)
669 // !!! FIXME: we could use a Win32 API for this. --ryan.
671 chdirToAppPath(argv[0]);
682 //ofstream os("error.txt");
684 //ofstream os("log.txt");
690 while (!gDone&&!game.quit&&(!game.tryquit))
696 // check windows messages
701 if(!game.isWaiting()) {
703 while( SDL_PollEvent( &e ) )
705 if( e.type == SDL_QUIT )
710 sdlEventProc(e, game);
721 // allow game chance to pause
726 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
728 SDL_WaitEvent((SDL_Event*)&evt);
729 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
731 else if (evt.type == SDL_QUIT)
743 catch (const std::exception& error)
747 std::string e = "Caught exception: ";
752 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
762 // --------------------------------------------------------------------------
765 bool LoadImage(const char * fname, TGAImageRec & tex)
767 if ( tex.data == NULL )
770 return load_image(fname, tex);
773 void ScreenShot(const char * fname)
780 static bool load_image(const char *file_name, TGAImageRec &tex)
782 const char *ptr = strrchr((char *)file_name, '.');
785 if (strcasecmp(ptr+1, "png") == 0)
786 return load_png(file_name, tex);
787 else if (strcasecmp(ptr+1, "jpg") == 0)
788 return load_jpg(file_name, tex);
791 STUBBED("Unsupported image type");
796 struct my_error_mgr {
797 struct jpeg_error_mgr pub; /* "public" fields */
798 jmp_buf setjmp_buffer; /* for return to caller */
800 typedef struct my_error_mgr * my_error_ptr;
803 static void my_error_exit(j_common_ptr cinfo)
805 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
806 longjmp(err->setjmp_buffer, 1);
809 /* stolen from public domain example.c code in libjpg distribution. */
810 static bool load_jpg(const char *file_name, TGAImageRec &tex)
812 struct jpeg_decompress_struct cinfo;
813 struct my_error_mgr jerr;
814 JSAMPROW buffer[1]; /* Output row buffer */
815 int row_stride; /* physical row width in output buffer */
816 FILE *infile = fopen(file_name, "rb");
821 cinfo.err = jpeg_std_error(&jerr.pub);
822 jerr.pub.error_exit = my_error_exit;
823 if (setjmp(jerr.setjmp_buffer)) {
824 jpeg_destroy_decompress(&cinfo);
829 jpeg_create_decompress(&cinfo);
830 jpeg_stdio_src(&cinfo, infile);
831 (void) jpeg_read_header(&cinfo, TRUE);
833 cinfo.out_color_space = JCS_RGB;
834 cinfo.quantize_colors = 0;
835 (void) jpeg_calc_output_dimensions(&cinfo);
836 (void) jpeg_start_decompress(&cinfo);
838 row_stride = cinfo.output_width * cinfo.output_components;
839 tex.sizeX = cinfo.output_width;
840 tex.sizeY = cinfo.output_height;
843 while (cinfo.output_scanline < cinfo.output_height) {
844 buffer[0] = (JSAMPROW)(char *)tex.data +
845 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
846 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
849 (void) jpeg_finish_decompress(&cinfo);
850 jpeg_destroy_decompress(&cinfo);
857 /* stolen from public domain example.c code in libpng distribution. */
858 static bool load_png(const char *file_name, TGAImageRec &tex)
860 bool hasalpha = false;
861 png_structp png_ptr = NULL;
862 png_infop info_ptr = NULL;
863 png_uint_32 width, height;
864 int bit_depth, color_type, interlace_type;
865 png_byte **rows = NULL;
867 png_byte **row_pointers = NULL;
868 FILE *fp = fopen(file_name, "rb");
873 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
877 info_ptr = png_create_info_struct(png_ptr);
878 if (info_ptr == NULL)
881 if (setjmp(png_jmpbuf(png_ptr)))
884 png_init_io(png_ptr, fp);
885 png_read_png(png_ptr, info_ptr,
886 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
888 png_get_IHDR(png_ptr, info_ptr, &width, &height,
889 &bit_depth, &color_type, &interlace_type, NULL, NULL);
891 if (bit_depth != 8) // transform SHOULD handle this...
894 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
897 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
900 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
901 row_pointers = png_get_rows(png_ptr, info_ptr);
907 png_byte *dst = tex.data;
908 for (int i = height-1; i >= 0; i--)
910 png_byte *src = row_pointers[i];
911 for (int j = 0; j < width; j++)
925 png_byte *dst = tex.data;
926 int pitch = width * 4;
927 for (int i = height-1; i >= 0; i--, dst += pitch)
928 memcpy(dst, row_pointers[i], pitch);
937 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
944 bool save_image(const char *file_name)
946 const char *ptr = strrchr((char *)file_name, '.');
949 if (strcasecmp(ptr+1, "png") == 0)
950 return save_png(file_name);
953 STUBBED("Unsupported image type");
958 static bool save_png(const char *file_name)
961 png_structp png_ptr = NULL;
962 png_infop info_ptr = NULL;
965 fp = fopen(file_name, "wb");
969 png_bytep *row_pointers = new png_bytep[kContextHeight];
970 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
971 if ((!screenshot) || (!row_pointers))
975 glReadPixels(0, 0, kContextWidth, kContextHeight,
976 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
977 if (glGetError() != GL_NO_ERROR)
980 for (int i = 0; i < kContextHeight; i++)
981 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
983 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
987 info_ptr = png_create_info_struct(png_ptr);
988 if (info_ptr == NULL)
991 if (setjmp(png_jmpbuf(png_ptr)))
994 png_init_io(png_ptr, fp);
996 if (setjmp(png_jmpbuf(png_ptr)))
999 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1000 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1001 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1003 png_write_info(png_ptr, info_ptr);
1005 if (setjmp(png_jmpbuf(png_ptr)))
1008 png_write_image(png_ptr, row_pointers);
1010 if (setjmp(png_jmpbuf(png_ptr)))
1013 png_write_end(png_ptr, NULL);
1017 png_destroy_write_struct(&png_ptr, &info_ptr);
1018 delete[] screenshot;
1019 delete[] row_pointers;
1023 unlink(ConvertFileName(file_name));