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
50 static bool load_image(const char * fname, TGAImageRec & tex);
51 static bool load_png(const char * fname, TGAImageRec & tex);
52 static bool load_jpg(const char * fname, TGAImageRec & tex);
53 bool save_image(const char * fname);
54 static bool save_png(const char * fname);
57 #include "openal_wrapper.h"
59 extern float multiplier;
61 extern float realmultiplier;
63 extern bool cellophane;
64 extern float texdetail;
68 extern bool stillloading;
73 extern float slomospeed;
74 extern float slomofreq;
84 #include "MacCompatibility.h"
89 #include "win-res/resource.h"
94 SDL_Rect **resolutions = NULL;
95 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
96 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
97 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
98 static SDL_Rect *hardcoded_resolutions[] = {
110 // statics/globals (internal only) ------------------------------------------
113 #pragma warning(push)
114 #pragma warning(disable: 4273)
117 #define GL_FUNC(ret,fn,params,call,rt) \
119 static ret (GLAPIENTRY *p##fn) params = NULL; \
120 ret GLAPIENTRY fn params { rt p##fn call; } \
129 static bool lookup_glsym(const char *funcname, void **func)
131 *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;
167 static int _argc = 0;
168 static char **_argv = NULL;
171 bool cmdline(const char *cmd)
173 for (int i = 1; i < _argc; i++) {
174 char *arg = _argv[i];
177 if (strcasecmp(arg, cmd) == 0)
184 //-----------------------------------------------------------------------------------------------------------------------
190 glClear( GL_COLOR_BUFFER_BIT );
194 glDisable( GL_ALPHA_TEST);
195 glDisable( GL_BLEND);
196 glDisable( GL_DEPTH_TEST);
197 //glDisable( GL_DITHER);
199 glDisable( GL_LIGHTING);
200 glDisable( GL_LOGIC_OP);
201 glDisable( GL_TEXTURE_1D);
202 glDisable( GL_TEXTURE_2D);
203 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
204 glPixelTransferi( GL_RED_SCALE, 1);
205 glPixelTransferi( GL_RED_BIAS, 0);
206 glPixelTransferi( GL_GREEN_SCALE, 1);
207 glPixelTransferi( GL_GREEN_BIAS, 0);
208 glPixelTransferi( GL_BLUE_SCALE, 1);
209 glPixelTransferi( GL_BLUE_BIAS, 0);
210 glPixelTransferi( GL_ALPHA_SCALE, 1);
211 glPixelTransferi( GL_ALPHA_BIAS, 0);
213 // set initial rendering states
214 glShadeModel( GL_SMOOTH);
216 glDepthFunc( GL_LEQUAL);
217 glDepthMask( GL_TRUE);
218 //glDepthRange( FRONT_CLIP, BACK_CLIP);
219 glEnable( GL_DEPTH_TEST);
220 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
221 glCullFace( GL_FRONT);
222 glEnable( GL_CULL_FACE);
223 glEnable( GL_LIGHTING);
224 //glEnable( GL_LIGHT_MODEL_AMBIENT);
225 glEnable( GL_DITHER);
226 glEnable( GL_COLOR_MATERIAL);
227 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
228 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
229 glAlphaFunc( GL_GREATER, 0.5f);
231 if ( CanInitStereo(stereomode) ) {
232 InitStereo(stereomode);
234 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
235 stereomode = stereoNone;
239 static void toggleFullscreen()
241 if (!SDL_WM_ToggleFullScreen(SDL_GetVideoSurface())) {
242 SDL_Surface* screen = SDL_GetVideoSurface();
243 Uint32 flags = screen->flags;
244 screen = SDL_SetVideoMode(0, 0, 0, flags ^ SDL_FULLSCREEN);
246 screen = SDL_SetVideoMode(0, 0, 0, flags);
249 //reload opengl state
251 Texture::reloadAll();
262 static void sdlEventProc(const SDL_Event &e)
265 case SDL_MOUSEMOTION:
266 deltah += e.motion.xrel;
267 deltav += e.motion.yrel;
271 if ((e.key.keysym.sym == SDLK_g) &&
272 (e.key.keysym.mod & KMOD_CTRL) &&
273 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
274 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY) == SDL_GRAB_ON) ? SDL_GRAB_OFF : SDL_GRAB_ON) );
275 } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
284 // --------------------------------------------------------------------------
286 static Point gMidPoint;
303 if (!SDL_WasInit(SDL_INIT_VIDEO))
304 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
305 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
308 if (!LoadSettings()) {
309 fprintf(stderr, "Failed to load config, creating default\n");
312 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
316 if (SDL_GL_LoadLibrary(NULL) == -1) {
317 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
322 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN | SDL_OPENGL);
323 if ( (res == NULL) || (res == ((SDL_Rect **) - 1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
324 res = hardcoded_resolutions;
326 // reverse list (it was sorted biggest to smallest by SDL)...
328 for (count = 0; res[count]; count++) {
329 if ((res[count]->w < 640) || (res[count]->h < 480))
330 break; // sane lower limit.
333 static SDL_Rect *resolutions_block = NULL;
334 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
335 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
336 if ((resolutions_block == NULL) || (resolutions == NULL)) {
338 fprintf(stderr, "Out of memory!\n");
342 resolutions[count--] = NULL;
343 for (int i = 0; count >= 0; i++, count--) {
344 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
345 resolutions[count] = &resolutions_block[count];
348 if (cmdline("showresolutions")) {
349 printf("Resolutions we think are okay:\n");
350 for (int i = 0; resolutions[i]; i++)
351 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
354 Uint32 sdlflags = SDL_OPENGL;
356 if (!cmdline("windowed"))
357 sdlflags |= SDL_FULLSCREEN;
359 SDL_WM_SetCaption("Lugaru", "Lugaru");
363 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
364 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
365 #if SDL_VERSION_ATLEAST(1, 2, 10)
366 SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, vblsync);
369 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL) {
370 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
371 fprintf(stderr, "forcing 640x480...\n");
373 kContextHeight = 480;
374 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL) {
375 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
376 fprintf(stderr, "forcing 640x480 windowed mode...\n");
377 sdlflags &= ~SDL_FULLSCREEN;
378 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL) {
379 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
386 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf)) {
387 fprintf(stderr, "Failed to get double buffered GL context!\n");
392 if (!lookup_all_glsyms()) {
397 if (!cmdline("nomousegrab"))
398 SDL_WM_GrabInput(SDL_GRAB_ON);
403 GLint width = kContextWidth;
404 GLint height = kContextHeight;
405 gMidPoint.h = width / 2;
406 gMidPoint.v = height / 2;
408 screenheight = height;
411 newscreenwidth = screenwidth;
412 newscreenheight = screenheight;
420 static void DoMouse()
423 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
424 deltah *= usermousesensitivity;
425 deltav *= usermousesensitivity;
426 mousecoordh += deltah;
427 mousecoordv += deltav;
430 else if (mousecoordh >= kContextWidth)
431 mousecoordh = kContextWidth - 1;
434 else if (mousecoordv >= kContextHeight)
435 mousecoordv = kContextHeight - 1;
440 void DoFrameRate (int update)
442 static long frames = 0;
444 static AbsoluteTime time = {0, 0};
445 static AbsoluteTime frametime = {0, 0};
446 AbsoluteTime currTime = UpTime ();
447 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
449 if (0 > deltaTime) // if negative microseconds
450 deltaTime /= -1000000.0;
451 else // else milliseconds
454 multiplier = deltaTime;
455 if (multiplier < .001)
460 frametime = currTime; // reset for next time interval
462 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
464 if (0 > deltaTime) // if negative microseconds
465 deltaTime /= -1000000.0;
466 else // else milliseconds
469 if (0.001 <= deltaTime) { // has update interval passed
471 time = currTime; // reset for next time interval
480 static float sps = 200;
482 static float oldmult;
488 fps = 1 / multiplier;
490 count = multiplier * sps;
494 realmultiplier = multiplier;
495 multiplier *= gamespeed;
502 multiplier *= .00001;
503 if (slomo && !mainmenu)
504 multiplier *= slomospeed;
505 oldmult = multiplier;
506 multiplier /= (float)count;
512 for (int i = 0; i < count; i++) {
515 multiplier = oldmult;
518 /* - Debug code to test how many channels were active on average per frame
519 static long frames = 0;
521 static AbsoluteTime start = {0,0};
522 AbsoluteTime currTime = UpTime ();
523 static int num_channels = 0;
525 num_channels += OPENAL_GetChannelsPlaying();
526 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
528 if (0 > deltaTime) // if negative microseconds
529 deltaTime /= -1000000.0;
530 else // else milliseconds
538 float avg_channels = (float)num_channels / (float)frames;
540 ofstream opstream("log.txt",ios::app);
541 opstream << "Average frame count: ";
543 opstream << " frames - ";
544 opstream << avg_channels;
545 opstream << " per frame.\n";
552 if ( stereomode == stereoNone ) {
553 DrawGLScene(stereoCenter);
555 DrawGLScene(stereoLeft);
556 DrawGLScene(stereoRight);
560 // --------------------------------------------------------------------------
568 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
571 // cheat here...static destructors are calling glDeleteTexture() after
572 // the context is destroyed and libGL unloaded by SDL_Quit().
573 pglDeleteTextures = glDeleteTextures_doNothing;
577 // --------------------------------------------------------------------------
579 static bool IsFocused()
581 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
587 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
588 static char *findBinaryInPath(const char *bin, char *envr)
590 size_t alloc_size = 0;
597 ptr = strchr(start, ':'); /* find next $PATH separator. */
601 size = strlen(start) + strlen(bin) + 2;
602 if (size > alloc_size) {
603 char *x = (char *) realloc(exe, size);
614 /* build full binary path... */
616 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
620 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
621 strcpy(exe, start); /* i'm lazy. piss off. */
625 start = ptr + 1; /* start points to beginning of next element. */
626 } while (ptr != NULL);
631 return(NULL); /* doesn't exist in path. */
632 } /* findBinaryInPath */
635 char *calcBaseDir(const char *argv0)
637 /* If there isn't a path on argv0, then look through the $PATH for it. */
641 const char *ptr = strrchr((char *)argv0, '/');
642 if (strchr(argv0, '/')) {
643 retval = strdup(argv0);
645 *((char *) strrchr(retval, '/')) = '\0';
649 envr = getenv("PATH");
655 retval = findBinaryInPath(argv0, envr);
660 static inline void chdirToAppPath(const char *argv0)
662 char *dir = calcBaseDir(argv0);
664 #if (defined(__APPLE__) && defined(__MACH__))
665 // Chop off /Contents/MacOS if it's at the end of the string, so we
666 // land in the base of the app bundle.
667 const size_t len = strlen(dir);
668 const char *bundledirs = "/Contents/MacOS";
669 const size_t bundledirslen = strlen(bundledirs);
670 if (len > bundledirslen) {
671 char *ptr = (dir + len) - bundledirslen;
672 if (strcasecmp(ptr, bundledirs) == 0)
683 int main(int argc, char **argv)
690 // !!! FIXME: we could use a Win32 API for this. --ryan.
692 chdirToAppPath(argv[0]);
701 //ofstream os("error.txt");
703 //ofstream os("log.txt");
709 while (!gDone && !tryquit) {
713 // check windows messages
720 while ( SDL_PollEvent( &e ) ) {
721 if ( e.type == SDL_QUIT ) {
733 // allow game chance to pause
738 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
740 SDL_WaitEvent((SDL_Event*)&evt);
741 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
743 else if (evt.type == SDL_QUIT)
754 } 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, '.');
794 if (strcasecmp(ptr + 1, "png") == 0)
795 return load_png(file_name, tex);
796 else if (strcasecmp(ptr + 1, "jpg") == 0)
797 return load_jpg(file_name, tex);
800 STUBBED("Unsupported image type");
805 struct my_error_mgr {
806 struct jpeg_error_mgr pub; /* "public" fields */
807 jmp_buf setjmp_buffer; /* for return to caller */
809 typedef struct my_error_mgr * my_error_ptr;
812 static void my_error_exit(j_common_ptr cinfo)
814 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
815 longjmp(err->setjmp_buffer, 1);
818 /* stolen from public domain example.c code in libjpg distribution. */
819 static bool load_jpg(const char *file_name, TGAImageRec &tex)
821 struct jpeg_decompress_struct cinfo;
822 struct my_error_mgr jerr;
823 JSAMPROW buffer[1]; /* Output row buffer */
824 int row_stride; /* physical row width in output buffer */
825 FILE *infile = fopen(file_name, "rb");
830 cinfo.err = jpeg_std_error(&jerr.pub);
831 jerr.pub.error_exit = my_error_exit;
832 if (setjmp(jerr.setjmp_buffer)) {
833 jpeg_destroy_decompress(&cinfo);
838 jpeg_create_decompress(&cinfo);
839 jpeg_stdio_src(&cinfo, infile);
840 (void) jpeg_read_header(&cinfo, TRUE);
842 cinfo.out_color_space = JCS_RGB;
843 cinfo.quantize_colors = 0;
844 (void) jpeg_calc_output_dimensions(&cinfo);
845 (void) jpeg_start_decompress(&cinfo);
847 row_stride = cinfo.output_width * cinfo.output_components;
848 tex.sizeX = cinfo.output_width;
849 tex.sizeY = cinfo.output_height;
852 while (cinfo.output_scanline < cinfo.output_height) {
853 buffer[0] = (JSAMPROW)(char *)tex.data +
854 ((cinfo.output_height - 1) - cinfo.output_scanline) * row_stride;
855 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
858 (void) jpeg_finish_decompress(&cinfo);
859 jpeg_destroy_decompress(&cinfo);
866 /* stolen from public domain example.c code in libpng distribution. */
867 static bool load_png(const char *file_name, TGAImageRec &tex)
869 bool hasalpha = false;
870 png_structp png_ptr = NULL;
871 png_infop info_ptr = NULL;
872 png_uint_32 width, height;
873 int bit_depth, color_type, interlace_type;
874 png_byte **rows = NULL;
876 png_byte **row_pointers = NULL;
877 FILE *fp = fopen(file_name, "rb");
880 cerr << file_name << " not found" << endl;
884 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
888 info_ptr = png_create_info_struct(png_ptr);
889 if (info_ptr == NULL)
892 if (setjmp(png_jmpbuf(png_ptr)))
895 png_init_io(png_ptr, fp);
896 png_read_png(png_ptr, info_ptr,
897 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
899 png_get_IHDR(png_ptr, info_ptr, &width, &height,
900 &bit_depth, &color_type, &interlace_type, NULL, NULL);
902 if (bit_depth != 8) // transform SHOULD handle this...
905 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
908 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
911 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
912 row_pointers = png_get_rows(png_ptr, info_ptr);
917 png_byte *dst = tex.data;
918 for (int i = height - 1; i >= 0; i--) {
919 png_byte *src = row_pointers[i];
920 for (int j = 0; j < width; j++) {
932 png_byte *dst = tex.data;
933 int pitch = width * 4;
934 for (int i = height - 1; i >= 0; i--, dst += pitch)
935 memcpy(dst, row_pointers[i], pitch);
945 cerr << "There was a problem loading " << file_name << endl;
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, '.');
958 if (strcasecmp(ptr + 1, "png") == 0)
959 return save_png(file_name);
962 STUBBED("Unsupported image type");
967 static bool save_png(const char *file_name)
970 png_structp png_ptr = NULL;
971 png_infop info_ptr = NULL;
974 fp = fopen(file_name, "wb");
978 png_bytep *row_pointers = new png_bytep[kContextHeight];
979 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
980 if ((!screenshot) || (!row_pointers))
984 glReadPixels(0, 0, kContextWidth, kContextHeight,
985 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
986 if (glGetError() != GL_NO_ERROR)
989 for (int i = 0; i < kContextHeight; i++)
990 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight - 1) - i)) * 3);
992 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
996 info_ptr = png_create_info_struct(png_ptr);
997 if (info_ptr == NULL)
1000 if (setjmp(png_jmpbuf(png_ptr)))
1003 png_init_io(png_ptr, fp);
1005 if (setjmp(png_jmpbuf(png_ptr)))
1008 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1009 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1010 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1012 png_write_info(png_ptr, info_ptr);
1014 if (setjmp(png_jmpbuf(png_ptr)))
1017 png_write_image(png_ptr, row_pointers);
1019 if (setjmp(png_jmpbuf(png_ptr)))
1022 png_write_end(png_ptr, NULL);
1026 png_destroy_write_struct(&png_ptr, &info_ptr);
1027 delete[] screenshot;
1028 delete[] row_pointers;
1032 unlink(ConvertFileName(file_name));