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.
35 static bool load_image(const char * fname, TGAImageRec & tex);
36 static bool load_png(const char * fname, TGAImageRec & tex);
37 static bool load_jpg(const char * fname, TGAImageRec & tex);
38 bool save_image(const char * fname);
39 static bool save_png(const char * fname);
42 #include "openal_wrapper.h"
44 extern float multiplier;
46 extern float realmultiplier;
48 extern bool cellophane;
49 extern float texdetail;
53 extern bool stillloading;
58 extern float slomospeed;
59 extern float slomofreq;
70 #include "MacCompatibility.h"
75 #include "win-res/resource.h"
78 extern SDL_Window *sdlwindow;
82 set<pair<int,int>> resolutions;
89 // statics/globals (internal only) ------------------------------------------
93 #pragma warning(disable: 4273)
96 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
97 #define GL_FUNC(ret,fn,params,call,rt) \
99 static ret (GLAPIENTRY *p##fn) params = NULL; \
100 ret GLAPIENTRY fn params { rt p##fn call; } \
104 #endif // __MINGW32__
110 static bool lookup_glsym(const char *funcname, void **func)
112 *func = SDL_GL_GetProcAddress(funcname);
114 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
120 static bool lookup_all_glsyms(void)
123 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
124 #define GL_FUNC(ret,fn,params,call,rt) \
125 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
128 #endif // __MINGW32__
132 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
133 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
137 #endif // __MINGW32__
142 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
149 Boolean gDone = false;
151 static int _argc = 0;
152 static char **_argv = NULL;
154 bool cmdline(const char *cmd)
156 for (int i = 1; i < _argc; i++) {
157 char *arg = _argv[i];
160 if (strcasecmp(arg, cmd) == 0)
167 //-----------------------------------------------------------------------------------------------------------------------
173 glClear( GL_COLOR_BUFFER_BIT );
177 glDisable( GL_ALPHA_TEST);
178 glDisable( GL_BLEND);
179 glDisable( GL_DEPTH_TEST);
180 //glDisable( GL_DITHER);
182 glDisable( GL_LIGHTING);
183 glDisable( GL_LOGIC_OP);
184 glDisable( GL_TEXTURE_1D);
185 glDisable( GL_TEXTURE_2D);
186 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
187 glPixelTransferi( GL_RED_SCALE, 1);
188 glPixelTransferi( GL_RED_BIAS, 0);
189 glPixelTransferi( GL_GREEN_SCALE, 1);
190 glPixelTransferi( GL_GREEN_BIAS, 0);
191 glPixelTransferi( GL_BLUE_SCALE, 1);
192 glPixelTransferi( GL_BLUE_BIAS, 0);
193 glPixelTransferi( GL_ALPHA_SCALE, 1);
194 glPixelTransferi( GL_ALPHA_BIAS, 0);
196 // set initial rendering states
197 glShadeModel( GL_SMOOTH);
199 glDepthFunc( GL_LEQUAL);
200 glDepthMask( GL_TRUE);
201 //glDepthRange( FRONT_CLIP, BACK_CLIP);
202 glEnable( GL_DEPTH_TEST);
203 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
204 glCullFace( GL_FRONT);
205 glEnable( GL_CULL_FACE);
206 glEnable( GL_LIGHTING);
207 //glEnable( GL_LIGHT_MODEL_AMBIENT);
208 glEnable( GL_DITHER);
209 glEnable( GL_COLOR_MATERIAL);
210 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
211 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
212 glAlphaFunc( GL_GREATER, 0.5f);
214 if ( CanInitStereo(stereomode) ) {
215 InitStereo(stereomode);
217 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
218 stereomode = stereoNone;
222 void toggleFullscreen()
224 fullscreen = !fullscreen;
225 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
226 if (flags & SDL_WINDOW_FULLSCREEN) {
227 flags &= ~SDL_WINDOW_FULLSCREEN;
229 flags |= SDL_WINDOW_FULLSCREEN;
231 SDL_SetWindowFullscreen(sdlwindow, flags);
234 static SDL_bool sdlEventProc(const SDL_Event &e)
240 case SDL_WINDOWEVENT:
241 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
246 case SDL_MOUSEMOTION:
247 deltah += e.motion.xrel;
248 deltav += e.motion.yrel;
252 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
253 (e.key.keysym.mod & KMOD_CTRL)) {
254 SDL_bool mode = SDL_TRUE;
255 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
256 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
257 SDL_SetWindowGrab(sdlwindow, mode);
258 SDL_SetRelativeMouseMode(mode);
259 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
269 // --------------------------------------------------------------------------
271 static Point gMidPoint;
287 if (!SDL_WasInit(SDL_INIT_VIDEO))
288 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
289 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
292 if (!LoadSettings()) {
293 fprintf(stderr, "Failed to load config, creating default\n");
296 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
300 if (SDL_GL_LoadLibrary(NULL) == -1) {
301 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
306 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
307 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
308 SDL_DisplayMode mode;
309 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
311 if ((mode.w < 640) || (mode.h < 480))
312 continue; // sane lower limit.
313 pair<int,int> resolution(mode.w, mode.h);
314 resolutions.insert(resolution);
318 if (resolutions.empty()) {
319 const std::string error = "No suitable video resolutions found.";
320 cerr << error << endl;
321 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
326 if (cmdline("showresolutions")) {
327 printf("Available resolutions:\n");
328 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
329 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
333 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
334 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
336 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
337 if ((fullscreen || cmdline("fullscreen")) && !cmdline("windowed")) {
339 sdlflags |= SDL_WINDOW_FULLSCREEN;
341 if (!cmdline("nomousegrab"))
342 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
344 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
345 kContextWidth, kContextHeight, sdlflags);
348 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
349 fprintf(stderr, "forcing 640x480...\n");
351 kContextHeight = 480;
352 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
353 kContextWidth, kContextHeight, sdlflags);
355 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
356 fprintf(stderr, "forcing 640x480 windowed mode...\n");
357 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
358 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
359 kContextWidth, kContextHeight, sdlflags);
362 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
368 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
370 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
375 SDL_GL_MakeCurrent(sdlwindow, glctx);
377 if (!lookup_all_glsyms()) {
378 fprintf(stderr, "Missing required OpenGL functions.\n");
384 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
386 fprintf(stderr, "Failed to get a double-buffered context.\n");
391 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
392 SDL_GL_SetSwapInterval(1);
395 if (!cmdline("nomousegrab"))
396 SDL_SetRelativeMouseMode(SDL_TRUE);
400 GLint width = kContextWidth;
401 GLint height = kContextHeight;
402 gMidPoint.h = width / 2;
403 gMidPoint.v = height / 2;
405 screenheight = height;
408 newscreenwidth = screenwidth;
409 newscreenheight = screenheight;
411 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
412 pair<int,int> startresolution(width,height);
413 if (resolutions.find(startresolution) == resolutions.end()) {
414 resolutions.insert(startresolution);
423 static void DoMouse()
426 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
427 deltah *= usermousesensitivity;
428 deltav *= usermousesensitivity;
429 mousecoordh += deltah;
430 mousecoordv += deltav;
433 else if (mousecoordh >= kContextWidth)
434 mousecoordh = kContextWidth - 1;
437 else if (mousecoordv >= kContextHeight)
438 mousecoordv = kContextHeight - 1;
443 void DoFrameRate (int update)
445 static long frames = 0;
447 static AbsoluteTime time = {0, 0};
448 static AbsoluteTime frametime = {0, 0};
449 AbsoluteTime currTime = UpTime ();
450 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
452 if (0 > deltaTime) // if negative microseconds
453 deltaTime /= -1000000.0;
454 else // else milliseconds
457 multiplier = deltaTime;
458 if (multiplier < .001)
463 frametime = currTime; // reset for next time interval
465 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
467 if (0 > deltaTime) // if negative microseconds
468 deltaTime /= -1000000.0;
469 else // else milliseconds
472 if (0.001 <= deltaTime) { // has update interval passed
474 time = currTime; // reset for next time interval
483 static float sps = 200;
485 static float oldmult;
491 fps = 1 / multiplier;
493 count = multiplier * sps;
497 realmultiplier = multiplier;
498 multiplier *= gamespeed;
505 multiplier *= .00001;
506 if (slomo && !mainmenu)
507 multiplier *= slomospeed;
508 oldmult = multiplier;
509 multiplier /= (float)count;
515 for (int i = 0; i < count; i++) {
518 multiplier = oldmult;
521 /* - Debug code to test how many channels were active on average per frame
522 static long frames = 0;
524 static AbsoluteTime start = {0,0};
525 AbsoluteTime currTime = UpTime ();
526 static int num_channels = 0;
528 num_channels += OPENAL_GetChannelsPlaying();
529 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
531 if (0 > deltaTime) // if negative microseconds
532 deltaTime /= -1000000.0;
533 else // else milliseconds
541 float avg_channels = (float)num_channels / (float)frames;
543 ofstream opstream("log.txt",ios::app);
544 opstream << "Average frame count: ";
546 opstream << " frames - ";
547 opstream << avg_channels;
548 opstream << " per frame.\n";
555 if ( stereomode == stereoNone ) {
556 DrawGLScene(stereoCenter);
558 DrawGLScene(stereoLeft);
559 DrawGLScene(stereoRight);
563 // --------------------------------------------------------------------------
571 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
572 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
575 // cheat here...static destructors are calling glDeleteTexture() after
576 // the context is destroyed and libGL unloaded by SDL_Quit().
577 pglDeleteTextures = glDeleteTextures_doNothing;
578 #endif // __MINGW32__
582 // --------------------------------------------------------------------------
584 static bool IsFocused()
586 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
592 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
593 static char *findBinaryInPath(const char *bin, char *envr)
595 size_t alloc_size = 0;
602 ptr = strchr(start, ':'); /* find next $PATH separator. */
606 size = strlen(start) + strlen(bin) + 2;
607 if (size > alloc_size) {
608 char *x = (char *) realloc(exe, size);
619 /* build full binary path... */
621 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
625 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
626 strcpy(exe, start); /* i'm lazy. piss off. */
630 start = ptr + 1; /* start points to beginning of next element. */
631 } while (ptr != NULL);
636 return(NULL); /* doesn't exist in path. */
637 } /* findBinaryInPath */
640 char *calcBaseDir(const char *argv0)
642 /* If there isn't a path on argv0, then look through the $PATH for it. */
646 const char *ptr = strrchr((char *)argv0, '/');
647 if (strchr(argv0, '/')) {
648 retval = strdup(argv0);
650 *((char *) strrchr(retval, '/')) = '\0';
654 envr = getenv("PATH");
660 retval = findBinaryInPath(argv0, envr);
665 static inline void chdirToAppPath(const char *argv0)
667 char *dir = calcBaseDir(argv0);
669 #if (defined(__APPLE__) && defined(__MACH__))
670 // Chop off /Contents/MacOS if it's at the end of the string, so we
671 // land in the base of the app bundle.
672 const size_t len = strlen(dir);
673 const char *bundledirs = "/Contents/MacOS";
674 const size_t bundledirslen = strlen(bundledirs);
675 if (len > bundledirslen) {
676 char *ptr = (dir + len) - bundledirslen;
677 if (strcasecmp(ptr, bundledirs) == 0)
688 int main(int argc, char **argv)
693 // !!! FIXME: we could use a Win32 API for this. --ryan.
695 chdirToAppPath(argv[0]);
704 //ofstream os("error.txt");
706 //ofstream os("log.txt");
712 while (!gDone && !tryquit) {
716 // check windows messages
723 while ( SDL_PollEvent( &e ) ) {
724 if (!sdlEventProc(e)) {
735 // allow game chance to pause
740 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
751 } catch (const std::exception& error) {
754 std::string e = "Caught exception: ";
759 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
769 // --------------------------------------------------------------------------
772 bool LoadImage(const char * fname, TGAImageRec & tex)
774 if ( tex.data == NULL )
777 return load_image(fname, tex);
780 void ScreenShot(const char * fname)
787 static bool load_image(const char *file_name, TGAImageRec &tex)
789 const char *ptr = strrchr((char *)file_name, '.');
791 if (strcasecmp(ptr + 1, "png") == 0)
792 return load_png(file_name, tex);
793 else if (strcasecmp(ptr + 1, "jpg") == 0)
794 return load_jpg(file_name, tex);
797 STUBBED("Unsupported image type");
802 struct my_error_mgr {
803 struct jpeg_error_mgr pub; /* "public" fields */
804 jmp_buf setjmp_buffer; /* for return to caller */
806 typedef struct my_error_mgr * my_error_ptr;
809 static void my_error_exit(j_common_ptr cinfo)
811 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
812 longjmp(err->setjmp_buffer, 1);
815 /* stolen from public domain example.c code in libjpg distribution. */
816 static bool load_jpg(const char *file_name, TGAImageRec &tex)
818 struct jpeg_decompress_struct cinfo;
819 struct my_error_mgr jerr;
820 JSAMPROW buffer[1]; /* Output row buffer */
821 int row_stride; /* physical row width in output buffer */
822 FILE *infile = fopen(file_name, "rb");
827 cinfo.err = jpeg_std_error(&jerr.pub);
828 jerr.pub.error_exit = my_error_exit;
829 if (setjmp(jerr.setjmp_buffer)) {
830 jpeg_destroy_decompress(&cinfo);
835 jpeg_create_decompress(&cinfo);
836 jpeg_stdio_src(&cinfo, infile);
837 (void) jpeg_read_header(&cinfo, TRUE);
839 cinfo.out_color_space = JCS_RGB;
840 cinfo.quantize_colors = 0;
841 (void) jpeg_calc_output_dimensions(&cinfo);
842 (void) jpeg_start_decompress(&cinfo);
844 row_stride = cinfo.output_width * cinfo.output_components;
845 tex.sizeX = cinfo.output_width;
846 tex.sizeY = cinfo.output_height;
849 while (cinfo.output_scanline < cinfo.output_height) {
850 buffer[0] = (JSAMPROW)(char *)tex.data +
851 ((cinfo.output_height - 1) - cinfo.output_scanline) * row_stride;
852 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
855 (void) jpeg_finish_decompress(&cinfo);
856 jpeg_destroy_decompress(&cinfo);
863 /* stolen from public domain example.c code in libpng distribution. */
864 static bool load_png(const char *file_name, TGAImageRec &tex)
866 bool hasalpha = false;
867 png_structp png_ptr = NULL;
868 png_infop info_ptr = NULL;
869 png_uint_32 width, height;
870 int bit_depth, color_type, interlace_type;
871 png_byte **rows = NULL;
873 png_byte **row_pointers = NULL;
874 FILE *fp = fopen(file_name, "rb");
877 cerr << file_name << " not found" << endl;
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);
914 png_byte *dst = tex.data;
915 for (int i = height - 1; i >= 0; i--) {
916 png_byte *src = row_pointers[i];
917 for (int j = 0; j < width; j++) {
929 png_byte *dst = tex.data;
930 int pitch = width * 4;
931 for (int i = height - 1; i >= 0; i--, dst += pitch)
932 memcpy(dst, row_pointers[i], pitch);
942 cerr << "There was a problem loading " << file_name << endl;
944 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
951 bool save_image(const char *file_name)
953 const char *ptr = strrchr((char *)file_name, '.');
955 if (strcasecmp(ptr + 1, "png") == 0)
956 return save_png(file_name);
959 STUBBED("Unsupported image type");
964 static bool save_png(const char *file_name)
967 png_structp png_ptr = NULL;
968 png_infop info_ptr = NULL;
971 fp = fopen(file_name, "wb");
975 png_bytep *row_pointers = new png_bytep[kContextHeight];
976 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
977 if ((!screenshot) || (!row_pointers))
981 glReadPixels(0, 0, kContextWidth, kContextHeight,
982 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
983 if (glGetError() != GL_NO_ERROR)
986 for (int i = 0; i < kContextHeight; i++)
987 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight - 1) - i)) * 3);
989 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
993 info_ptr = png_create_info_struct(png_ptr);
994 if (info_ptr == NULL)
997 if (setjmp(png_jmpbuf(png_ptr)))
1000 png_init_io(png_ptr, fp);
1002 if (setjmp(png_jmpbuf(png_ptr)))
1005 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1006 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1007 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1009 png_write_info(png_ptr, info_ptr);
1011 if (setjmp(png_jmpbuf(png_ptr)))
1014 png_write_image(png_ptr, row_pointers);
1016 if (setjmp(png_jmpbuf(png_ptr)))
1019 png_write_end(png_ptr, NULL);
1023 png_destroy_write_struct(&png_ptr, &info_ptr);
1024 delete[] screenshot;
1025 delete[] row_pointers;
1029 unlink(ConvertFileName(file_name));