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;
302 if (!SDL_WasInit(SDL_INIT_VIDEO))
303 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
304 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
307 if (!LoadSettings()) {
308 fprintf(stderr, "Failed to load config, creating default\n");
311 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
315 if (SDL_GL_LoadLibrary(NULL) == -1) {
316 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
321 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN | SDL_OPENGL);
322 if ( (res == NULL) || (res == ((SDL_Rect **) - 1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
323 res = hardcoded_resolutions;
325 // reverse list (it was sorted biggest to smallest by SDL)...
327 for (count = 0; res[count]; count++) {
328 if ((res[count]->w < 640) || (res[count]->h < 480))
329 break; // sane lower limit.
332 static SDL_Rect *resolutions_block = NULL;
333 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
334 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
335 if ((resolutions_block == NULL) || (resolutions == NULL)) {
337 fprintf(stderr, "Out of memory!\n");
341 resolutions[count--] = NULL;
342 for (int i = 0; count >= 0; i++, count--) {
343 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
344 resolutions[count] = &resolutions_block[count];
347 if (cmdline("showresolutions")) {
348 printf("Resolutions we think are okay:\n");
349 for (int i = 0; resolutions[i]; i++)
350 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
353 Uint32 sdlflags = SDL_OPENGL;
355 if (!cmdline("windowed"))
356 sdlflags |= SDL_FULLSCREEN;
358 SDL_WM_SetCaption("Lugaru", "Lugaru");
362 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
363 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
364 #if SDL_VERSION_ATLEAST(1, 2, 10)
365 SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, vblsync);
368 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL) {
369 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
370 fprintf(stderr, "forcing 640x480...\n");
372 kContextHeight = 480;
373 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL) {
374 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
375 fprintf(stderr, "forcing 640x480 windowed mode...\n");
376 sdlflags &= ~SDL_FULLSCREEN;
377 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL) {
378 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
385 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf)) {
386 fprintf(stderr, "Failed to get double buffered GL context!\n");
391 if (!lookup_all_glsyms()) {
396 if (!cmdline("nomousegrab"))
397 SDL_WM_GrabInput(SDL_GRAB_ON);
402 GLint width = kContextWidth;
403 GLint height = kContextHeight;
404 gMidPoint.h = width / 2;
405 gMidPoint.v = height / 2;
407 screenheight = height;
410 newscreenwidth = screenwidth;
411 newscreenheight = screenheight;
419 static void DoMouse()
422 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
423 deltah *= usermousesensitivity;
424 deltav *= usermousesensitivity;
425 mousecoordh += deltah;
426 mousecoordv += deltav;
429 else if (mousecoordh >= kContextWidth)
430 mousecoordh = kContextWidth - 1;
433 else if (mousecoordv >= kContextHeight)
434 mousecoordv = kContextHeight - 1;
439 void DoFrameRate (int update)
441 static long frames = 0;
443 static AbsoluteTime time = {0, 0};
444 static AbsoluteTime frametime = {0, 0};
445 AbsoluteTime currTime = UpTime ();
446 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
448 if (0 > deltaTime) // if negative microseconds
449 deltaTime /= -1000000.0;
450 else // else milliseconds
453 multiplier = deltaTime;
454 if (multiplier < .001)
459 frametime = currTime; // reset for next time interval
461 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
463 if (0 > deltaTime) // if negative microseconds
464 deltaTime /= -1000000.0;
465 else // else milliseconds
468 if (0.001 <= deltaTime) { // has update interval passed
470 time = currTime; // reset for next time interval
479 static float sps = 200;
481 static float oldmult;
487 fps = 1 / multiplier;
489 count = multiplier * sps;
493 realmultiplier = multiplier;
494 multiplier *= gamespeed;
501 multiplier *= .00001;
502 if (slomo && !mainmenu)
503 multiplier *= slomospeed;
504 oldmult = multiplier;
505 multiplier /= (float)count;
511 for (int i = 0; i < count; i++) {
514 multiplier = oldmult;
517 /* - Debug code to test how many channels were active on average per frame
518 static long frames = 0;
520 static AbsoluteTime start = {0,0};
521 AbsoluteTime currTime = UpTime ();
522 static int num_channels = 0;
524 num_channels += OPENAL_GetChannelsPlaying();
525 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
527 if (0 > deltaTime) // if negative microseconds
528 deltaTime /= -1000000.0;
529 else // else milliseconds
537 float avg_channels = (float)num_channels / (float)frames;
539 ofstream opstream("log.txt",ios::app);
540 opstream << "Average frame count: ";
542 opstream << " frames - ";
543 opstream << avg_channels;
544 opstream << " per frame.\n";
551 if ( stereomode == stereoNone ) {
552 DrawGLScene(stereoCenter);
554 DrawGLScene(stereoLeft);
555 DrawGLScene(stereoRight);
559 // --------------------------------------------------------------------------
567 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
570 // cheat here...static destructors are calling glDeleteTexture() after
571 // the context is destroyed and libGL unloaded by SDL_Quit().
572 pglDeleteTextures = glDeleteTextures_doNothing;
576 // --------------------------------------------------------------------------
578 static bool IsFocused()
580 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
586 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
587 static char *findBinaryInPath(const char *bin, char *envr)
589 size_t alloc_size = 0;
596 ptr = strchr(start, ':'); /* find next $PATH separator. */
600 size = strlen(start) + strlen(bin) + 2;
601 if (size > alloc_size) {
602 char *x = (char *) realloc(exe, size);
613 /* build full binary path... */
615 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
619 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
620 strcpy(exe, start); /* i'm lazy. piss off. */
624 start = ptr + 1; /* start points to beginning of next element. */
625 } while (ptr != NULL);
630 return(NULL); /* doesn't exist in path. */
631 } /* findBinaryInPath */
634 char *calcBaseDir(const char *argv0)
636 /* If there isn't a path on argv0, then look through the $PATH for it. */
640 const char *ptr = strrchr((char *)argv0, '/');
641 if (strchr(argv0, '/')) {
642 retval = strdup(argv0);
644 *((char *) strrchr(retval, '/')) = '\0';
648 envr = getenv("PATH");
654 retval = findBinaryInPath(argv0, envr);
659 static inline void chdirToAppPath(const char *argv0)
661 char *dir = calcBaseDir(argv0);
663 #if (defined(__APPLE__) && defined(__MACH__))
664 // Chop off /Contents/MacOS if it's at the end of the string, so we
665 // land in the base of the app bundle.
666 const size_t len = strlen(dir);
667 const char *bundledirs = "/Contents/MacOS";
668 const size_t bundledirslen = strlen(bundledirs);
669 if (len > bundledirslen) {
670 char *ptr = (dir + len) - bundledirslen;
671 if (strcasecmp(ptr, bundledirs) == 0)
682 int main(int argc, char **argv)
689 // !!! FIXME: we could use a Win32 API for this. --ryan.
691 chdirToAppPath(argv[0]);
700 //ofstream os("error.txt");
702 //ofstream os("log.txt");
708 while (!gDone && !tryquit) {
712 // check windows messages
719 while ( SDL_PollEvent( &e ) ) {
720 if ( e.type == SDL_QUIT ) {
732 // allow game chance to pause
737 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
739 SDL_WaitEvent((SDL_Event*)&evt);
740 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
742 else if (evt.type == SDL_QUIT)
753 } catch (const std::exception& error) {
756 std::string e = "Caught exception: ";
761 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
771 // --------------------------------------------------------------------------
774 bool LoadImage(const char * fname, TGAImageRec & tex)
776 if ( tex.data == NULL )
779 return load_image(fname, tex);
782 void ScreenShot(const char * fname)
789 static bool load_image(const char *file_name, TGAImageRec &tex)
791 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");
879 cerr << file_name << " not found" << endl;
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);
916 png_byte *dst = tex.data;
917 for (int i = height - 1; i >= 0; i--) {
918 png_byte *src = row_pointers[i];
919 for (int j = 0; j < width; j++) {
931 png_byte *dst = tex.data;
932 int pitch = width * 4;
933 for (int i = height - 1; i >= 0; i--, dst += pitch)
934 memcpy(dst, row_pointers[i], pitch);
944 cerr << "There was a problem loading " << file_name << endl;
946 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
953 bool save_image(const char *file_name)
955 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));