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.
23 #define UINT8 WIN32API_UINT8
24 #define UINT16 WIN32API_UINT16
25 #define boolean WIN32API_boolean
54 static bool load_image(const char * fname, TGAImageRec & tex);
55 static bool load_png(const char * fname, TGAImageRec & tex);
56 static bool load_jpg(const char * fname, TGAImageRec & tex);
57 static bool save_image(const char * fname);
58 static bool save_png(const char * fname);
61 #include "openal_wrapper.h"
65 #pragma comment(lib, "opengl32.lib")
66 #pragma comment(lib, "glu32.lib")
67 #pragma comment(lib, "glaux.lib")
70 extern bool buttons[3];
71 extern float multiplier;
72 extern float screenwidth,screenheight;
74 extern float realmultiplier;
76 extern bool ismotionblur;
77 extern float usermousesensitivity;
79 extern bool floatjump;
80 extern bool cellophane;
82 //extern int terraindetail;
83 //extern int texdetail;
84 extern float terraindetail;
85 extern float texdetail;
86 extern int bloodtoggle;
88 extern bool autoslomo;
90 extern bool musictoggle;
91 extern bool trilinear;
92 extern float gamespeed;
93 extern int difficulty;
94 extern bool damageeffects;
95 extern int numplayers;
97 extern bool invertmouse;
98 extern bool texttoggle;
99 extern bool ambientsound;
100 extern bool mousejump;
102 extern Person player[maxplayers];
104 extern bool stillloading;
105 extern bool showpoints;
106 extern bool alwaysblur;
107 extern bool immediate;
108 extern bool velocityblur;
109 extern bool debugmode;
111 /*extern*/ bool gameFocused;
112 extern int kBitsPerPixel;
113 extern float slomospeed;
114 extern float slomofreq;
115 extern float oldgamespeed;
124 #include "MacCompatibility.h"
127 #include <shellapi.h>
132 #include "res/resource.h"
138 SDL_Rect **resolutions = NULL;
139 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
140 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
141 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
142 static SDL_Rect *hardcoded_resolutions[] = {
151 unsigned int resolutionDepths[8][2] = {0};
153 bool selectDetail(int & width, int & height, int & bpp, int & detail);
154 int closestResolution(int width, int height);
155 int resolutionID(int width, int height);
157 void ReportError (char * strError);
159 void SetupDSpFullScreen();
162 void DrawGL(Game & game);
164 void CreateGLWindow (void);
165 Boolean SetUp (Game & game);
166 void DoKey (SInt8 theKey, SInt8 theCode);
167 void DoUpdate (Game & game);
173 // statics/globals (internal only) ------------------------------------------
175 typedef struct tagPOINT {
184 #pragma warning(push)
185 #pragma warning(disable: 4273)
188 #define GL_FUNC(ret,fn,params,call,rt) \
190 static ret (GLAPIENTRY *p##fn) params = NULL; \
191 ret GLAPIENTRY fn params { rt p##fn call; } \
200 static bool lookup_glsym(const char *funcname, void **func)
202 *func = SDL_GL_GetProcAddress(funcname);
205 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
211 static bool lookup_all_glsyms(void)
214 #define GL_FUNC(ret,fn,params,call,rt) \
215 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
221 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
228 void sdlGetCursorPos(POINT *pt)
231 SDL_GetMouseState(&x, &y);
235 #define GetCursorPos(x) sdlGetCursorPos(x)
236 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
237 #define ScreenToClient(x, pt)
238 #define ClientToScreen(x, pt)
242 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
247 static bool g_button, fullscreen = true;
258 kForegroundSleep = 10,
259 kBackgroundSleep = 10000
266 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
269 char gcstrMode [256] = "";
271 UInt32 gSleepTime = kForegroundSleep;
272 Boolean gDone = false, gfFrontProcess = true;
277 static int _argc = 0;
278 static char **_argv = NULL;
281 bool cmdline(const char *cmd)
283 for (int i = 1; i < _argc; i++)
285 char *arg = _argv[i];
288 if (strcasecmp(arg, cmd) == 0)
296 // --------------------------------------------------------------------------
298 void ReportError (char * strError)
300 #ifdef _MSC_VER // !!! FIXME. --ryan.
301 throw std::exception( strError);
304 /* char errMsgCStr [256];
307 sprintf (errMsgCStr, "%s", strError);
309 // out as debug string
310 CToPStr (strErr, errMsgCStr);
315 void SetupDSpFullScreen ()
325 //-----------------------------------------------------------------------------------------------------------------------
329 void DrawGL (Game & game)
335 static KeyMap g_theKeys;
337 void SetKey( int key)
339 g_theKeys[ key >> 3] |= (1 << (key & 7));
342 void ClearKey( int key)
344 g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
347 void GetKeys( unsigned char theKeys[16])
349 memcpy( theKeys, &g_theKeys, 16);
358 static void initSDLKeyTable(void) {}
360 #define MAX_SDLKEYS SDLK_LAST
361 static unsigned short KeyTable[MAX_SDLKEYS];
363 static void initSDLKeyTable(void)
365 memset(KeyTable, 0xFF, sizeof (KeyTable));
366 KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
367 KeyTable[SDLK_TAB] = MAC_TAB_KEY;
368 KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
369 KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
370 KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
371 KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
372 KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
373 KeyTable[SDLK_END] = MAC_END_KEY;
374 KeyTable[SDLK_HOME] = MAC_HOME_KEY;
375 KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
376 KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
377 KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
378 KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
379 KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
380 KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
381 KeyTable[SDLK_0] = MAC_0_KEY;
382 KeyTable[SDLK_1] = MAC_1_KEY;
383 KeyTable[SDLK_2] = MAC_2_KEY;
384 KeyTable[SDLK_3] = MAC_3_KEY;
385 KeyTable[SDLK_4] = MAC_4_KEY;
386 KeyTable[SDLK_5] = MAC_5_KEY;
387 KeyTable[SDLK_6] = MAC_6_KEY;
388 KeyTable[SDLK_7] = MAC_7_KEY;
389 KeyTable[SDLK_8] = MAC_8_KEY;
390 KeyTable[SDLK_9] = MAC_9_KEY;
391 KeyTable[SDLK_a] = MAC_A_KEY;
392 KeyTable[SDLK_b] = MAC_B_KEY;
393 KeyTable[SDLK_c] = MAC_C_KEY;
394 KeyTable[SDLK_d] = MAC_D_KEY;
395 KeyTable[SDLK_e] = MAC_E_KEY;
396 KeyTable[SDLK_f] = MAC_F_KEY;
397 KeyTable[SDLK_g] = MAC_G_KEY;
398 KeyTable[SDLK_h] = MAC_H_KEY;
399 KeyTable[SDLK_i] = MAC_I_KEY;
400 KeyTable[SDLK_j] = MAC_J_KEY;
401 KeyTable[SDLK_k] = MAC_K_KEY;
402 KeyTable[SDLK_l] = MAC_L_KEY;
403 KeyTable[SDLK_m] = MAC_M_KEY;
404 KeyTable[SDLK_n] = MAC_N_KEY;
405 KeyTable[SDLK_o] = MAC_O_KEY;
406 KeyTable[SDLK_p] = MAC_P_KEY;
407 KeyTable[SDLK_q] = MAC_Q_KEY;
408 KeyTable[SDLK_r] = MAC_R_KEY;
409 KeyTable[SDLK_s] = MAC_S_KEY;
410 KeyTable[SDLK_t] = MAC_T_KEY;
411 KeyTable[SDLK_u] = MAC_U_KEY;
412 KeyTable[SDLK_v] = MAC_V_KEY;
413 KeyTable[SDLK_w] = MAC_W_KEY;
414 KeyTable[SDLK_x] = MAC_X_KEY;
415 KeyTable[SDLK_y] = MAC_Y_KEY;
416 KeyTable[SDLK_z] = MAC_Z_KEY;
417 KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
418 KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
419 KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
420 KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
421 KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
422 KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
423 KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
424 KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
425 KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
426 KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
427 KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
428 KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
429 KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
430 KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
431 KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
432 KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
433 KeyTable[SDLK_F1] = MAC_F1_KEY;
434 KeyTable[SDLK_F2] = MAC_F2_KEY;
435 KeyTable[SDLK_F3] = MAC_F3_KEY;
436 KeyTable[SDLK_F4] = MAC_F4_KEY;
437 KeyTable[SDLK_F5] = MAC_F5_KEY;
438 KeyTable[SDLK_F6] = MAC_F6_KEY;
439 KeyTable[SDLK_F7] = MAC_F7_KEY;
440 KeyTable[SDLK_F8] = MAC_F8_KEY;
441 KeyTable[SDLK_F9] = MAC_F9_KEY;
442 KeyTable[SDLK_F10] = MAC_F10_KEY;
443 KeyTable[SDLK_F11] = MAC_F11_KEY;
444 KeyTable[SDLK_F12] = MAC_F12_KEY;
445 KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
446 KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
447 KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
448 KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
449 KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
450 KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
451 KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
452 KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
453 KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
454 KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
455 KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
458 static inline int clamp_sdl_mouse_button(Uint8 button)
460 if (button == 2) // right mouse button is button 3 in SDL.
462 else if (button == 3)
465 if ((button >= 1) && (button <= 3))
470 static void sdlEventProc(const SDL_Event &e, Game &game)
473 bool skipkey = false;
478 case SDL_MOUSEMOTION:
479 game.deltah += e.motion.xrel;
480 game.deltav += e.motion.yrel;
483 case SDL_MOUSEBUTTONDOWN:
485 val = clamp_sdl_mouse_button(e.button.button);
486 if ((val >= 0) && (val <= 2))
495 case SDL_MOUSEBUTTONUP:
497 val = clamp_sdl_mouse_button(e.button.button);
498 if ((val >= 0) && (val <= 2))
502 buttons[val] = false;
508 if (e.key.keysym.sym == SDLK_g)
510 if (e.key.keysym.mod & KMOD_CTRL)
513 SDL_GrabMode mode = SDL_GRAB_ON;
514 if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
516 mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
517 mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
519 SDL_WM_GrabInput(mode);
523 else if (e.key.keysym.sym == SDLK_RETURN)
525 if (e.key.keysym.mod & KMOD_ALT)
528 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
532 if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
534 if (KeyTable[e.key.keysym.sym] != 0xffff)
535 SetKey(KeyTable[e.key.keysym.sym]);
538 mod = SDL_GetModState();
540 SetKey(MAC_CONTROL_KEY);
542 SetKey(MAC_OPTION_KEY);
544 SetKey(MAC_COMMAND_KEY);
545 if (mod & KMOD_SHIFT)
546 SetKey(MAC_SHIFT_KEY);
548 SetKey(MAC_CAPS_LOCK_KEY);
553 if (e.key.keysym.sym < SDLK_LAST)
555 if (KeyTable[e.key.keysym.sym] != 0xffff)
556 ClearKey(KeyTable[e.key.keysym.sym]);
559 mod = SDL_GetModState();
560 if ((mod & KMOD_CTRL) == 0)
561 ClearKey(MAC_CONTROL_KEY);
562 if ((mod & KMOD_ALT) == 0)
563 ClearKey(MAC_OPTION_KEY);
564 if ((mod & KMOD_META) == 0)
565 ClearKey(MAC_COMMAND_KEY);
566 if ((mod & KMOD_SHIFT) == 0)
567 ClearKey(MAC_SHIFT_KEY);
568 if ((mod & KMOD_CAPS) == 0)
569 ClearKey(MAC_CAPS_LOCK_KEY);
575 // --------------------------------------------------------------------------
577 static Point gMidPoint;
579 Boolean SetUp (Game & game)
585 randSeed = UpTime().lo;
588 ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
591 usermousesensitivity=1;
620 game.crouchkey=MAC_SHIFT_KEY;
621 game.jumpkey=MAC_SPACE_KEY;
622 game.leftkey=MAC_A_KEY;
623 game.forwardkey=MAC_W_KEY;
624 game.backkey=MAC_S_KEY;
625 game.rightkey=MAC_D_KEY;
626 game.drawkey=MAC_E_KEY;
627 game.throwkey=MAC_Q_KEY;
628 game.attackkey=MAC_MOUSEBUTTON1;
629 game.chatkey=MAC_T_KEY;
635 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
638 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
639 opstream << "Screenwidth:\n";
640 opstream << kContextWidth;
641 opstream << "\nScreenheight:\n";
642 opstream << kContextHeight;
643 opstream << "\nMouse sensitivity:\n";
644 opstream << usermousesensitivity;
645 opstream << "\nBlur(0,1):\n";
646 opstream << ismotionblur;
647 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
649 opstream << "\nFloating jump:\n";
650 opstream << floatjump;
651 opstream << "\nMouse jump:\n";
652 opstream << mousejump;
653 opstream << "\nAmbient sound:\n";
654 opstream << ambientsound;
655 opstream << "\nBlood (0,1,2):\n";
656 opstream << bloodtoggle;
657 opstream << "\nAuto slomo:\n";
658 opstream << autoslomo;
659 opstream << "\nFoliage:\n";
661 opstream << "\nMusic:\n";
662 opstream << musictoggle;
663 opstream << "\nTrilinear:\n";
664 opstream << trilinear;
665 opstream << "\nDecals(shadows,blood puddles,etc):\n";
667 opstream << "\nInvert mouse:\n";
668 opstream << invertmouse;
669 opstream << "\nGamespeed:\n";
670 opstream << gamespeed;
671 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
672 opstream << difficulty;
673 opstream << "\nDamage effects(blackout, doublevision):\n";
674 opstream << damageeffects;
675 opstream << "\nText:\n";
676 opstream << texttoggle;
677 opstream << "\nDebug:\n";
678 opstream << debugmode;
679 opstream << "\nVBL Sync:\n";
681 opstream << "\nShow Points:\n";
682 opstream << showpoints;
683 opstream << "\nAlways Blur:\n";
684 opstream << alwaysblur;
685 opstream << "\nImmediate mode (turn on on G5):\n";
686 opstream << immediate;
687 opstream << "\nVelocity blur:\n";
688 opstream << velocityblur;
689 opstream << "\nVolume:\n";
691 opstream << "\nForward key:\n";
692 opstream << KeyToChar(game.forwardkey);
693 opstream << "\nBack key:\n";
694 opstream << KeyToChar(game.backkey);
695 opstream << "\nLeft key:\n";
696 opstream << KeyToChar(game.leftkey);
697 opstream << "\nRight key:\n";
698 opstream << KeyToChar(game.rightkey);
699 opstream << "\nJump key:\n";
700 opstream << KeyToChar(game.jumpkey);
701 opstream << "\nCrouch key:\n";
702 opstream << KeyToChar(game.crouchkey);
703 opstream << "\nDraw key:\n";
704 opstream << KeyToChar(game.drawkey);
705 opstream << "\nThrow key:\n";
706 opstream << KeyToChar(game.throwkey);
707 opstream << "\nAttack key:\n";
708 opstream << KeyToChar(game.attackkey);
709 opstream << "\nChat key:\n";
710 opstream << KeyToChar(game.chatkey);
715 ipstream.ignore(256,'\n');
716 ipstream >> kContextWidth;
717 ipstream.ignore(256,'\n');
718 ipstream.ignore(256,'\n');
719 ipstream >> kContextHeight;
720 ipstream.ignore(256,'\n');
721 ipstream.ignore(256,'\n');
722 ipstream >> usermousesensitivity;
723 ipstream.ignore(256,'\n');
724 ipstream.ignore(256,'\n');
726 ismotionblur = (i != 0);
727 ipstream.ignore(256,'\n');
728 ipstream.ignore(256,'\n');
730 if(detail!=0)kBitsPerPixel=32;
731 else kBitsPerPixel=16;
732 ipstream.ignore(256,'\n');
733 ipstream.ignore(256,'\n');
735 floatjump = (i != 0);
736 ipstream.ignore(256,'\n');
737 ipstream.ignore(256,'\n');
739 mousejump = (i != 0);
740 ipstream.ignore(256,'\n');
741 ipstream.ignore(256,'\n');
743 ambientsound = (i != 0);
744 ipstream.ignore(256,'\n');
745 ipstream.ignore(256,'\n');
746 ipstream >> bloodtoggle;
747 ipstream.ignore(256,'\n');
748 ipstream.ignore(256,'\n');
750 autoslomo = (i != 0);
751 ipstream.ignore(256,'\n');
752 ipstream.ignore(256,'\n');
755 ipstream.ignore(256,'\n');
756 ipstream.ignore(256,'\n');
758 musictoggle = (i != 0);
759 ipstream.ignore(256,'\n');
760 ipstream.ignore(256,'\n');
762 trilinear = (i != 0);
763 ipstream.ignore(256,'\n');
764 ipstream.ignore(256,'\n');
767 ipstream.ignore(256,'\n');
768 ipstream.ignore(256,'\n');
770 invertmouse = (i != 0);
771 ipstream.ignore(256,'\n');
772 ipstream.ignore(256,'\n');
773 ipstream >> gamespeed;
774 oldgamespeed=gamespeed;
779 ipstream.ignore(256,'\n');
780 ipstream.ignore(256,'\n');
781 ipstream >> difficulty;
782 ipstream.ignore(256,'\n');
783 ipstream.ignore(256,'\n');
785 damageeffects = (i != 0);
786 ipstream.ignore(256,'\n');
787 ipstream.ignore(256,'\n');
789 texttoggle = (i != 0);
790 ipstream.ignore(256,'\n');
791 ipstream.ignore(256,'\n');
793 debugmode = (i != 0);
794 ipstream.ignore(256,'\n');
795 ipstream.ignore(256,'\n');
798 ipstream.ignore(256,'\n');
799 ipstream.ignore(256,'\n');
801 showpoints = (i != 0);
802 ipstream.ignore(256,'\n');
803 ipstream.ignore(256,'\n');
805 alwaysblur = (i != 0);
806 ipstream.ignore(256,'\n');
807 ipstream.ignore(256,'\n');
809 immediate = (i != 0);
810 ipstream.ignore(256,'\n');
811 ipstream.ignore(256,'\n');
813 velocityblur = (i != 0);
814 ipstream.ignore(256,'\n');
815 ipstream.ignore(256,'\n');
817 ipstream.ignore(256,'\n');
818 ipstream.ignore(256,'\n');
820 game.forwardkey=CharToKey(string);
821 ipstream.ignore(256,'\n');
822 ipstream.ignore(256,'\n');
824 game.backkey=CharToKey(string);
825 ipstream.ignore(256,'\n');
826 ipstream.ignore(256,'\n');
828 game.leftkey=CharToKey(string);
829 ipstream.ignore(256,'\n');
830 ipstream.ignore(256,'\n');
832 game.rightkey=CharToKey(string);
833 ipstream.ignore(256,'\n');
834 ipstream.ignore(256,'\n');
836 game.jumpkey=CharToKey(string);
837 ipstream.ignore(256,'\n');
838 ipstream.ignore(256,'\n');
840 game.crouchkey=CharToKey(string);
841 ipstream.ignore(256,'\n');
842 ipstream.ignore(256,'\n');
844 game.drawkey=CharToKey(string);
845 ipstream.ignore(256,'\n');
846 ipstream.ignore(256,'\n');
848 game.throwkey=CharToKey(string);
849 ipstream.ignore(256,'\n');
850 ipstream.ignore(256,'\n');
852 game.attackkey=CharToKey(string);
853 ipstream.ignore(256,'\n');
854 ipstream.ignore(256,'\n');
856 game.chatkey=CharToKey(string);
859 if(detail>2)detail=2;
860 if(detail<0)detail=0;
861 if(screenwidth<0)screenwidth=640;
862 if(screenheight<0)screenheight=480;
863 #if !USE_SDL // we'll take anything that works.
864 if(screenwidth>3000)screenwidth=640;
865 if(screenheight>3000)screenheight=480;
868 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
873 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
875 SetupDSpFullScreen();
878 if (!SDL_WasInit(SDL_INIT_VIDEO))
880 if (SDL_Init(SDL_INIT_VIDEO) == -1)
882 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
886 if (SDL_GL_LoadLibrary(NULL) == -1)
888 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
893 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
894 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
895 res = hardcoded_resolutions;
897 // reverse list (it was sorted biggest to smallest by SDL)...
899 for (count = 0; res[count]; count++)
901 if ((res[count]->w < 640) || (res[count]->h < 480))
902 break; // sane lower limit.
905 static SDL_Rect *resolutions_block = NULL;
906 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
907 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
908 if ((resolutions_block == NULL) || (resolutions == NULL))
911 fprintf(stderr, "Out of memory!\n");
915 resolutions[count--] = NULL;
916 for (int i = 0; count >= 0; i++, count--)
918 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
919 resolutions[count] = &resolutions_block[count];
922 if (cmdline("showresolutions"))
924 printf("Resolutions we think are okay:\n");
925 for (int i = 0; resolutions[i]; i++)
926 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
930 Uint32 sdlflags = SDL_OPENGL;
931 if (!cmdline("windowed"))
932 sdlflags |= SDL_FULLSCREEN;
934 SDL_WM_SetCaption("Lugaru", "Lugaru");
938 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
940 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
942 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
943 fprintf(stderr, "forcing 640x480...\n");
945 kContextHeight = 480;
946 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
948 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
949 fprintf(stderr, "forcing 640x480 windowed mode...\n");
950 sdlflags &= ~SDL_FULLSCREEN;
951 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
953 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
960 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
962 fprintf(stderr, "Failed to get double buffered GL context!\n");
967 if (!lookup_all_glsyms())
973 if (!cmdline("nomousegrab"))
974 SDL_WM_GrabInput(SDL_GRAB_ON);
977 glClear( GL_COLOR_BUFFER_BIT );
981 glDisable( GL_ALPHA_TEST);
982 glDisable( GL_BLEND);
983 glDisable( GL_DEPTH_TEST);
984 // glDisable( GL_DITHER);
986 glDisable( GL_LIGHTING);
987 glDisable( GL_LOGIC_OP);
988 glDisable( GL_STENCIL_TEST);
989 glDisable( GL_TEXTURE_1D);
990 glDisable( GL_TEXTURE_2D);
991 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
992 glPixelTransferi( GL_RED_SCALE, 1);
993 glPixelTransferi( GL_RED_BIAS, 0);
994 glPixelTransferi( GL_GREEN_SCALE, 1);
995 glPixelTransferi( GL_GREEN_BIAS, 0);
996 glPixelTransferi( GL_BLUE_SCALE, 1);
997 glPixelTransferi( GL_BLUE_BIAS, 0);
998 glPixelTransferi( GL_ALPHA_SCALE, 1);
999 glPixelTransferi( GL_ALPHA_BIAS, 0);
1001 // set initial rendering states
1002 glShadeModel( GL_SMOOTH);
1003 glClearDepth( 1.0f);
1004 glDepthFunc( GL_LEQUAL);
1005 glDepthMask( GL_TRUE);
1006 // glDepthRange( FRONT_CLIP, BACK_CLIP);
1007 glEnable( GL_DEPTH_TEST);
1008 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
1009 glCullFace( GL_FRONT);
1010 glEnable( GL_CULL_FACE);
1011 glEnable( GL_LIGHTING);
1012 // glEnable( GL_LIGHT_MODEL_AMBIENT);
1013 glEnable( GL_DITHER);
1014 glEnable( GL_COLOR_MATERIAL);
1015 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1016 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1017 glAlphaFunc( GL_GREATER, 0.5f);
1020 if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION ||
1021 iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION ||
1022 ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION)
1024 ReportError("DevIL version is different...exiting!\n");
1032 ilutRenderer(ILUT_OPENGL);
1034 ilEnable(IL_ORIGIN_SET);
1035 ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
1038 GLint width = kContextWidth;
1039 GLint height = kContextHeight;
1040 gMidPoint.h = width / 2;
1041 gMidPoint.v = height / 2;
1043 screenheight=height;
1045 game.newdetail=detail;
1046 game.newscreenwidth=screenwidth;
1047 game.newscreenheight=screenheight;
1055 static void DoMouse(Game & game)
1058 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1060 game.deltah *= usermousesensitivity;
1061 game.deltav *= usermousesensitivity;
1062 game.mousecoordh += game.deltah;
1063 game.mousecoordv += game.deltav;
1064 if (game.mousecoordh < 0)
1065 game.mousecoordh = 0;
1066 else if (game.mousecoordh >= kContextWidth)
1067 game.mousecoordh = kContextWidth - 1;
1068 if (game.mousecoordv < 0)
1069 game.mousecoordv = 0;
1070 else if (game.mousecoordv >= kContextHeight)
1071 game.mousecoordv = kContextHeight - 1;
1078 // --------------------------------------------------------------------------
1080 void DoKey (SInt8 theKey, SInt8 theCode)
1085 // --------------------------------------------------------------------------
1089 void DoFrameRate (int update)
1091 static long frames = 0;
1093 static AbsoluteTime time = {0,0};
1094 static AbsoluteTime frametime = {0,0};
1095 AbsoluteTime currTime = UpTime ();
1096 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1098 if (0 > deltaTime) // if negative microseconds
1099 deltaTime /= -1000000.0;
1100 else // else milliseconds
1101 deltaTime /= 1000.0;
1103 multiplier=deltaTime;
1104 if(multiplier<.001)multiplier=.001;
1105 if(multiplier>10)multiplier=10;
1106 if(update)frametime = currTime; // reset for next time interval
1108 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1110 if (0 > deltaTime) // if negative microseconds
1111 deltaTime /= -1000000.0;
1112 else // else milliseconds
1113 deltaTime /= 1000.0;
1115 if (0.001 <= deltaTime) // has update interval passed
1118 time = currTime; // reset for next time interval
1125 void DoUpdate (Game & game)
1127 static float sps=200;
1129 static float oldmult;
1132 if(multiplier>.6)multiplier=.6;
1134 game.fps=1/multiplier;
1136 count = multiplier*sps;
1138 //if(count>10)count=10;
1140 realmultiplier=multiplier;
1141 multiplier*=gamespeed;
1142 if(difficulty==1)multiplier*=.9;
1143 if(difficulty==0)multiplier*=.8;
1145 if(game.loading==4)multiplier*=.00001;
1147 if(slomo&&!mainmenu)multiplier*=slomospeed;
1148 //if(freeze)multiplier*=0.00001;
1150 multiplier/=(float)count;
1156 for(int i=0;i<count;i++)
1162 game.TickOnceAfter();
1163 /* - Debug code to test how many channels were active on average per frame
1164 static long frames = 0;
1166 static AbsoluteTime start = {0,0};
1167 AbsoluteTime currTime = UpTime ();
1168 static int num_channels = 0;
1170 num_channels += OPENAL_GetChannelsPlaying();
1171 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1173 if (0 > deltaTime) // if negative microseconds
1174 deltaTime /= -1000000.0;
1175 else // else milliseconds
1176 deltaTime /= 1000.0;
1183 float avg_channels = (float)num_channels / (float)frames;
1185 ofstream opstream("log.txt",ios::app);
1186 opstream << "Average frame count: ";
1188 opstream << " frames - ";
1189 opstream << avg_channels;
1190 opstream << " per frame.\n";
1200 // --------------------------------------------------------------------------
1215 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1216 #include "glstubs.h"
1218 // cheat here...static destructors are calling glDeleteTexture() after
1219 // the context is destroyed and libGL unloaded by SDL_Quit().
1220 pglDeleteTextures = glDeleteTextures_doNothing;
1224 // --------------------------------------------------------------------------
1226 static bool g_focused = true;
1229 static bool IsFocused()
1231 STUBBED("write me");
1236 static void launch_web_browser(const char *url)
1239 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1241 #elif (defined(__APPLE__) && defined(__MACH__))
1242 const char *fmt = "open '%s'";
1243 const size_t len = strlen(fmt) + strlen(url) + 16;
1244 char *buf = new char[len];
1245 snprintf(buf, len, fmt, url);
1249 #elif PLATFORM_LINUX
1250 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1251 const size_t len = strlen(fmt) + strlen(url) + 16;
1252 char *buf = new char[len];
1253 snprintf(buf, len, fmt, url);
1261 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1262 static char *findBinaryInPath(const char *bin, char *envr)
1264 size_t alloc_size = 0;
1272 ptr = strchr(start, ':'); /* find next $PATH separator. */
1276 size = strlen(start) + strlen(bin) + 2;
1277 if (size > alloc_size)
1279 char *x = (char *) realloc(exe, size);
1291 /* build full binary path... */
1293 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1297 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
1299 strcpy(exe, start); /* i'm lazy. piss off. */
1303 start = ptr + 1; /* start points to beginning of next element. */
1304 } while (ptr != NULL);
1309 return(NULL); /* doesn't exist in path. */
1310 } /* findBinaryInPath */
1313 char *calcBaseDir(const char *argv0)
1315 /* If there isn't a path on argv0, then look through the $PATH for it. */
1319 char *ptr = strrchr((char *)argv0, '/');
1320 if (strchr(argv0, '/'))
1322 retval = strdup(argv0);
1324 *(strrchr(retval, '/')) = '\0';
1328 envr = getenv("PATH");
1329 if (!envr) return NULL;
1330 envr = strdup(envr);
1331 if (!envr) return NULL;
1332 retval = findBinaryInPath(argv0, envr);
1337 static inline void chdirToAppPath(const char *argv0)
1339 char *dir = calcBaseDir(argv0);
1342 #if (defined(__APPLE__) && defined(__MACH__))
1343 // Chop off /Contents/MacOS if it's at the end of the string, so we
1344 // land in the base of the app bundle.
1345 const size_t len = strlen(dir);
1346 const char *bundledirs = "/Contents/MacOS";
1347 const size_t bundledirslen = strlen(bundledirs);
1348 if (len > bundledirslen)
1350 char *ptr = (dir + len) - bundledirslen;
1351 if (strcasecmp(ptr, bundledirs) == 0)
1362 int main(int argc, char **argv)
1369 // !!! FIXME: we could use a Win32 API for this. --ryan.
1371 chdirToAppPath(argv[0]);
1376 memset( &g_theKeys, 0, sizeof( KeyMap));
1382 bool regnow = false;
1387 //ofstream os("error.txt");
1389 //ofstream os("log.txt");
1395 while (!gDone&&!game.quit&&(!game.tryquit||!game.registered))
1401 // check windows messages
1407 while( SDL_PollEvent( &e ) )
1409 if( e.type == SDL_QUIT )
1414 sdlEventProc(e, game);
1425 // allow game chance to pause
1426 gameFocused = false;
1430 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1431 STUBBED("give up CPU but sniff the event queue");
1435 regnow = game.registernow;
1440 // if(game.registernow){
1443 #if (defined(__APPLE__) && defined(__MACH__))
1444 launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1445 #elif PLATFORM_LINUX
1446 launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1448 launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1452 #if PLATFORM_LINUX // (this may not be necessary any more.)
1453 _exit(0); // !!! FIXME: hack...crashes on exit!
1457 catch (const std::exception& error)
1461 std::string e = "Caught exception: ";
1466 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1476 // --------------------------------------------------------------------------
1479 int resolutionID(int width, int height)
1483 if(width==640 && height==480)whichres=0;
1484 if(width==800 && height==600)whichres=1;
1485 if(width==1024 && height==768)whichres=2;
1486 if(width==1280 && height==1024)whichres=3;
1487 if(width==1600 && height==1200)whichres=4;
1488 if(width==840 && height==524)whichres=5;
1489 if(width==1024 && height==640)whichres=6;
1490 if(width==1344 && height==840)whichres=7;
1491 if(width==1920 && height==1200)whichres=8;
1496 int closestResolution(int width, int height)
1500 if(width>=640 && height>=480)whichres=0;
1501 if(width>=800 && height>=600)whichres=1;
1502 if(width>=1024 && height>=768)whichres=2;
1503 if(width>=1280 && height>=1024)whichres=3;
1504 if(width>=1600 && height>=1200)whichres=4;
1505 if(width==840 && height==524)whichres=5;
1506 if(width==1024 && height==640)whichres=6;
1507 if(width==1344 && height==840)whichres=7;
1508 if(width>=1920 && height>=1200)whichres=8;
1514 bool selectDetail(int & width, int & height, int & bpp, int & detail)
1518 // currently with SDL, we just use whatever is requested
1519 // and don't care. --ryan.
1521 int whichres = closestResolution(width, height);
1525 if(whichres<=0 || whichres>8){
1563 if ((detail != 0) && (resolutionDepths[whichres][1] != 0))
1567 else if ((detail == 0) && (resolutionDepths[whichres][0] != 0))
1571 else if ((detail != 0) && (resolutionDepths[whichres][0] != 0))
1587 bpp = resolutionDepths[whichres][(detail != 0)];
1593 extern int channels[100];
1594 extern OPENAL_SAMPLE * samp[100];
1595 extern OPENAL_STREAM * strm[20];
1597 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1599 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1600 if (currSample && currSample == samp[chan])
1602 if (OPENAL_GetPaused(channels[chan]))
1604 OPENAL_StopSound(channels[chan]);
1605 channels[chan] = OPENAL_FREE;
1607 else if (OPENAL_IsPlaying(channels[chan]))
1609 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
1610 if (loop_mode & OPENAL_LOOP_OFF)
1612 channels[chan] = OPENAL_FREE;
1618 channels[chan] = OPENAL_FREE;
1621 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
1622 if (channels[chan] < 0)
1624 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
1628 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1630 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1631 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
1633 OPENAL_StopSound(channels[chan]);
1634 OPENAL_Stream_Stop(sptr);
1638 OPENAL_Stream_Stop(sptr);
1639 channels[chan] = OPENAL_FREE;
1642 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
1643 if (channels[chan] < 0)
1645 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
1649 bool LoadImage(const char * fname, TGAImageRec & tex)
1653 if ( tex.data == NULL )
1659 ILstring f = strdup(ConvertFileName(fname));
1666 ilGenImages(1, &iid);
1671 tex.sizeX = ilGetInteger(IL_IMAGE_WIDTH);
1672 tex.sizeY = ilGetInteger(IL_IMAGE_HEIGHT);
1673 tex.bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
1674 ILuint Bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL),
1675 imageSize = tex.sizeX * tex.sizeY * Bpp;
1676 ILubyte *Data = ilGetData();
1677 memcpy(tex.data, Data, imageSize);
1679 // Truvision Targa files are stored as BGR colors
1680 // We want RGB so Blue and Red bytes are switched
1681 if (IL_TGA == ilGetInteger(IL_IMAGE_FORMAT))
1683 // Loop Through The Image Data
1684 for (GLuint i = 0; i < int(imageSize); i += Bpp)
1686 // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
1687 GLbyte temp; // Temporary Variable
1688 temp = tex.data[i]; // Temporarily Store The Value At Image Data 'i'
1689 tex.data[i] = tex.data[i + 2]; // Set The 1st Byte To The Value Of The 3rd Byte
1690 tex.data[i + 2] = temp; // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
1698 ilDeleteImages(1, &iid);
1702 GLuint texid = ilutGLLoadImage(f);
1707 ilutGLBuildMipmaps()
1716 res = load_image(fname, tex);
1717 //if (!res) printf("failed to load %s\n", fname);
1723 void ScreenShot(const char * fname)
1726 ILstring f = strdup(fname);
1733 ilGenImages(1, &iid);
1739 ilDeleteImages(1, &iid);
1749 static bool load_image(const char *file_name, TGAImageRec &tex)
1751 char *ptr = strrchr((char *)file_name, '.');
1754 if (strcasecmp(ptr+1, "png") == 0)
1755 return load_png(file_name, tex);
1756 else if (strcasecmp(ptr+1, "jpg") == 0)
1757 return load_jpg(file_name, tex);
1760 STUBBED("Unsupported image type");
1765 struct my_error_mgr {
1766 struct jpeg_error_mgr pub; /* "public" fields */
1767 jmp_buf setjmp_buffer; /* for return to caller */
1769 typedef struct my_error_mgr * my_error_ptr;
1772 static void my_error_exit(j_common_ptr cinfo)
1774 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1775 longjmp(err->setjmp_buffer, 1);
1778 /* stolen from public domain example.c code in libjpg distribution. */
1779 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1781 struct jpeg_decompress_struct cinfo;
1782 struct my_error_mgr jerr;
1783 JSAMPROW buffer[1]; /* Output row buffer */
1784 int row_stride; /* physical row width in output buffer */
1785 FILE *infile = fopen(file_name, "rb");
1790 cinfo.err = jpeg_std_error(&jerr.pub);
1791 jerr.pub.error_exit = my_error_exit;
1792 if (setjmp(jerr.setjmp_buffer)) {
1793 jpeg_destroy_decompress(&cinfo);
1798 jpeg_create_decompress(&cinfo);
1799 jpeg_stdio_src(&cinfo, infile);
1800 (void) jpeg_read_header(&cinfo, TRUE);
1802 cinfo.out_color_space = JCS_RGB;
1803 cinfo.quantize_colors = 0;
1804 (void) jpeg_calc_output_dimensions(&cinfo);
1805 (void) jpeg_start_decompress(&cinfo);
1807 row_stride = cinfo.output_width * cinfo.output_components;
1808 tex.sizeX = cinfo.output_width;
1809 tex.sizeY = cinfo.output_height;
1812 while (cinfo.output_scanline < cinfo.output_height) {
1813 buffer[0] = (JSAMPROW)(char *)tex.data +
1814 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1815 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1818 (void) jpeg_finish_decompress(&cinfo);
1819 jpeg_destroy_decompress(&cinfo);
1826 /* stolen from public domain example.c code in libpng distribution. */
1827 static bool load_png(const char *file_name, TGAImageRec &tex)
1829 bool hasalpha = false;
1830 png_structp png_ptr = NULL;
1831 png_infop info_ptr = NULL;
1832 png_uint_32 width, height;
1833 int bit_depth, color_type, interlace_type;
1834 png_byte **rows = NULL;
1835 bool retval = false;
1836 png_byte **row_pointers = NULL;
1837 FILE *fp = fopen(file_name, "rb");
1842 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1843 if (png_ptr == NULL)
1846 info_ptr = png_create_info_struct(png_ptr);
1847 if (info_ptr == NULL)
1850 if (setjmp(png_jmpbuf(png_ptr)))
1853 png_init_io(png_ptr, fp);
1854 png_read_png(png_ptr, info_ptr,
1855 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1857 png_get_IHDR(png_ptr, info_ptr, &width, &height,
1858 &bit_depth, &color_type, &interlace_type, NULL, NULL);
1860 if (bit_depth != 8) // transform SHOULD handle this...
1863 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
1866 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
1869 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1870 row_pointers = png_get_rows(png_ptr, info_ptr);
1876 png_byte *dst = tex.data;
1877 for (int i = height-1; i >= 0; i--)
1879 png_byte *src = row_pointers[i];
1880 for (int j = 0; j < width; j++)
1894 png_byte *dst = tex.data;
1895 int pitch = width * 4;
1896 for (int i = height-1; i >= 0; i--, dst += pitch)
1897 memcpy(dst, row_pointers[i], pitch);
1906 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1913 static bool save_image(const char *file_name)
1915 char *ptr = strrchr((char *)file_name, '.');
1918 if (strcasecmp(ptr+1, "png") == 0)
1919 return save_png(file_name);
1922 STUBBED("Unsupported image type");
1927 static bool save_png(const char *file_name)
1930 png_structp png_ptr = NULL;
1931 png_infop info_ptr = NULL;
1932 bool retval = false;
1934 fp = fopen(file_name, "wb");
1938 png_bytep *row_pointers = new png_bytep[kContextHeight];
1939 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1940 if ((!screenshot) || (!row_pointers))
1944 glReadPixels(0, 0, kContextWidth, kContextHeight,
1945 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1946 if (glGetError() != GL_NO_ERROR)
1949 for (int i = 0; i < kContextHeight; i++)
1950 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1952 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1953 if (png_ptr == NULL)
1956 info_ptr = png_create_info_struct(png_ptr);
1957 if (info_ptr == NULL)
1960 if (setjmp(png_jmpbuf(png_ptr)))
1963 png_init_io(png_ptr, fp);
1965 if (setjmp(png_jmpbuf(png_ptr)))
1968 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1969 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1970 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1972 png_write_info(png_ptr, info_ptr);
1974 if (setjmp(png_jmpbuf(png_ptr)))
1977 png_write_image(png_ptr, row_pointers);
1979 if (setjmp(png_jmpbuf(png_ptr)))
1982 png_write_end(png_ptr, NULL);
1986 png_destroy_write_struct(&png_ptr, &info_ptr);
1987 delete[] screenshot;
1988 delete[] row_pointers;
1992 unlink(ConvertFileName(file_name));