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;
74 extern bool stillloading;
76 /*extern*/ bool gameFocused;
78 extern float slomospeed;
79 extern float slomofreq;
89 #include "MacCompatibility.h"
94 #include "win-res/resource.h"
99 SDL_Rect **resolutions = NULL;
100 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
101 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
102 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
103 static SDL_Rect *hardcoded_resolutions[] = {
110 void DrawGL(Game & game);
112 Boolean SetUp (Game & game);
113 void DoUpdate (Game & game);
117 // statics/globals (internal only) ------------------------------------------
120 #pragma warning(push)
121 #pragma warning(disable: 4273)
124 #define GL_FUNC(ret,fn,params,call,rt) \
126 static ret (GLAPIENTRY *p##fn) params = NULL; \
127 ret GLAPIENTRY fn params { rt p##fn call; } \
136 static bool lookup_glsym(const char *funcname, void **func)
138 *func = SDL_GL_GetProcAddress(funcname);
141 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
147 static bool lookup_all_glsyms(void)
150 #define GL_FUNC(ret,fn,params,call,rt) \
151 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
157 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
165 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
172 Boolean gDone = false;
177 static int _argc = 0;
178 static char **_argv = NULL;
181 bool cmdline(const char *cmd)
183 for (int i = 1; i < _argc; i++)
185 char *arg = _argv[i];
188 if (strcasecmp(arg, cmd) == 0)
195 //-----------------------------------------------------------------------------------------------------------------------
199 static void sdlEventProc(const SDL_Event &e, Game &game)
203 case SDL_MOUSEMOTION:
204 game.deltah += e.motion.xrel;
205 game.deltav += e.motion.yrel;
209 if ((e.key.keysym.sym == SDLK_g) &&
210 (e.key.keysym.mod & KMOD_CTRL) &&
211 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
212 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
213 } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
214 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
221 // --------------------------------------------------------------------------
223 static Point gMidPoint;
225 Boolean SetUp (Game & game)
239 DefaultSettings(game);
241 if (!SDL_WasInit(SDL_INIT_VIDEO))
242 if (SDL_Init(SDL_INIT_VIDEO) == -1)
244 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
247 if(!LoadSettings(game)) {
248 fprintf(stderr, "Failed to load config, creating default\n");
251 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
255 if (SDL_GL_LoadLibrary(NULL) == -1)
257 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
262 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
263 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
264 res = hardcoded_resolutions;
266 // reverse list (it was sorted biggest to smallest by SDL)...
268 for (count = 0; res[count]; count++)
270 if ((res[count]->w < 640) || (res[count]->h < 480))
271 break; // sane lower limit.
274 static SDL_Rect *resolutions_block = NULL;
275 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
276 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
277 if ((resolutions_block == NULL) || (resolutions == NULL))
280 fprintf(stderr, "Out of memory!\n");
284 resolutions[count--] = NULL;
285 for (int i = 0; count >= 0; i++, count--)
287 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
288 resolutions[count] = &resolutions_block[count];
291 if (cmdline("showresolutions"))
293 printf("Resolutions we think are okay:\n");
294 for (int i = 0; resolutions[i]; i++)
295 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
298 Uint32 sdlflags = SDL_OPENGL;
299 if (!cmdline("windowed"))
300 sdlflags |= SDL_FULLSCREEN;
302 SDL_WM_SetCaption("Lugaru", "Lugaru");
306 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
307 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
309 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
311 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
312 fprintf(stderr, "forcing 640x480...\n");
314 kContextHeight = 480;
315 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
317 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
318 fprintf(stderr, "forcing 640x480 windowed mode...\n");
319 sdlflags &= ~SDL_FULLSCREEN;
320 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
322 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
329 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
331 fprintf(stderr, "Failed to get double buffered GL context!\n");
336 if (!lookup_all_glsyms())
342 if (!cmdline("nomousegrab"))
343 SDL_WM_GrabInput(SDL_GRAB_ON);
346 glClear( GL_COLOR_BUFFER_BIT );
350 glDisable( GL_ALPHA_TEST);
351 glDisable( GL_BLEND);
352 glDisable( GL_DEPTH_TEST);
353 // glDisable( GL_DITHER);
355 glDisable( GL_LIGHTING);
356 glDisable( GL_LOGIC_OP);
357 glDisable( GL_TEXTURE_1D);
358 glDisable( GL_TEXTURE_2D);
359 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
360 glPixelTransferi( GL_RED_SCALE, 1);
361 glPixelTransferi( GL_RED_BIAS, 0);
362 glPixelTransferi( GL_GREEN_SCALE, 1);
363 glPixelTransferi( GL_GREEN_BIAS, 0);
364 glPixelTransferi( GL_BLUE_SCALE, 1);
365 glPixelTransferi( GL_BLUE_BIAS, 0);
366 glPixelTransferi( GL_ALPHA_SCALE, 1);
367 glPixelTransferi( GL_ALPHA_BIAS, 0);
369 // set initial rendering states
370 glShadeModel( GL_SMOOTH);
372 glDepthFunc( GL_LEQUAL);
373 glDepthMask( GL_TRUE);
374 // glDepthRange( FRONT_CLIP, BACK_CLIP);
375 glEnable( GL_DEPTH_TEST);
376 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
377 glCullFace( GL_FRONT);
378 glEnable( GL_CULL_FACE);
379 glEnable( GL_LIGHTING);
380 // glEnable( GL_LIGHT_MODEL_AMBIENT);
381 glEnable( GL_DITHER);
382 glEnable( GL_COLOR_MATERIAL);
383 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
384 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
385 glAlphaFunc( GL_GREATER, 0.5f);
387 GLint width = kContextWidth;
388 GLint height = kContextHeight;
389 gMidPoint.h = width / 2;
390 gMidPoint.v = height / 2;
394 game.newdetail=detail;
395 game.newscreenwidth=screenwidth;
396 game.newscreenheight=screenheight;
398 if ( CanInitStereo(stereomode) ) {
399 InitStereo(stereomode);
401 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
402 stereomode = stereoNone;
411 static void DoMouse(Game & game)
414 if(mainmenu|| ( (abs(game.deltah)<10*realmultiplier*1000) && (abs(game.deltav)<10*realmultiplier*1000) ))
416 game.deltah *= usermousesensitivity;
417 game.deltav *= usermousesensitivity;
418 game.mousecoordh += game.deltah;
419 game.mousecoordv += game.deltav;
420 if (game.mousecoordh < 0)
421 game.mousecoordh = 0;
422 else if (game.mousecoordh >= kContextWidth)
423 game.mousecoordh = kContextWidth - 1;
424 if (game.mousecoordv < 0)
425 game.mousecoordv = 0;
426 else if (game.mousecoordv >= kContextHeight)
427 game.mousecoordv = kContextHeight - 1;
432 void DoFrameRate (int update)
434 static long frames = 0;
436 static AbsoluteTime time = {0,0};
437 static AbsoluteTime frametime = {0,0};
438 AbsoluteTime currTime = UpTime ();
439 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
441 if (0 > deltaTime) // if negative microseconds
442 deltaTime /= -1000000.0;
443 else // else milliseconds
446 multiplier=deltaTime;
447 if(multiplier<.001) multiplier=.001;
448 if(multiplier>10) multiplier=10;
449 if(update) frametime = currTime; // reset for next time interval
451 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
453 if (0 > deltaTime) // if negative microseconds
454 deltaTime /= -1000000.0;
455 else // else milliseconds
458 if (0.001 <= deltaTime) // has update interval passed
461 time = currTime; // reset for next time interval
468 void DoUpdate (Game & game)
470 static float sps=200;
472 static float oldmult;
475 if(multiplier>.6)multiplier=.6;
477 game.fps=1/multiplier;
479 count = multiplier*sps;
482 realmultiplier=multiplier;
483 multiplier*=gamespeed;
484 if(difficulty==1)multiplier*=.9;
485 if(difficulty==0)multiplier*=.8;
487 if(game.loading==4)multiplier*=.00001;
488 if(slomo&&!mainmenu)multiplier*=slomospeed;
490 multiplier/=(float)count;
496 for(int i=0;i<count;i++)
502 game.TickOnceAfter();
503 /* - Debug code to test how many channels were active on average per frame
504 static long frames = 0;
506 static AbsoluteTime start = {0,0};
507 AbsoluteTime currTime = UpTime ();
508 static int num_channels = 0;
510 num_channels += OPENAL_GetChannelsPlaying();
511 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
513 if (0 > deltaTime) // if negative microseconds
514 deltaTime /= -1000000.0;
515 else // else milliseconds
523 float avg_channels = (float)num_channels / (float)frames;
525 ofstream opstream("log.txt",ios::app);
526 opstream << "Average frame count: ";
528 opstream << " frames - ";
529 opstream << avg_channels;
530 opstream << " per frame.\n";
540 // --------------------------------------------------------------------------
548 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
551 // cheat here...static destructors are calling glDeleteTexture() after
552 // the context is destroyed and libGL unloaded by SDL_Quit().
553 pglDeleteTextures = glDeleteTextures_doNothing;
557 // --------------------------------------------------------------------------
559 static bool IsFocused()
561 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
567 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
568 static char *findBinaryInPath(const char *bin, char *envr)
570 size_t alloc_size = 0;
578 ptr = strchr(start, ':'); /* find next $PATH separator. */
582 size = strlen(start) + strlen(bin) + 2;
583 if (size > alloc_size)
585 char *x = (char *) realloc(exe, size);
597 /* build full binary path... */
599 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
603 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
605 strcpy(exe, start); /* i'm lazy. piss off. */
609 start = ptr + 1; /* start points to beginning of next element. */
610 } while (ptr != NULL);
615 return(NULL); /* doesn't exist in path. */
616 } /* findBinaryInPath */
619 char *calcBaseDir(const char *argv0)
621 /* If there isn't a path on argv0, then look through the $PATH for it. */
625 const char *ptr = strrchr((char *)argv0, '/');
626 if (strchr(argv0, '/'))
628 retval = strdup(argv0);
630 *((char *) strrchr(retval, '/')) = '\0';
634 envr = getenv("PATH");
635 if (!envr) return NULL;
637 if (!envr) return NULL;
638 retval = findBinaryInPath(argv0, envr);
643 static inline void chdirToAppPath(const char *argv0)
645 char *dir = calcBaseDir(argv0);
648 #if (defined(__APPLE__) && defined(__MACH__))
649 // Chop off /Contents/MacOS if it's at the end of the string, so we
650 // land in the base of the app bundle.
651 const size_t len = strlen(dir);
652 const char *bundledirs = "/Contents/MacOS";
653 const size_t bundledirslen = strlen(bundledirs);
654 if (len > bundledirslen)
656 char *ptr = (dir + len) - bundledirslen;
657 if (strcasecmp(ptr, bundledirs) == 0)
668 int main(int argc, char **argv)
675 // !!! FIXME: we could use a Win32 API for this. --ryan.
677 chdirToAppPath(argv[0]);
689 //ofstream os("error.txt");
691 //ofstream os("log.txt");
697 while (!gDone&&!game.quit&&(!game.tryquit))
703 // check windows messages
708 if(!game.isWaiting()) {
710 while( SDL_PollEvent( &e ) )
712 if( e.type == SDL_QUIT )
717 sdlEventProc(e, game);
728 // allow game chance to pause
733 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
735 SDL_WaitEvent((SDL_Event*)&evt);
736 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
738 else if (evt.type == SDL_QUIT)
743 regnow = game.registernow;
751 catch (const std::exception& error)
755 std::string e = "Caught exception: ";
760 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
770 // --------------------------------------------------------------------------
773 bool LoadImage(const char * fname, TGAImageRec & tex)
775 if ( tex.data == NULL )
778 return load_image(fname, tex);
781 void ScreenShot(const char * fname)
788 static bool load_image(const char *file_name, TGAImageRec &tex)
790 const char *ptr = strrchr((char *)file_name, '.');
793 if (strcasecmp(ptr+1, "png") == 0)
794 return load_png(file_name, tex);
795 else if (strcasecmp(ptr+1, "jpg") == 0)
796 return load_jpg(file_name, tex);
799 STUBBED("Unsupported image type");
804 struct my_error_mgr {
805 struct jpeg_error_mgr pub; /* "public" fields */
806 jmp_buf setjmp_buffer; /* for return to caller */
808 typedef struct my_error_mgr * my_error_ptr;
811 static void my_error_exit(j_common_ptr cinfo)
813 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
814 longjmp(err->setjmp_buffer, 1);
817 /* stolen from public domain example.c code in libjpg distribution. */
818 static bool load_jpg(const char *file_name, TGAImageRec &tex)
820 struct jpeg_decompress_struct cinfo;
821 struct my_error_mgr jerr;
822 JSAMPROW buffer[1]; /* Output row buffer */
823 int row_stride; /* physical row width in output buffer */
824 FILE *infile = fopen(file_name, "rb");
829 cinfo.err = jpeg_std_error(&jerr.pub);
830 jerr.pub.error_exit = my_error_exit;
831 if (setjmp(jerr.setjmp_buffer)) {
832 jpeg_destroy_decompress(&cinfo);
837 jpeg_create_decompress(&cinfo);
838 jpeg_stdio_src(&cinfo, infile);
839 (void) jpeg_read_header(&cinfo, TRUE);
841 cinfo.out_color_space = JCS_RGB;
842 cinfo.quantize_colors = 0;
843 (void) jpeg_calc_output_dimensions(&cinfo);
844 (void) jpeg_start_decompress(&cinfo);
846 row_stride = cinfo.output_width * cinfo.output_components;
847 tex.sizeX = cinfo.output_width;
848 tex.sizeY = cinfo.output_height;
851 while (cinfo.output_scanline < cinfo.output_height) {
852 buffer[0] = (JSAMPROW)(char *)tex.data +
853 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
854 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
857 (void) jpeg_finish_decompress(&cinfo);
858 jpeg_destroy_decompress(&cinfo);
865 /* stolen from public domain example.c code in libpng distribution. */
866 static bool load_png(const char *file_name, TGAImageRec &tex)
868 bool hasalpha = false;
869 png_structp png_ptr = NULL;
870 png_infop info_ptr = NULL;
871 png_uint_32 width, height;
872 int bit_depth, color_type, interlace_type;
873 png_byte **rows = NULL;
875 png_byte **row_pointers = NULL;
876 FILE *fp = fopen(file_name, "rb");
881 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
885 info_ptr = png_create_info_struct(png_ptr);
886 if (info_ptr == NULL)
889 if (setjmp(png_jmpbuf(png_ptr)))
892 png_init_io(png_ptr, fp);
893 png_read_png(png_ptr, info_ptr,
894 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
896 png_get_IHDR(png_ptr, info_ptr, &width, &height,
897 &bit_depth, &color_type, &interlace_type, NULL, NULL);
899 if (bit_depth != 8) // transform SHOULD handle this...
902 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
905 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
908 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
909 row_pointers = png_get_rows(png_ptr, info_ptr);
915 png_byte *dst = tex.data;
916 for (int i = height-1; i >= 0; i--)
918 png_byte *src = row_pointers[i];
919 for (int j = 0; j < width; j++)
933 png_byte *dst = tex.data;
934 int pitch = width * 4;
935 for (int i = height-1; i >= 0; i--, dst += pitch)
936 memcpy(dst, row_pointers[i], pitch);
945 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
952 bool save_image(const char *file_name)
954 const char *ptr = strrchr((char *)file_name, '.');
957 if (strcasecmp(ptr+1, "png") == 0)
958 return save_png(file_name);
961 STUBBED("Unsupported image type");
966 static bool save_png(const char *file_name)
969 png_structp png_ptr = NULL;
970 png_infop info_ptr = NULL;
973 fp = fopen(file_name, "wb");
977 png_bytep *row_pointers = new png_bytep[kContextHeight];
978 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
979 if ((!screenshot) || (!row_pointers))
983 glReadPixels(0, 0, kContextWidth, kContextHeight,
984 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
985 if (glGetError() != GL_NO_ERROR)
988 for (int i = 0; i < kContextHeight; i++)
989 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
991 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
995 info_ptr = png_create_info_struct(png_ptr);
996 if (info_ptr == NULL)
999 if (setjmp(png_jmpbuf(png_ptr)))
1002 png_init_io(png_ptr, fp);
1004 if (setjmp(png_jmpbuf(png_ptr)))
1007 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1008 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1009 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1011 png_write_info(png_ptr, info_ptr);
1013 if (setjmp(png_jmpbuf(png_ptr)))
1016 png_write_image(png_ptr, row_pointers);
1018 if (setjmp(png_jmpbuf(png_ptr)))
1021 png_write_end(png_ptr, NULL);
1025 png_destroy_write_struct(&png_ptr, &info_ptr);
1026 delete[] screenshot;
1027 delete[] row_pointers;
1031 unlink(ConvertFileName(file_name));