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 static 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;
70 //extern int terraindetail;
71 //extern int texdetail;
72 extern float terraindetail;
73 extern float texdetail;
76 extern int numplayers;
78 extern Person player[maxplayers];
79 extern bool stillloading;
81 /*extern*/ bool gameFocused;
83 extern float slomospeed;
84 extern float slomofreq;
94 #include "MacCompatibility.h"
99 #include "win-res/resource.h"
106 SDL_Rect **resolutions = NULL;
107 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
108 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
109 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
110 static SDL_Rect *hardcoded_resolutions[] = {
119 unsigned int resolutionDepths[8][2] = {0};
121 int closestResolution(int width, int height);
122 int resolutionID(int width, int height);
124 void ReportError (char * strError);
126 void DrawGL(Game & game);
128 void CreateGLWindow (void);
129 Boolean SetUp (Game & game);
130 void DoUpdate (Game & game);
136 // statics/globals (internal only) ------------------------------------------
138 typedef struct tagPOINT {
147 #pragma warning(push)
148 #pragma warning(disable: 4273)
151 #define GL_FUNC(ret,fn,params,call,rt) \
153 static ret (GLAPIENTRY *p##fn) params = NULL; \
154 ret GLAPIENTRY fn params { rt p##fn call; } \
163 static bool lookup_glsym(const char *funcname, void **func)
165 *func = SDL_GL_GetProcAddress(funcname);
168 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
174 static bool lookup_all_glsyms(void)
177 #define GL_FUNC(ret,fn,params,call,rt) \
178 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
184 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
191 void sdlGetCursorPos(POINT *pt)
193 SDL_GetMouseState(&(pt->x), &(pt->y));
195 #define GetCursorPos(x) sdlGetCursorPos(x)
196 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
197 #define ScreenToClient(x, pt)
198 #define ClientToScreen(x, pt)
202 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
207 static bool g_button, fullscreen = true;
218 kForegroundSleep = 10,
219 kBackgroundSleep = 10000
226 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
229 char gcstrMode [256] = "";
231 UInt32 gSleepTime = kForegroundSleep;
232 Boolean gDone = false, gfFrontProcess = true;
237 static int _argc = 0;
238 static char **_argv = NULL;
241 bool cmdline(const char *cmd)
243 for (int i = 1; i < _argc; i++)
245 char *arg = _argv[i];
248 if (strcasecmp(arg, cmd) == 0)
256 // --------------------------------------------------------------------------
258 void ReportError (char * strError)
260 #ifdef _MSC_VER // !!! FIXME. --ryan.
261 throw std::exception( strError);
264 /* char errMsgCStr [256];
267 sprintf (errMsgCStr, "%s", strError);
269 // out as debug string
270 CToPStr (strErr, errMsgCStr);
275 //-----------------------------------------------------------------------------------------------------------------------
279 void DrawGL (Game & game)
281 if ( stereomode == stereoNone ) {
282 game.DrawGLScene(stereoCenter);
284 game.DrawGLScene(stereoLeft);
285 game.DrawGLScene(stereoRight);
289 static void sdlEventProc(const SDL_Event &e, Game &game)
296 case SDL_MOUSEMOTION:
297 game.deltah += e.motion.xrel;
298 game.deltav += e.motion.yrel;
302 if ((e.key.keysym.sym == SDLK_g) &&
303 (e.key.keysym.mod & KMOD_CTRL) &&
304 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
305 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
306 } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
307 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
314 // --------------------------------------------------------------------------
316 static Point gMidPoint;
318 Boolean SetUp (Game & game)
324 randSeed = UpTime().lo;
334 DefaultSettings(game);
336 if (!SDL_WasInit(SDL_INIT_VIDEO))
337 if (SDL_Init(SDL_INIT_VIDEO) == -1)
339 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
342 if(!LoadSettings(game)) {
343 fprintf(stderr, "Failed to load config, creating default\n");
346 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
350 if (SDL_GL_LoadLibrary(NULL) == -1)
352 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
357 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
358 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
359 res = hardcoded_resolutions;
361 // reverse list (it was sorted biggest to smallest by SDL)...
363 for (count = 0; res[count]; count++)
365 if ((res[count]->w < 640) || (res[count]->h < 480))
366 break; // sane lower limit.
369 static SDL_Rect *resolutions_block = NULL;
370 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
371 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
372 if ((resolutions_block == NULL) || (resolutions == NULL))
375 fprintf(stderr, "Out of memory!\n");
379 resolutions[count--] = NULL;
380 for (int i = 0; count >= 0; i++, count--)
382 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
383 resolutions[count] = &resolutions_block[count];
386 if (cmdline("showresolutions"))
388 printf("Resolutions we think are okay:\n");
389 for (int i = 0; resolutions[i]; i++)
390 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
393 Uint32 sdlflags = SDL_OPENGL;
394 if (!cmdline("windowed"))
395 sdlflags |= SDL_FULLSCREEN;
397 SDL_WM_SetCaption("Lugaru", "Lugaru");
401 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
402 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
404 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
406 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
407 fprintf(stderr, "forcing 640x480...\n");
409 kContextHeight = 480;
410 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
412 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
413 fprintf(stderr, "forcing 640x480 windowed mode...\n");
414 sdlflags &= ~SDL_FULLSCREEN;
415 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
417 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
424 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
426 fprintf(stderr, "Failed to get double buffered GL context!\n");
431 if (!lookup_all_glsyms())
437 if (!cmdline("nomousegrab"))
438 SDL_WM_GrabInput(SDL_GRAB_ON);
441 glClear( GL_COLOR_BUFFER_BIT );
445 glDisable( GL_ALPHA_TEST);
446 glDisable( GL_BLEND);
447 glDisable( GL_DEPTH_TEST);
448 // glDisable( GL_DITHER);
450 glDisable( GL_LIGHTING);
451 glDisable( GL_LOGIC_OP);
452 glDisable( GL_TEXTURE_1D);
453 glDisable( GL_TEXTURE_2D);
454 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
455 glPixelTransferi( GL_RED_SCALE, 1);
456 glPixelTransferi( GL_RED_BIAS, 0);
457 glPixelTransferi( GL_GREEN_SCALE, 1);
458 glPixelTransferi( GL_GREEN_BIAS, 0);
459 glPixelTransferi( GL_BLUE_SCALE, 1);
460 glPixelTransferi( GL_BLUE_BIAS, 0);
461 glPixelTransferi( GL_ALPHA_SCALE, 1);
462 glPixelTransferi( GL_ALPHA_BIAS, 0);
464 // set initial rendering states
465 glShadeModel( GL_SMOOTH);
467 glDepthFunc( GL_LEQUAL);
468 glDepthMask( GL_TRUE);
469 // glDepthRange( FRONT_CLIP, BACK_CLIP);
470 glEnable( GL_DEPTH_TEST);
471 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
472 glCullFace( GL_FRONT);
473 glEnable( GL_CULL_FACE);
474 glEnable( GL_LIGHTING);
475 // glEnable( GL_LIGHT_MODEL_AMBIENT);
476 glEnable( GL_DITHER);
477 glEnable( GL_COLOR_MATERIAL);
478 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
479 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
480 glAlphaFunc( GL_GREATER, 0.5f);
482 GLint width = kContextWidth;
483 GLint height = kContextHeight;
484 gMidPoint.h = width / 2;
485 gMidPoint.v = height / 2;
489 game.newdetail=detail;
490 game.newscreenwidth=screenwidth;
491 game.newscreenheight=screenheight;
493 if ( CanInitStereo(stereomode) ) {
494 InitStereo(stereomode);
496 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
497 stereomode = stereoNone;
506 static void DoMouse(Game & game)
509 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
511 game.deltah *= usermousesensitivity;
512 game.deltav *= usermousesensitivity;
513 game.mousecoordh += game.deltah;
514 game.mousecoordv += game.deltav;
515 if (game.mousecoordh < 0)
516 game.mousecoordh = 0;
517 else if (game.mousecoordh >= kContextWidth)
518 game.mousecoordh = kContextWidth - 1;
519 if (game.mousecoordv < 0)
520 game.mousecoordv = 0;
521 else if (game.mousecoordv >= kContextHeight)
522 game.mousecoordv = kContextHeight - 1;
527 void DoFrameRate (int update)
529 static long frames = 0;
531 static AbsoluteTime time = {0,0};
532 static AbsoluteTime frametime = {0,0};
533 AbsoluteTime currTime = UpTime ();
534 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
536 if (0 > deltaTime) // if negative microseconds
537 deltaTime /= -1000000.0;
538 else // else milliseconds
541 multiplier=deltaTime;
542 if(multiplier<.001) multiplier=.001;
543 if(multiplier>10) multiplier=10;
544 if(update) frametime = currTime; // reset for next time interval
546 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
548 if (0 > deltaTime) // if negative microseconds
549 deltaTime /= -1000000.0;
550 else // else milliseconds
553 if (0.001 <= deltaTime) // has update interval passed
556 time = currTime; // reset for next time interval
563 void DoUpdate (Game & game)
565 static float sps=200;
567 static float oldmult;
570 if(multiplier>.6)multiplier=.6;
572 game.fps=1/multiplier;
574 count = multiplier*sps;
576 //if(count>10)count=10;
578 realmultiplier=multiplier;
579 multiplier*=gamespeed;
580 if(difficulty==1)multiplier*=.9;
581 if(difficulty==0)multiplier*=.8;
583 if(game.loading==4)multiplier*=.00001;
585 if(slomo&&!mainmenu)multiplier*=slomospeed;
586 //if(freeze)multiplier*=0.00001;
588 multiplier/=(float)count;
594 for(int i=0;i<count;i++)
600 game.TickOnceAfter();
601 /* - Debug code to test how many channels were active on average per frame
602 static long frames = 0;
604 static AbsoluteTime start = {0,0};
605 AbsoluteTime currTime = UpTime ();
606 static int num_channels = 0;
608 num_channels += OPENAL_GetChannelsPlaying();
609 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
611 if (0 > deltaTime) // if negative microseconds
612 deltaTime /= -1000000.0;
613 else // else milliseconds
621 float avg_channels = (float)num_channels / (float)frames;
623 ofstream opstream("log.txt",ios::app);
624 opstream << "Average frame count: ";
626 opstream << " frames - ";
627 opstream << avg_channels;
628 opstream << " per frame.\n";
638 // --------------------------------------------------------------------------
651 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
654 // cheat here...static destructors are calling glDeleteTexture() after
655 // the context is destroyed and libGL unloaded by SDL_Quit().
656 pglDeleteTextures = glDeleteTextures_doNothing;
660 // --------------------------------------------------------------------------
662 static bool IsFocused()
664 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
668 static void launch_web_browser(const char *url)
671 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
673 #elif (defined(__APPLE__) && defined(__MACH__))
674 const char *fmt = "open '%s'";
675 const size_t len = strlen(fmt) + strlen(url) + 16;
676 char *buf = new char[len];
677 snprintf(buf, len, fmt, url);
682 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
683 const size_t len = strlen(fmt) + strlen(url) + 16;
684 char *buf = new char[len];
685 snprintf(buf, len, fmt, url);
693 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
694 static char *findBinaryInPath(const char *bin, char *envr)
696 size_t alloc_size = 0;
704 ptr = strchr(start, ':'); /* find next $PATH separator. */
708 size = strlen(start) + strlen(bin) + 2;
709 if (size > alloc_size)
711 char *x = (char *) realloc(exe, size);
723 /* build full binary path... */
725 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
729 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
731 strcpy(exe, start); /* i'm lazy. piss off. */
735 start = ptr + 1; /* start points to beginning of next element. */
736 } while (ptr != NULL);
741 return(NULL); /* doesn't exist in path. */
742 } /* findBinaryInPath */
745 char *calcBaseDir(const char *argv0)
747 /* If there isn't a path on argv0, then look through the $PATH for it. */
751 const char *ptr = strrchr((char *)argv0, '/');
752 if (strchr(argv0, '/'))
754 retval = strdup(argv0);
756 *((char *) strrchr(retval, '/')) = '\0';
760 envr = getenv("PATH");
761 if (!envr) return NULL;
763 if (!envr) return NULL;
764 retval = findBinaryInPath(argv0, envr);
769 static inline void chdirToAppPath(const char *argv0)
771 char *dir = calcBaseDir(argv0);
774 #if (defined(__APPLE__) && defined(__MACH__))
775 // Chop off /Contents/MacOS if it's at the end of the string, so we
776 // land in the base of the app bundle.
777 const size_t len = strlen(dir);
778 const char *bundledirs = "/Contents/MacOS";
779 const size_t bundledirslen = strlen(bundledirs);
780 if (len > bundledirslen)
782 char *ptr = (dir + len) - bundledirslen;
783 if (strcasecmp(ptr, bundledirs) == 0)
794 int main(int argc, char **argv)
801 // !!! FIXME: we could use a Win32 API for this. --ryan.
803 chdirToAppPath(argv[0]);
808 //memset( &g_theKeys, 0, sizeof( KeyMap));
819 //ofstream os("error.txt");
821 //ofstream os("log.txt");
827 while (!gDone&&!game.quit&&(!game.tryquit))
833 // check windows messages
838 if(!game.isWaiting()) {
840 while( SDL_PollEvent( &e ) )
842 if( e.type == SDL_QUIT )
847 sdlEventProc(e, game);
858 // allow game chance to pause
863 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
865 SDL_WaitEvent((SDL_Event*)&evt);
866 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
868 else if (evt.type == SDL_QUIT)
873 regnow = game.registernow;
881 catch (const std::exception& error)
885 std::string e = "Caught exception: ";
890 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
900 // --------------------------------------------------------------------------
902 extern int channels[100];
903 extern OPENAL_SAMPLE * samp[100];
904 extern OPENAL_STREAM * strm[20];
906 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
908 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
909 if (currSample && currSample == samp[chan])
911 if (OPENAL_GetPaused(channels[chan]))
913 OPENAL_StopSound(channels[chan]);
914 channels[chan] = OPENAL_FREE;
916 else if (OPENAL_IsPlaying(channels[chan]))
918 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
919 if (loop_mode & OPENAL_LOOP_OFF)
921 channels[chan] = OPENAL_FREE;
927 channels[chan] = OPENAL_FREE;
930 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
931 if (channels[chan] < 0)
933 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
937 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
939 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
940 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
942 OPENAL_StopSound(channels[chan]);
943 OPENAL_Stream_Stop(sptr);
947 OPENAL_Stream_Stop(sptr);
948 channels[chan] = OPENAL_FREE;
951 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
952 if (channels[chan] < 0)
954 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
959 bool LoadImage(const char * fname, TGAImageRec & tex)
961 if ( tex.data == NULL )
964 return load_image(fname, tex);
967 void ScreenShot(const char * fname)
974 static bool load_image(const char *file_name, TGAImageRec &tex)
976 const char *ptr = strrchr((char *)file_name, '.');
979 if (strcasecmp(ptr+1, "png") == 0)
980 return load_png(file_name, tex);
981 else if (strcasecmp(ptr+1, "jpg") == 0)
982 return load_jpg(file_name, tex);
985 STUBBED("Unsupported image type");
990 struct my_error_mgr {
991 struct jpeg_error_mgr pub; /* "public" fields */
992 jmp_buf setjmp_buffer; /* for return to caller */
994 typedef struct my_error_mgr * my_error_ptr;
997 static void my_error_exit(j_common_ptr cinfo)
999 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1000 longjmp(err->setjmp_buffer, 1);
1003 /* stolen from public domain example.c code in libjpg distribution. */
1004 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1006 struct jpeg_decompress_struct cinfo;
1007 struct my_error_mgr jerr;
1008 JSAMPROW buffer[1]; /* Output row buffer */
1009 int row_stride; /* physical row width in output buffer */
1010 FILE *infile = fopen(file_name, "rb");
1015 cinfo.err = jpeg_std_error(&jerr.pub);
1016 jerr.pub.error_exit = my_error_exit;
1017 if (setjmp(jerr.setjmp_buffer)) {
1018 jpeg_destroy_decompress(&cinfo);
1023 jpeg_create_decompress(&cinfo);
1024 jpeg_stdio_src(&cinfo, infile);
1025 (void) jpeg_read_header(&cinfo, TRUE);
1027 cinfo.out_color_space = JCS_RGB;
1028 cinfo.quantize_colors = 0;
1029 (void) jpeg_calc_output_dimensions(&cinfo);
1030 (void) jpeg_start_decompress(&cinfo);
1032 row_stride = cinfo.output_width * cinfo.output_components;
1033 tex.sizeX = cinfo.output_width;
1034 tex.sizeY = cinfo.output_height;
1037 while (cinfo.output_scanline < cinfo.output_height) {
1038 buffer[0] = (JSAMPROW)(char *)tex.data +
1039 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1040 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1043 (void) jpeg_finish_decompress(&cinfo);
1044 jpeg_destroy_decompress(&cinfo);
1051 /* stolen from public domain example.c code in libpng distribution. */
1052 static bool load_png(const char *file_name, TGAImageRec &tex)
1054 bool hasalpha = false;
1055 png_structp png_ptr = NULL;
1056 png_infop info_ptr = NULL;
1057 png_uint_32 width, height;
1058 int bit_depth, color_type, interlace_type;
1059 png_byte **rows = NULL;
1060 bool retval = false;
1061 png_byte **row_pointers = NULL;
1062 FILE *fp = fopen(file_name, "rb");
1067 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1068 if (png_ptr == NULL)
1071 info_ptr = png_create_info_struct(png_ptr);
1072 if (info_ptr == NULL)
1075 if (setjmp(png_jmpbuf(png_ptr)))
1078 png_init_io(png_ptr, fp);
1079 png_read_png(png_ptr, info_ptr,
1080 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1082 png_get_IHDR(png_ptr, info_ptr, &width, &height,
1083 &bit_depth, &color_type, &interlace_type, NULL, NULL);
1085 if (bit_depth != 8) // transform SHOULD handle this...
1088 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
1091 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
1094 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1095 row_pointers = png_get_rows(png_ptr, info_ptr);
1101 png_byte *dst = tex.data;
1102 for (int i = height-1; i >= 0; i--)
1104 png_byte *src = row_pointers[i];
1105 for (int j = 0; j < width; j++)
1119 png_byte *dst = tex.data;
1120 int pitch = width * 4;
1121 for (int i = height-1; i >= 0; i--, dst += pitch)
1122 memcpy(dst, row_pointers[i], pitch);
1131 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1138 static bool save_image(const char *file_name)
1140 const char *ptr = strrchr((char *)file_name, '.');
1143 if (strcasecmp(ptr+1, "png") == 0)
1144 return save_png(file_name);
1147 STUBBED("Unsupported image type");
1152 static bool save_png(const char *file_name)
1155 png_structp png_ptr = NULL;
1156 png_infop info_ptr = NULL;
1157 bool retval = false;
1159 fp = fopen(file_name, "wb");
1163 png_bytep *row_pointers = new png_bytep[kContextHeight];
1164 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1165 if ((!screenshot) || (!row_pointers))
1169 glReadPixels(0, 0, kContextWidth, kContextHeight,
1170 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1171 if (glGetError() != GL_NO_ERROR)
1174 for (int i = 0; i < kContextHeight; i++)
1175 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1177 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1178 if (png_ptr == NULL)
1181 info_ptr = png_create_info_struct(png_ptr);
1182 if (info_ptr == NULL)
1185 if (setjmp(png_jmpbuf(png_ptr)))
1188 png_init_io(png_ptr, fp);
1190 if (setjmp(png_jmpbuf(png_ptr)))
1193 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1194 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1195 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1197 png_write_info(png_ptr, info_ptr);
1199 if (setjmp(png_jmpbuf(png_ptr)))
1202 png_write_image(png_ptr, row_pointers);
1204 if (setjmp(png_jmpbuf(png_ptr)))
1207 png_write_end(png_ptr, NULL);
1211 png_destroy_write_struct(&png_ptr, &info_ptr);
1212 delete[] screenshot;
1213 delete[] row_pointers;
1217 unlink(ConvertFileName(file_name));