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.
22 /* No need for Visual Leak Detector
47 static bool load_image(const char * fname, TGAImageRec & tex);
48 static bool load_png(const char * fname, TGAImageRec & tex);
49 static bool load_jpg(const char * fname, TGAImageRec & tex);
50 static bool save_image(const char * fname);
51 static bool save_png(const char * fname);
56 #pragma comment(lib, "opengl32.lib")
57 #pragma comment(lib, "glu32.lib")
58 #pragma comment(lib, "glaux.lib")
61 extern bool buttons[3];
62 extern float multiplier;
63 extern float screenwidth,screenheight;
65 extern float realmultiplier;
67 extern bool ismotionblur;
68 extern float usermousesensitivity;
70 extern bool floatjump;
71 extern bool cellophane;
73 //extern int terraindetail;
74 //extern int texdetail;
75 extern float terraindetail;
76 extern float texdetail;
77 extern int bloodtoggle;
79 extern bool autoslomo;
81 extern bool musictoggle;
82 extern bool trilinear;
83 extern float gamespeed;
84 extern int difficulty;
85 extern bool damageeffects;
86 extern int numplayers;
88 extern bool invertmouse;
89 extern bool texttoggle;
90 extern bool ambientsound;
91 extern bool mousejump;
93 extern Person player[maxplayers];
95 extern bool stillloading;
96 extern bool showpoints;
97 extern bool alwaysblur;
98 extern bool immediate;
99 extern bool velocityblur;
100 extern bool debugmode;
102 /*extern*/ bool gameFocused;
103 extern int kBitsPerPixel;
104 extern float slomospeed;
105 extern float slomofreq;
106 extern float oldgamespeed;
115 #include "MacCompatibility.h"
118 #include <shellapi.h>
123 #include "res/resource.h"
129 SDL_Rect **resolutions = NULL;
130 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
131 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
132 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
133 static SDL_Rect *hardcoded_resolutions[] = {
142 unsigned int resolutionDepths[8][2] = {0};
144 bool selectDetail(int & width, int & height, int & bpp, int & detail);
145 int closestResolution(int width, int height);
146 int resolutionID(int width, int height);
148 void ReportError (char * strError);
150 void SetupDSpFullScreen();
153 void DrawGL(Game & game);
155 void CreateGLWindow (void);
156 Boolean SetUp (Game & game);
157 void DoKey (SInt8 theKey, SInt8 theCode);
158 void DoUpdate (Game & game);
164 // statics/globals (internal only) ------------------------------------------
166 typedef struct tagPOINT {
173 #define GL_FUNC(ret,fn,params,call,rt) \
175 static ret GLAPIENTRY (*p##fn) params = NULL; \
176 ret GLAPIENTRY fn params { rt p##fn call; } \
181 static bool lookup_glsym(const char *funcname, void **func)
183 *func = SDL_GL_GetProcAddress(funcname);
186 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
192 static bool lookup_all_glsyms(void)
195 #define GL_FUNC(ret,fn,params,call,rt) \
196 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
202 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
209 void sdlGetCursorPos(POINT *pt)
212 SDL_GetMouseState(&x, &y);
216 #define GetCursorPos(x) sdlGetCursorPos(x)
217 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
218 #define ScreenToClient(x, pt)
219 #define ClientToScreen(x, pt)
220 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
226 static const char g_wndClassName[]={ "LUGARUWINDOWCLASS" };
227 static HINSTANCE g_appInstance;
228 static HWND g_windowHandle;
232 static bool g_button, fullscreen = true;
243 kForegroundSleep = 10,
244 kBackgroundSleep = 10000
251 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
254 char gcstrMode [256] = "";
256 UInt32 gSleepTime = kForegroundSleep;
257 Boolean gDone = false, gfFrontProcess = true;
262 static int _argc = 0;
263 static char **_argv = NULL;
265 bool cmdline(const char *cmd)
267 for (int i = 1; i < _argc; i++)
269 char *arg = _argv[i];
272 if (strcasecmp(arg, cmd) == 0)
280 // --------------------------------------------------------------------------
282 void ReportError (char * strError)
284 #ifdef WIN32 // !!! FIXME. --ryan.
285 throw std::exception( strError);
288 /* char errMsgCStr [256];
291 sprintf (errMsgCStr, "%s", strError);
293 // out as debug string
294 CToPStr (strErr, errMsgCStr);
299 void SetupDSpFullScreen ()
306 DEVMODE dmScreenSettings;
307 memset( &dmScreenSettings, 0, sizeof( dmScreenSettings));
308 dmScreenSettings.dmSize = sizeof( dmScreenSettings);
309 dmScreenSettings.dmPelsWidth = kContextWidth;
310 dmScreenSettings.dmPelsHeight = kContextHeight;
311 dmScreenSettings.dmBitsPerPel = kBitsPerPixel;
312 dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
315 if (ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
317 ReportError( "Could not set display mode");
334 ChangeDisplaySettings( NULL, 0);
342 //-----------------------------------------------------------------------------------------------------------------------
346 void DrawGL (Game & game)
357 static KeyMap g_theKeys;
359 void SetKey( int key)
361 g_theKeys[ key >> 3] |= (1 << (key & 7));
364 void ClearKey( int key)
366 g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
369 void GetKeys( unsigned char theKeys[16])
371 memcpy( theKeys, &g_theKeys, 16);
380 static void initSDLKeyTable(void) {}
382 #define MAX_SDLKEYS SDLK_LAST
383 static unsigned short KeyTable[MAX_SDLKEYS];
385 static void initSDLKeyTable(void)
387 memset(KeyTable, 0xFF, sizeof (KeyTable));
388 KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
389 KeyTable[SDLK_TAB] = MAC_TAB_KEY;
390 KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
391 KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
392 KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
393 KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
394 KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
395 KeyTable[SDLK_END] = MAC_END_KEY;
396 KeyTable[SDLK_HOME] = MAC_HOME_KEY;
397 KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
398 KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
399 KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
400 KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
401 KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
402 KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
403 KeyTable[SDLK_0] = MAC_0_KEY;
404 KeyTable[SDLK_1] = MAC_1_KEY;
405 KeyTable[SDLK_2] = MAC_2_KEY;
406 KeyTable[SDLK_3] = MAC_3_KEY;
407 KeyTable[SDLK_4] = MAC_4_KEY;
408 KeyTable[SDLK_5] = MAC_5_KEY;
409 KeyTable[SDLK_6] = MAC_6_KEY;
410 KeyTable[SDLK_7] = MAC_7_KEY;
411 KeyTable[SDLK_8] = MAC_8_KEY;
412 KeyTable[SDLK_9] = MAC_9_KEY;
413 KeyTable[SDLK_a] = MAC_A_KEY;
414 KeyTable[SDLK_b] = MAC_B_KEY;
415 KeyTable[SDLK_c] = MAC_C_KEY;
416 KeyTable[SDLK_d] = MAC_D_KEY;
417 KeyTable[SDLK_e] = MAC_E_KEY;
418 KeyTable[SDLK_f] = MAC_F_KEY;
419 KeyTable[SDLK_g] = MAC_G_KEY;
420 KeyTable[SDLK_h] = MAC_H_KEY;
421 KeyTable[SDLK_i] = MAC_I_KEY;
422 KeyTable[SDLK_j] = MAC_J_KEY;
423 KeyTable[SDLK_k] = MAC_K_KEY;
424 KeyTable[SDLK_l] = MAC_L_KEY;
425 KeyTable[SDLK_m] = MAC_M_KEY;
426 KeyTable[SDLK_n] = MAC_N_KEY;
427 KeyTable[SDLK_o] = MAC_O_KEY;
428 KeyTable[SDLK_p] = MAC_P_KEY;
429 KeyTable[SDLK_q] = MAC_Q_KEY;
430 KeyTable[SDLK_r] = MAC_R_KEY;
431 KeyTable[SDLK_s] = MAC_S_KEY;
432 KeyTable[SDLK_t] = MAC_T_KEY;
433 KeyTable[SDLK_u] = MAC_U_KEY;
434 KeyTable[SDLK_v] = MAC_V_KEY;
435 KeyTable[SDLK_w] = MAC_W_KEY;
436 KeyTable[SDLK_x] = MAC_X_KEY;
437 KeyTable[SDLK_y] = MAC_Y_KEY;
438 KeyTable[SDLK_z] = MAC_Z_KEY;
439 KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
440 KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
441 KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
442 KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
443 KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
444 KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
445 KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
446 KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
447 KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
448 KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
449 KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
450 KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
451 KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
452 KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
453 KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
454 KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
455 KeyTable[SDLK_F1] = MAC_F1_KEY;
456 KeyTable[SDLK_F2] = MAC_F2_KEY;
457 KeyTable[SDLK_F3] = MAC_F3_KEY;
458 KeyTable[SDLK_F4] = MAC_F4_KEY;
459 KeyTable[SDLK_F5] = MAC_F5_KEY;
460 KeyTable[SDLK_F6] = MAC_F6_KEY;
461 KeyTable[SDLK_F7] = MAC_F7_KEY;
462 KeyTable[SDLK_F8] = MAC_F8_KEY;
463 KeyTable[SDLK_F9] = MAC_F9_KEY;
464 KeyTable[SDLK_F10] = MAC_F10_KEY;
465 KeyTable[SDLK_F11] = MAC_F11_KEY;
466 KeyTable[SDLK_F12] = MAC_F12_KEY;
467 KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
468 KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
469 KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
470 KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
471 KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
472 KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
473 KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
474 KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
475 KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
476 KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
477 KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
480 static inline int clamp_sdl_mouse_button(Uint8 button)
482 if (button == 2) // right mouse button is button 3 in SDL.
484 else if (button == 3)
487 if ((button >= 1) && (button <= 3))
492 static void sdlEventProc(const SDL_Event &e, Game &game)
495 bool skipkey = false;
500 case SDL_MOUSEMOTION:
501 game.deltah += e.motion.xrel;
502 game.deltav += e.motion.yrel;
505 case SDL_MOUSEBUTTONDOWN:
507 val = clamp_sdl_mouse_button(e.button.button);
508 if ((val >= 0) && (val <= 2))
517 case SDL_MOUSEBUTTONUP:
519 val = clamp_sdl_mouse_button(e.button.button);
520 if ((val >= 0) && (val <= 2))
524 buttons[val] = false;
530 if (e.key.keysym.sym == SDLK_g)
532 if (e.key.keysym.mod & KMOD_CTRL)
535 SDL_GrabMode mode = SDL_GRAB_ON;
536 if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
538 mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
539 mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
541 SDL_WM_GrabInput(mode);
545 else if (e.key.keysym.sym == SDLK_RETURN)
547 if (e.key.keysym.mod & KMOD_ALT)
550 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
554 if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
556 if (KeyTable[e.key.keysym.sym] != 0xffff)
557 SetKey(KeyTable[e.key.keysym.sym]);
560 mod = SDL_GetModState();
562 SetKey(MAC_CONTROL_KEY);
564 SetKey(MAC_OPTION_KEY);
566 SetKey(MAC_COMMAND_KEY);
567 if (mod & KMOD_SHIFT)
568 SetKey(MAC_SHIFT_KEY);
570 SetKey(MAC_CAPS_LOCK_KEY);
575 if (e.key.keysym.sym < SDLK_LAST)
577 if (KeyTable[e.key.keysym.sym] != 0xffff)
578 ClearKey(KeyTable[e.key.keysym.sym]);
581 mod = SDL_GetModState();
582 if ((mod & KMOD_CTRL) == 0)
583 ClearKey(MAC_CONTROL_KEY);
584 if ((mod & KMOD_ALT) == 0)
585 ClearKey(MAC_OPTION_KEY);
586 if ((mod & KMOD_SHIFT) == 0)
587 ClearKey(MAC_SHIFT_KEY);
588 if ((mod & KMOD_CAPS) == 0)
589 ClearKey(MAC_CAPS_LOCK_KEY);
595 // --------------------------------------------------------------------------
597 static Point gMidPoint;
599 Boolean SetUp (Game & game)
605 randSeed = UpTime().lo;
608 ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
611 usermousesensitivity=1;
640 game.crouchkey=MAC_SHIFT_KEY;
641 game.jumpkey=MAC_SPACE_KEY;
642 game.leftkey=MAC_A_KEY;
643 game.forwardkey=MAC_W_KEY;
644 game.backkey=MAC_S_KEY;
645 game.rightkey=MAC_D_KEY;
646 game.drawkey=MAC_E_KEY;
647 game.throwkey=MAC_Q_KEY;
648 game.attackkey=MAC_MOUSEBUTTON1;
649 game.chatkey=MAC_T_KEY;
655 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
658 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
659 opstream << "Screenwidth:\n";
660 opstream << kContextWidth;
661 opstream << "\nScreenheight:\n";
662 opstream << kContextHeight;
663 opstream << "\nMouse sensitivity:\n";
664 opstream << usermousesensitivity;
665 opstream << "\nBlur(0,1):\n";
666 opstream << ismotionblur;
667 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
669 opstream << "\nFloating jump:\n";
670 opstream << floatjump;
671 opstream << "\nMouse jump:\n";
672 opstream << mousejump;
673 opstream << "\nAmbient sound:\n";
674 opstream << ambientsound;
675 opstream << "\nBlood (0,1,2):\n";
676 opstream << bloodtoggle;
677 opstream << "\nAuto slomo:\n";
678 opstream << autoslomo;
679 opstream << "\nFoliage:\n";
681 opstream << "\nMusic:\n";
682 opstream << musictoggle;
683 opstream << "\nTrilinear:\n";
684 opstream << trilinear;
685 opstream << "\nDecals(shadows,blood puddles,etc):\n";
687 opstream << "\nInvert mouse:\n";
688 opstream << invertmouse;
689 opstream << "\nGamespeed:\n";
690 opstream << gamespeed;
691 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
692 opstream << difficulty;
693 opstream << "\nDamage effects(blackout, doublevision):\n";
694 opstream << damageeffects;
695 opstream << "\nText:\n";
696 opstream << texttoggle;
697 opstream << "\nDebug:\n";
698 opstream << debugmode;
699 opstream << "\nVBL Sync:\n";
701 opstream << "\nShow Points:\n";
702 opstream << showpoints;
703 opstream << "\nAlways Blur:\n";
704 opstream << alwaysblur;
705 opstream << "\nImmediate mode (turn on on G5):\n";
706 opstream << immediate;
707 opstream << "\nVelocity blur:\n";
708 opstream << velocityblur;
709 opstream << "\nVolume:\n";
711 opstream << "\nForward key:\n";
712 opstream << KeyToChar(game.forwardkey);
713 opstream << "\nBack key:\n";
714 opstream << KeyToChar(game.backkey);
715 opstream << "\nLeft key:\n";
716 opstream << KeyToChar(game.leftkey);
717 opstream << "\nRight key:\n";
718 opstream << KeyToChar(game.rightkey);
719 opstream << "\nJump key:\n";
720 opstream << KeyToChar(game.jumpkey);
721 opstream << "\nCrouch key:\n";
722 opstream << KeyToChar(game.crouchkey);
723 opstream << "\nDraw key:\n";
724 opstream << KeyToChar(game.drawkey);
725 opstream << "\nThrow key:\n";
726 opstream << KeyToChar(game.throwkey);
727 opstream << "\nAttack key:\n";
728 opstream << KeyToChar(game.attackkey);
729 opstream << "\nChat key:\n";
730 opstream << KeyToChar(game.chatkey);
735 ipstream.ignore(256,'\n');
736 ipstream >> kContextWidth;
737 ipstream.ignore(256,'\n');
738 ipstream.ignore(256,'\n');
739 ipstream >> kContextHeight;
740 ipstream.ignore(256,'\n');
741 ipstream.ignore(256,'\n');
742 ipstream >> usermousesensitivity;
743 ipstream.ignore(256,'\n');
744 ipstream.ignore(256,'\n');
746 ismotionblur = (i != 0);
747 ipstream.ignore(256,'\n');
748 ipstream.ignore(256,'\n');
750 if(detail!=0)kBitsPerPixel=32;
751 else kBitsPerPixel=16;
752 ipstream.ignore(256,'\n');
753 ipstream.ignore(256,'\n');
755 floatjump = (i != 0);
756 ipstream.ignore(256,'\n');
757 ipstream.ignore(256,'\n');
759 mousejump = (i != 0);
760 ipstream.ignore(256,'\n');
761 ipstream.ignore(256,'\n');
763 ambientsound = (i != 0);
764 ipstream.ignore(256,'\n');
765 ipstream.ignore(256,'\n');
766 ipstream >> bloodtoggle;
767 ipstream.ignore(256,'\n');
768 ipstream.ignore(256,'\n');
770 autoslomo = (i != 0);
771 ipstream.ignore(256,'\n');
772 ipstream.ignore(256,'\n');
775 ipstream.ignore(256,'\n');
776 ipstream.ignore(256,'\n');
778 musictoggle = (i != 0);
779 ipstream.ignore(256,'\n');
780 ipstream.ignore(256,'\n');
782 trilinear = (i != 0);
783 ipstream.ignore(256,'\n');
784 ipstream.ignore(256,'\n');
787 ipstream.ignore(256,'\n');
788 ipstream.ignore(256,'\n');
790 invertmouse = (i != 0);
791 ipstream.ignore(256,'\n');
792 ipstream.ignore(256,'\n');
793 ipstream >> gamespeed;
794 oldgamespeed=gamespeed;
799 ipstream.ignore(256,'\n');
800 ipstream.ignore(256,'\n');
801 ipstream >> difficulty;
802 ipstream.ignore(256,'\n');
803 ipstream.ignore(256,'\n');
805 damageeffects = (i != 0);
806 ipstream.ignore(256,'\n');
807 ipstream.ignore(256,'\n');
809 texttoggle = (i != 0);
810 ipstream.ignore(256,'\n');
811 ipstream.ignore(256,'\n');
813 debugmode = (i != 0);
814 ipstream.ignore(256,'\n');
815 ipstream.ignore(256,'\n');
818 ipstream.ignore(256,'\n');
819 ipstream.ignore(256,'\n');
821 showpoints = (i != 0);
822 ipstream.ignore(256,'\n');
823 ipstream.ignore(256,'\n');
825 alwaysblur = (i != 0);
826 ipstream.ignore(256,'\n');
827 ipstream.ignore(256,'\n');
829 immediate = (i != 0);
830 ipstream.ignore(256,'\n');
831 ipstream.ignore(256,'\n');
833 velocityblur = (i != 0);
834 ipstream.ignore(256,'\n');
835 ipstream.ignore(256,'\n');
837 ipstream.ignore(256,'\n');
838 ipstream.ignore(256,'\n');
840 game.forwardkey=CharToKey(string);
841 ipstream.ignore(256,'\n');
842 ipstream.ignore(256,'\n');
844 game.backkey=CharToKey(string);
845 ipstream.ignore(256,'\n');
846 ipstream.ignore(256,'\n');
848 game.leftkey=CharToKey(string);
849 ipstream.ignore(256,'\n');
850 ipstream.ignore(256,'\n');
852 game.rightkey=CharToKey(string);
853 ipstream.ignore(256,'\n');
854 ipstream.ignore(256,'\n');
856 game.jumpkey=CharToKey(string);
857 ipstream.ignore(256,'\n');
858 ipstream.ignore(256,'\n');
860 game.crouchkey=CharToKey(string);
861 ipstream.ignore(256,'\n');
862 ipstream.ignore(256,'\n');
864 game.drawkey=CharToKey(string);
865 ipstream.ignore(256,'\n');
866 ipstream.ignore(256,'\n');
868 game.throwkey=CharToKey(string);
869 ipstream.ignore(256,'\n');
870 ipstream.ignore(256,'\n');
872 game.attackkey=CharToKey(string);
873 ipstream.ignore(256,'\n');
874 ipstream.ignore(256,'\n');
876 game.chatkey=CharToKey(string);
879 if(detail>2)detail=2;
880 if(detail<0)detail=0;
881 if(screenwidth<0)screenwidth=640;
882 if(screenheight<0)screenheight=480;
883 #if !USE_SDL // we'll take anything that works.
884 if(screenwidth>3000)screenwidth=640;
885 if(screenheight>3000)screenheight=480;
888 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
893 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
895 SetupDSpFullScreen();
898 if (!SDL_WasInit(SDL_INIT_VIDEO))
900 if (SDL_Init(SDL_INIT_VIDEO) == -1)
902 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
906 if (SDL_GL_LoadLibrary(NULL) == -1)
908 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
913 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
914 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
915 res = hardcoded_resolutions;
917 // reverse list (it was sorted biggest to smallest by SDL)...
919 for (count = 0; res[count]; count++)
921 if ((res[count]->w < 640) || (res[count]->h < 480))
922 break; // sane lower limit.
925 static SDL_Rect *resolutions_block = NULL;
926 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
927 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
928 if ((resolutions_block == NULL) || (resolutions == NULL))
931 fprintf(stderr, "Out of memory!\n");
935 resolutions[count--] = NULL;
936 for (int i = 0; count >= 0; i++, count--)
938 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
939 resolutions[count] = &resolutions_block[count];
942 if (cmdline("showresolutions"))
944 printf("Resolutions we think are okay:\n");
945 for (int i = 0; resolutions[i]; i++)
946 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
950 Uint32 sdlflags = SDL_OPENGL;
951 if (!cmdline("windowed"))
952 sdlflags |= SDL_FULLSCREEN;
954 SDL_WM_SetCaption("Lugaru", "Lugaru");
958 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
960 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
962 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
963 fprintf(stderr, "forcing 640x480...\n");
965 kContextHeight = 480;
966 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
968 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
969 fprintf(stderr, "forcing 640x480 windowed mode...\n");
970 sdlflags &= ~SDL_FULLSCREEN;
971 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
973 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
980 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
982 fprintf(stderr, "Failed to get double buffered GL context!\n");
987 if (!lookup_all_glsyms())
993 if (!cmdline("nomousegrab"))
994 SDL_WM_GrabInput(SDL_GRAB_ON);
996 #elif (defined WIN32)
997 //------------------------------------------------------------------
1000 RECT r = {0, 0, kContextWidth-1, kContextHeight-1};
1001 DWORD dwStyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE;
1002 DWORD dwExStyle = WS_EX_APPWINDOW;
1006 dwStyle |= WS_POPUP;
1011 dwStyle |= WS_OVERLAPPEDWINDOW;
1012 dwExStyle |= WS_EX_WINDOWEDGE;
1015 AdjustWindowRectEx(&r, dwStyle, FALSE, dwExStyle);
1019 x = (GetSystemMetrics(SM_CXSCREEN) >> 1) - ((r.right - r.left + 1) >> 1);
1020 y = (GetSystemMetrics(SM_CYSCREEN) >> 1) - ((r.bottom - r.top + 1) >> 1);
1023 g_windowHandle=CreateWindowEx(
1025 g_wndClassName, "Lugaru", dwStyle,
1027 // kContextWidth, kContextHeight,
1028 r.right - r.left + 1, r.bottom - r.top + 1,
1029 NULL,NULL,g_appInstance,NULL );
1030 if (!g_windowHandle)
1032 ReportError("Could not create window");
1036 //------------------------------------------------------------------
1039 static PIXELFORMATDESCRIPTOR pfd =
1041 sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1042 1, // Version Number
1043 PFD_DRAW_TO_WINDOW | // Format Must Support Window
1044 PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
1045 PFD_DOUBLEBUFFER, // Must Support Double Buffering
1046 PFD_TYPE_RGBA, // Request An RGBA Format
1047 kBitsPerPixel, // Select Our Color Depth
1048 0, 0, 0, 0, 0, 0, // Color Bits Ignored
1049 0, // No Alpha Buffer
1050 0, // Shift Bit Ignored
1051 0, // No Accumulation Buffer
1052 0, 0, 0, 0, // Accumulation Bits Ignored
1053 16, // 16Bit Z-Buffer (Depth Buffer)
1054 0, // No Stencil Buffer
1055 0, // No Auxiliary Buffer
1056 PFD_MAIN_PLANE, // Main Drawing Layer
1058 0, 0, 0 // Layer Masks Ignored
1061 if (!(hDC = GetDC( g_windowHandle)))
1062 ReportError( "Could not get device context");
1065 if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))
1067 ReportError( "Could not find appropriate pixel format");
1071 if (!DescribePixelFormat(hDC, PixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd))
1073 ReportError( "Could not retrieve pixel format");
1077 if (!SetPixelFormat( hDC, PixelFormat, &pfd))
1079 ReportError( "Could not set pixel format");
1083 if (!(hRC = wglCreateContext(hDC)))
1085 ReportError( "Could not create rendering context");
1089 if (!wglMakeCurrent(hDC, hRC))
1091 ReportError( "Could not activate rendering context");
1097 // Place the window above all topmost windows
1098 SetWindowPos( g_windowHandle, HWND_TOPMOST, 0,0,0,0,
1099 SWP_NOMOVE | SWP_NOSIZE );
1102 SetForegroundWindow(g_windowHandle);
1103 SetFocus(g_windowHandle);
1106 glClear( GL_COLOR_BUFFER_BIT );
1110 glDisable( GL_ALPHA_TEST);
1111 glDisable( GL_BLEND);
1112 glDisable( GL_DEPTH_TEST);
1113 // glDisable( GL_DITHER);
1115 glDisable( GL_LIGHTING);
1116 glDisable( GL_LOGIC_OP);
1117 glDisable( GL_STENCIL_TEST);
1118 glDisable( GL_TEXTURE_1D);
1119 glDisable( GL_TEXTURE_2D);
1120 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
1121 glPixelTransferi( GL_RED_SCALE, 1);
1122 glPixelTransferi( GL_RED_BIAS, 0);
1123 glPixelTransferi( GL_GREEN_SCALE, 1);
1124 glPixelTransferi( GL_GREEN_BIAS, 0);
1125 glPixelTransferi( GL_BLUE_SCALE, 1);
1126 glPixelTransferi( GL_BLUE_BIAS, 0);
1127 glPixelTransferi( GL_ALPHA_SCALE, 1);
1128 glPixelTransferi( GL_ALPHA_BIAS, 0);
1130 // set initial rendering states
1131 glShadeModel( GL_SMOOTH);
1132 glClearDepth( 1.0f);
1133 glDepthFunc( GL_LEQUAL);
1134 glDepthMask( GL_TRUE);
1135 // glDepthRange( FRONT_CLIP, BACK_CLIP);
1136 glEnable( GL_DEPTH_TEST);
1137 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
1138 glCullFace( GL_FRONT);
1139 glEnable( GL_CULL_FACE);
1140 glEnable( GL_LIGHTING);
1141 // glEnable( GL_LIGHT_MODEL_AMBIENT);
1142 glEnable( GL_DITHER);
1143 glEnable( GL_COLOR_MATERIAL);
1144 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1145 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1146 glAlphaFunc( GL_GREATER, 0.5f);
1149 if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION ||
1150 iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION ||
1151 ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION)
1153 ReportError("DevIL version is different...exiting!\n");
1161 ilutRenderer(ILUT_OPENGL);
1163 ilEnable(IL_ORIGIN_SET);
1164 ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
1167 GLint width = kContextWidth;
1168 GLint height = kContextHeight;
1169 gMidPoint.h = width / 2;
1170 gMidPoint.v = height / 2;
1172 screenheight=height;
1174 game.newdetail=detail;
1175 game.newscreenwidth=screenwidth;
1176 game.newscreenheight=screenheight;
1184 static void DoMouse(Game & game)
1187 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1189 game.deltah *= usermousesensitivity;
1190 game.deltav *= usermousesensitivity;
1191 game.mousecoordh += game.deltah;
1192 game.mousecoordv += game.deltav;
1193 if (game.mousecoordh < 0)
1194 game.mousecoordh = 0;
1195 else if (game.mousecoordh >= kContextWidth)
1196 game.mousecoordh = kContextWidth - 1;
1197 if (game.mousecoordv < 0)
1198 game.mousecoordv = 0;
1199 else if (game.mousecoordv >= kContextHeight)
1200 game.mousecoordv = kContextHeight - 1;
1203 static Point lastMouse = {-1,-1};
1208 ScreenToClient(g_windowHandle, &pos);
1209 globalMouse.h = pos.x;
1210 globalMouse.v = pos.y;
1212 if (lastMouse.h == globalMouse.h && lastMouse.v == globalMouse.v)
1219 static Point virtualMouse = {0,0};
1220 delta = globalMouse;
1222 delta.h -= lastMouse.h;
1223 delta.v -= lastMouse.v;
1224 lastMouse.h = pos.x;
1225 lastMouse.v = pos.y;
1227 if(mainmenu||(abs(delta.h)<10*realmultiplier*1000&&abs(delta.v)<10*realmultiplier*1000)){
1228 game.deltah=delta.h*usermousesensitivity;
1229 game.deltav=delta.v*usermousesensitivity;
1230 game.mousecoordh=globalMouse.h;
1231 game.mousecoordv=globalMouse.v;
1236 if(lastMouse.h>gMidPoint.h+100||lastMouse.h<gMidPoint.h-100||lastMouse.v>gMidPoint.v+100||lastMouse.v<gMidPoint.v-100){
1237 pos.x = gMidPoint.h;
1238 pos.y = gMidPoint.v;
1239 ClientToScreen(g_windowHandle, &pos);
1240 //SetCursorPos( gMidPoint.h,gMidPoint.v);
1241 SetCursorPos(pos.x, pos.y);
1242 lastMouse = gMidPoint;
1251 // --------------------------------------------------------------------------
1253 void DoKey (SInt8 theKey, SInt8 theCode)
1258 // --------------------------------------------------------------------------
1262 void DoFrameRate (int update)
1264 static long frames = 0;
1266 static AbsoluteTime time = {0,0};
1267 static AbsoluteTime frametime = {0,0};
1268 AbsoluteTime currTime = UpTime ();
1269 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1271 if (0 > deltaTime) // if negative microseconds
1272 deltaTime /= -1000000.0;
1273 else // else milliseconds
1274 deltaTime /= 1000.0;
1276 multiplier=deltaTime;
1277 if(multiplier<.001)multiplier=.001;
1278 if(multiplier>10)multiplier=10;
1279 if(update)frametime = currTime; // reset for next time interval
1281 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1283 if (0 > deltaTime) // if negative microseconds
1284 deltaTime /= -1000000.0;
1285 else // else milliseconds
1286 deltaTime /= 1000.0;
1288 if (0.001 <= deltaTime) // has update interval passed
1291 time = currTime; // reset for next time interval
1298 void DoUpdate (Game & game)
1300 static float sps=200;
1302 static float oldmult;
1305 if(multiplier>.6)multiplier=.6;
1307 game.fps=1/multiplier;
1309 count = multiplier*sps;
1311 //if(count>10)count=10;
1313 realmultiplier=multiplier;
1314 multiplier*=gamespeed;
1315 if(difficulty==1)multiplier*=.9;
1316 if(difficulty==0)multiplier*=.8;
1318 if(game.loading==4)multiplier*=.00001;
1320 if(slomo&&!mainmenu)multiplier*=slomospeed;
1321 //if(freeze)multiplier*=0.00001;
1323 multiplier/=(float)count;
1329 for(int i=0;i<count;i++)
1335 game.TickOnceAfter();
1336 /* - Debug code to test how many channels were active on average per frame
1337 static long frames = 0;
1339 static AbsoluteTime start = {0,0};
1340 AbsoluteTime currTime = UpTime ();
1341 static int num_channels = 0;
1343 num_channels += FSOUND_GetChannelsPlaying();
1344 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1346 if (0 > deltaTime) // if negative microseconds
1347 deltaTime /= -1000000.0;
1348 else // else milliseconds
1349 deltaTime /= 1000.0;
1356 float avg_channels = (float)num_channels / (float)frames;
1358 ofstream opstream("log.txt",ios::app);
1359 opstream << "Average frame count: ";
1361 opstream << " frames - ";
1362 opstream << avg_channels;
1363 opstream << " per frame.\n";
1373 // --------------------------------------------------------------------------
1388 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1389 #include "glstubs.h"
1391 // cheat here...static destructors are calling glDeleteTexture() after
1392 // the context is destroyed and libGL unloaded by SDL_Quit().
1393 pglDeleteTextures = glDeleteTextures_doNothing;
1395 #elif (defined WIN32)
1398 wglMakeCurrent( NULL, NULL);
1399 wglDeleteContext( hRC);
1405 ReleaseDC( g_windowHandle, hDC);
1411 ShowWindow( g_windowHandle, SW_HIDE );
1412 DestroyWindow( g_windowHandle);
1413 g_windowHandle = NULL;
1421 // --------------------------------------------------------------------------
1423 static bool g_focused = true;
1426 static bool IsFocused()
1432 if (GetActiveWindow() != g_windowHandle)
1435 if (IsIconic( g_windowHandle))
1443 static void launch_web_browser(const char *url)
1446 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1448 #elif (defined(__APPLE__) && defined(__MACH__))
1449 const char *fmt = "open '%s'";
1450 const size_t len = strlen(fmt) + strlen(url) + 16;
1451 char *buf = new char[len];
1452 snprintf(buf, len, fmt, url);
1456 #elif PLATFORM_LINUX
1457 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1458 const size_t len = strlen(fmt) + strlen(url) + 16;
1459 char *buf = new char[len];
1460 snprintf(buf, len, fmt, url);
1468 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1469 static char *findBinaryInPath(const char *bin, char *envr)
1471 size_t alloc_size = 0;
1479 ptr = strchr(start, ':'); /* find next $PATH separator. */
1483 size = strlen(start) + strlen(bin) + 2;
1484 if (size > alloc_size)
1486 char *x = (char *) realloc(exe, size);
1498 /* build full binary path... */
1500 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1504 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
1506 strcpy(exe, start); /* i'm lazy. piss off. */
1510 start = ptr + 1; /* start points to beginning of next element. */
1511 } while (ptr != NULL);
1516 return(NULL); /* doesn't exist in path. */
1517 } /* findBinaryInPath */
1520 char *calcBaseDir(const char *argv0)
1522 /* If there isn't a path on argv0, then look through the $PATH for it. */
1526 char *ptr = strrchr((char *)argv0, '/');
1527 if (strchr(argv0, '/'))
1529 retval = strdup(argv0);
1531 *(strrchr(retval, '/')) = '\0';
1535 envr = getenv("PATH");
1536 if (!envr) return NULL;
1537 envr = strdup(envr);
1538 if (!envr) return NULL;
1539 retval = findBinaryInPath(argv0, envr);
1544 static inline void chdirToAppPath(const char *argv0)
1546 char *dir = calcBaseDir(argv0);
1549 #if (defined(__APPLE__) && defined(__MACH__))
1550 // Chop off /Contents/MacOS if it's at the end of the string, so we
1551 // land in the base of the app bundle.
1552 const size_t len = strlen(dir);
1553 const char *bundledirs = "/Contents/MacOS";
1554 const size_t bundledirslen = strlen(bundledirs);
1555 if (len > bundledirslen)
1557 char *ptr = (dir + len) - bundledirslen;
1558 if (strcasecmp(ptr, bundledirs) == 0)
1569 int main(int argc, char **argv)
1574 chdirToAppPath(argv[0]);
1579 #ifndef WIN32 // this is in WinMain, too.
1580 memset( &g_theKeys, 0, sizeof( KeyMap));
1587 bool regnow = false;
1592 //ofstream os("error.txt");
1594 //ofstream os("log.txt");
1600 while (!gDone&&!game.quit&&(!game.tryquit||!game.registered))
1606 // check windows messages
1612 while( SDL_PollEvent( &e ) )
1614 if( e.type == SDL_QUIT )
1619 sdlEventProc(e, game);
1622 #elif (defined WIN32)
1625 while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE | PM_NOYIELD ) )
1627 if( msg.message == WM_QUIT )
1634 TranslateMessage( &msg );
1635 DispatchMessage( &msg );
1647 // allow game chance to pause
1648 gameFocused = false;
1652 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1656 //if (GetMessage( &msg, g_windowHandle, 0, 0 ))
1657 /*if (GetMessage( &msg, NULL, 0, 0 ))
1659 TranslateMessage(&msg);
1660 DispatchMessage(&msg);
1662 if ( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
1666 // handle the error and possibly exit
1671 TranslateMessage(&msg);
1672 DispatchMessage(&msg);
1676 STUBBED("give up CPU but sniff the event queue");
1681 regnow = game.registernow;
1686 // if(game.registernow){
1689 #if (defined(__APPLE__) && defined(__MACH__))
1690 launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1691 #elif PLATFORM_LINUX
1692 launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1694 launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1698 #if PLATFORM_LINUX // (this may not be necessary any more.)
1699 _exit(0); // !!! FIXME: hack...crashes on exit!
1703 catch (const std::exception& error)
1707 std::string e = "Caught exception: ";
1712 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1722 // --------------------------------------------------------------------------
1725 #define MAX_WINKEYS 256
1726 static unsigned short KeyTable[MAX_WINKEYS]=
1729 MAC_MOUSEBUTTON1, // VK_LBUTTON (1)
1730 MAC_MOUSEBUTTON2, // VK_RBUTTON (2)
1731 0xffff, // VK_CANCEL (3)
1732 0xffff, // VK_MBUTTON (4)
1736 MAC_DELETE_KEY, // VK_BACK (8)
1737 MAC_TAB_KEY, // VK_TAB (9)
1740 0xffff, // VK_CLEAR (12)
1741 MAC_RETURN_KEY, // VK_RETURN (13)
1744 MAC_SHIFT_KEY, // VK_SHIFT (16)
1745 MAC_CONTROL_KEY, // VK_CONTROL (17)
1746 MAC_OPTION_KEY, // VK_MENU (18)
1747 0xffff, // VK_PAUSE (19)
1748 MAC_CAPS_LOCK_KEY, // #define VK_CAPITAL (20)
1755 MAC_ESCAPE_KEY, // VK_ESCAPE (27)
1760 MAC_SPACE_KEY, // VK_SPACE (32)
1761 MAC_PAGE_UP_KEY, // VK_PRIOR (33)
1762 MAC_PAGE_DOWN_KEY, // VK_NEXT (34)
1763 MAC_END_KEY, // VK_END (35)
1764 MAC_HOME_KEY, // VK_HOME (36)
1765 MAC_ARROW_LEFT_KEY, // VK_LEFT (37)
1766 MAC_ARROW_UP_KEY, // VK_UP (38)
1767 MAC_ARROW_RIGHT_KEY, // VK_RIGHT (39)
1768 MAC_ARROW_DOWN_KEY, // VK_DOWN (40)
1769 0xffff, // VK_SELECT (41)
1770 0xffff, // VK_PRINT (42)
1771 0xffff, // VK_EXECUTE (43)
1772 0xffff, // VK_SNAPSHOT (44)
1773 MAC_INSERT_KEY, // VK_INSERT (45)
1774 MAC_DEL_KEY, // VK_DELETE (46)
1775 0xffff, // VK_HELP (47)
1776 MAC_0_KEY, // VK_0 (48)
1777 MAC_1_KEY, // VK_1 (49)
1778 MAC_2_KEY, // VK_2 (50)
1779 MAC_3_KEY, // VK_3 (51)
1780 MAC_4_KEY, // VK_4 (52)
1781 MAC_5_KEY, // VK_5 (53)
1782 MAC_6_KEY, // VK_6 (54)
1783 MAC_7_KEY, // VK_7 (55)
1784 MAC_8_KEY, // VK_8 (56)
1785 MAC_9_KEY, // VK_9 (57)
1793 MAC_A_KEY, // VK_A (65)
1794 MAC_B_KEY, // VK_B (66)
1795 MAC_C_KEY, // VK_C (67)
1796 MAC_D_KEY, // VK_D (68)
1797 MAC_E_KEY, // VK_E (69)
1798 MAC_F_KEY, // VK_F (70)
1799 MAC_G_KEY, // VK_G (71)
1800 MAC_H_KEY, // VK_H (72)
1801 MAC_I_KEY, // VK_I (73)
1802 MAC_J_KEY, // VK_J (74)
1803 MAC_K_KEY, // VK_K (75)
1804 MAC_L_KEY, // VK_L (76)
1805 MAC_M_KEY, // VK_M (77)
1806 MAC_N_KEY, // VK_N (78)
1807 MAC_O_KEY, // VK_O (79)
1808 MAC_P_KEY, // VK_P (80)
1809 MAC_Q_KEY, // VK_Q (81)
1810 MAC_R_KEY, // VK_R (82)
1811 MAC_S_KEY, // VK_S (83)
1812 MAC_T_KEY, // VK_T (84)
1813 MAC_U_KEY, // VK_U (85)
1814 MAC_V_KEY, // VK_V (86)
1815 MAC_W_KEY, // VK_W (87)
1816 MAC_X_KEY, // VK_X (88)
1817 MAC_Y_KEY, // VK_Y (89)
1818 MAC_Z_KEY, // VK_Z (90)
1824 MAC_NUMPAD_0_KEY, // VK_NUMPAD0 (96)
1825 MAC_NUMPAD_1_KEY, // VK_NUMPAD1 (97)
1826 MAC_NUMPAD_2_KEY, // VK_NUMPAD2 (98)
1827 MAC_NUMPAD_3_KEY, // VK_NUMPAD3 (99)
1828 MAC_NUMPAD_4_KEY, // VK_NUMPAD4 (100)
1829 MAC_NUMPAD_5_KEY, // VK_NUMPAD5 (101)
1830 MAC_NUMPAD_6_KEY, // VK_NUMPAD6 (102)
1831 MAC_NUMPAD_7_KEY, // VK_NUMPAD7 (103)
1832 MAC_NUMPAD_8_KEY, // VK_NUMPAD8 (104)
1833 MAC_NUMPAD_9_KEY, // VK_NUMPAD9 (105)
1834 MAC_NUMPAD_ASTERISK_KEY, // VK_MULTIPLY (106)
1835 MAC_NUMPAD_PLUS_KEY, // VK_ADD (107)
1836 MAC_NUMPAD_ENTER_KEY, // VK_SEPARATOR (108)
1837 MAC_NUMPAD_MINUS_KEY, // VK_SUBTRACT (109)
1838 MAC_NUMPAD_PERIOD_KEY, // VK_DECIMAL (110)
1839 MAC_NUMPAD_SLASH_KEY, // VK_DIVIDE (111)
1840 MAC_F1_KEY, // VK_F1 (112)
1841 MAC_F2_KEY, // VK_F2 (113)
1842 MAC_F3_KEY, // VK_F3 (114)
1843 MAC_F4_KEY, // VK_F4 (115)
1844 MAC_F5_KEY, // VK_F5 (116)
1845 MAC_F6_KEY, // VK_F6 (117)
1846 MAC_F7_KEY, // VK_F7 (118)
1847 MAC_F8_KEY, // VK_F8 (119)
1848 MAC_F9_KEY, // VK_F9 (120)
1849 MAC_F10_KEY, // VK_F10 (121)
1850 MAC_F11_KEY, // VK_F11 (122)
1851 MAC_F12_KEY, // VK_F12 (123)
1872 0xffff, // VK_NUMLOCK (144)
1873 0xffff, // VK_SCROLL (145)
1888 MAC_SHIFT_KEY, // VK_LSHIFT (160)
1889 MAC_SHIFT_KEY, // VK_RSHIFT (161)
1890 MAC_CONTROL_KEY, // VK_LCONTROL (162)
1891 MAC_CONTROL_KEY, // VK_RCONTROL (163)
1892 MAC_OPTION_KEY, // VK_LMENU (164)
1893 MAC_OPTION_KEY, // VK_RMENU (165)
1914 MAC_SEMICOLON_KEY, // (186)
1915 MAC_PLUS_KEY, // (187)
1916 MAC_COMMA_KEY, // (188)
1917 MAC_MINUS_KEY, // (189)
1918 MAC_PERIOD_KEY, // (190)
1919 MAC_SLASH_KEY, // (191)
1920 MAC_TILDE_KEY, // (192)
1947 MAC_LEFTBRACKET_KEY, // (219)
1948 MAC_BACKSLASH_KEY, // (220)
1949 MAC_RIGHTBRACKET_KEY, // (221)
1950 MAC_APOSTROPHE_KEY, // (222)
1986 void ClipMouseToWindow(HWND window)
1990 GetClientRect(window, &wRect);
1992 ClientToScreen(window, (LPPOINT)&wRect.left);
1993 ClientToScreen(window, (LPPOINT)&wRect.right);
2000 LRESULT FAR PASCAL AppWndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
2002 /* this is where we receive all messages concerning this window
2003 * we can either process a message or pass it on to the default
2004 * message handler of windows */
2006 static PAINTSTRUCT ps;
2010 case WM_ACTIVATE: // Watch For Window Activate Message
2012 // Check Minimization State
2013 BOOL iconified = HIWORD(wParam) ? TRUE : FALSE;
2015 if (LOWORD(wParam) == WA_INACTIVE)
2024 CloseWindow( hWnd );
2026 // The window is now iconified
2027 iconified = GL_TRUE;
2033 g_focused=false; // Program Is Active
2037 SetupDSpFullScreen();
2044 // The window is now iconified
2045 iconified = GL_FALSE;
2048 ShowWindow( hWnd, SW_SHOW );
2049 SetForegroundWindow( hWnd );
2053 ClipMouseToWindow(hWnd);
2054 g_focused=true; // Program Is No Longer Active
2057 return 0; // Return To The Message Loop
2063 // check for Alt-F4 (exit hotkey)
2064 if (wParam == VK_F4)
2066 if (GetKeyState( VK_MENU) & 0x8080)
2072 if (wParam < MAX_WINKEYS)
2074 if (KeyTable[wParam] != 0xffff)
2075 SetKey( KeyTable[wParam]);
2083 if (wParam < MAX_WINKEYS)
2084 if (KeyTable[wParam] != 0xffff)
2085 ClearKey( KeyTable[wParam]);
2092 case WM_SYSDEADCHAR:
2095 case WM_NCLBUTTONDOWN:
2096 case WM_LBUTTONDOWN:
2103 case WM_NCRBUTTONDOWN:
2104 case WM_RBUTTONDOWN:
2110 case WM_NCMBUTTONDOWN:
2111 case WM_MBUTTONDOWN:
2117 case WM_NCLBUTTONUP:
2121 buttons[ 0] = false;
2125 case WM_NCRBUTTONUP:
2128 buttons[ 1] = false;
2132 case WM_NCMBUTTONUP:
2135 buttons[ 2] = false;
2139 case WM_NCLBUTTONDBLCLK:
2140 case WM_NCRBUTTONDBLCLK:
2141 case WM_NCMBUTTONDBLCLK:
2142 case WM_LBUTTONDBLCLK:
2144 case WM_RBUTTONDBLCLK:
2145 case WM_MBUTTONDBLCLK:
2148 case WM_NCMOUSEMOVE:
2150 /* ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseX = (signed short)(lParam & 0xffff);
2151 ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseY = (signed short)(lParam >> 16);
2152 if (g_lastWindow->m_mouseCallbacksEnabled) g_lastWindow->MouseMoveCallback();
2153 */// goto winmessage;
2156 case WM_SYSCOMMAND: // Intercept System Commands
2158 switch (wParam) // Check System Calls
2160 case SC_SCREENSAVE: // Screensaver Trying To Start?
2161 case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
2162 return 0; // Prevent From Happening
2164 // User trying to access application menu using ALT?
2173 // ReleaseCapture();
2174 // ClipMouseToWindow(hWnd);
2191 PostQuitMessage(0); /* Terminate Application */
2199 // BeginPaint( g_windowHandle,&ps);
2200 // EndPaint( g_windowHandle,&ps);
2207 /* We processed the message and there
2208 * is no processing by Windows necessary */
2210 /* We didn't process the message so let Windows do it */
2211 return DefWindowProc(hWnd,msg,wParam,lParam);
2215 static BOOL RegisterWindowClasses(HINSTANCE hFirstInstance)
2218 memset( &wc, 0, sizeof( wc));
2220 /* Register the window class. */
2221 wc.cbSize = sizeof(wc);
2223 wc.style = (CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_OWNDC); /* Combination of Class Styles */
2224 wc.lpfnWndProc = AppWndProc; /* Adress of Window Procedure */
2225 wc.cbClsExtra = 0; /* Extra Bytes allocated for this Class */
2226 wc.cbWndExtra = 0; /* Extra Bytes allocated for each Window */
2227 wc.hInstance = hFirstInstance; /* Handle of program instance */
2228 wc.hIcon = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2229 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2230 wc.hbrBackground = NULL;
2231 wc.lpszMenuName = NULL;
2232 wc.lpszClassName = g_wndClassName; /* Name of the Window Class */
2233 wc.hIconSm = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2235 if (!RegisterClassEx(&wc)) return FALSE; /* Register Class failed */
2242 int resolutionID(int width, int height)
2246 if(width==640 && height==480)whichres=0;
2247 if(width==800 && height==600)whichres=1;
2248 if(width==1024 && height==768)whichres=2;
2249 if(width==1280 && height==1024)whichres=3;
2250 if(width==1600 && height==1200)whichres=4;
2251 if(width==840 && height==524)whichres=5;
2252 if(width==1024 && height==640)whichres=6;
2253 if(width==1344 && height==840)whichres=7;
2254 if(width==1920 && height==1200)whichres=8;
2259 int closestResolution(int width, int height)
2263 if(width>=640 && height>=480)whichres=0;
2264 if(width>=800 && height>=600)whichres=1;
2265 if(width>=1024 && height>=768)whichres=2;
2266 if(width>=1280 && height>=1024)whichres=3;
2267 if(width>=1600 && height>=1200)whichres=4;
2268 if(width==840 && height==524)whichres=5;
2269 if(width==1024 && height==640)whichres=6;
2270 if(width==1344 && height==840)whichres=7;
2271 if(width>=1920 && height>=1200)whichres=8;
2277 bool selectDetail(int & width, int & height, int & bpp, int & detail)
2281 // currently with SDL, we just use whatever is requested
2282 // and don't care. --ryan.
2284 int whichres = closestResolution(width, height);
2288 if(whichres<=0 || whichres>8){
2326 if ((detail != 0) && (resolutionDepths[whichres][1] != 0))
2330 else if ((detail == 0) && (resolutionDepths[whichres][0] != 0))
2334 else if ((detail != 0) && (resolutionDepths[whichres][0] != 0))
2350 bpp = resolutionDepths[whichres][(detail != 0)];
2357 int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
2360 LPWSTR * cl = CommandLineToArgvW(GetCommandLineW(), &argc);
2363 if (0 == _wcsicmp(cl[1], L"-windowed"))
2369 memset( &g_theKeys, 0, sizeof( KeyMap));
2373 memset(&mode, 0, sizeof(mode));
2374 mode.dmSize = sizeof(mode);
2375 while (EnumDisplaySettings(NULL, i++, &mode))
2377 if (mode.dmBitsPerPel < 16)
2382 int res = resolutionID(mode.dmPelsWidth, mode.dmPelsHeight);
2384 if (res > -1 && res < 8)
2386 if (DISP_CHANGE_SUCCESSFUL != ChangeDisplaySettings(&mode, CDS_TEST))
2391 switch(mode.dmBitsPerPel)
2395 resolutionDepths[res][1] = mode.dmBitsPerPel;
2398 resolutionDepths[res][0] = mode.dmBitsPerPel;
2404 /* if there is no Instance of our program in memory then register the window class */
2405 if (hPrevInstance == NULL && !RegisterWindowClasses(hInstance))
2406 return FALSE; /* registration failed! */
2408 g_appInstance=hInstance;
2412 UnregisterClass( g_wndClassName, hInstance);
2419 extern int channels[100];
2420 extern FSOUND_SAMPLE * samp[100];
2421 extern FSOUND_STREAM * strm[20];
2423 extern "C" void PlaySoundEx(int chan, FSOUND_SAMPLE *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2425 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2426 if (currSample && currSample == samp[chan])
2428 if (FSOUND_GetPaused(channels[chan]))
2430 FSOUND_StopSound(channels[chan]);
2431 channels[chan] = FSOUND_FREE;
2433 else if (FSOUND_IsPlaying(channels[chan]))
2435 int loop_mode = FSOUND_GetLoopMode(channels[chan]);
2436 if (loop_mode & FSOUND_LOOP_OFF)
2438 channels[chan] = FSOUND_FREE;
2444 channels[chan] = FSOUND_FREE;
2447 channels[chan] = FSOUND_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
2448 if (channels[chan] < 0)
2450 channels[chan] = FSOUND_PlaySoundEx(FSOUND_FREE, sptr, dsp, startpaused);
2454 extern "C" void PlayStreamEx(int chan, FSOUND_STREAM *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2456 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2457 if (currSample && currSample == FSOUND_Stream_GetSample(sptr))
2459 FSOUND_StopSound(channels[chan]);
2460 FSOUND_Stream_Stop(sptr);
2464 FSOUND_Stream_Stop(sptr);
2465 channels[chan] = FSOUND_FREE;
2468 channels[chan] = FSOUND_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
2469 if (channels[chan] < 0)
2471 channels[chan] = FSOUND_Stream_PlayEx(FSOUND_FREE, sptr, dsp, startpaused);
2475 bool LoadImage(const char * fname, TGAImageRec & tex)
2479 if ( tex.data == NULL )
2485 ILstring f = strdup(ConvertFileName(fname));
2492 ilGenImages(1, &iid);
2497 tex.sizeX = ilGetInteger(IL_IMAGE_WIDTH);
2498 tex.sizeY = ilGetInteger(IL_IMAGE_HEIGHT);
2499 tex.bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
2500 ILuint Bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL),
2501 imageSize = tex.sizeX * tex.sizeY * Bpp;
2502 ILubyte *Data = ilGetData();
2503 memcpy(tex.data, Data, imageSize);
2505 // Truvision Targa files are stored as BGR colors
2506 // We want RGB so Blue and Red bytes are switched
2507 if (IL_TGA == ilGetInteger(IL_IMAGE_FORMAT))
2509 // Loop Through The Image Data
2510 for (GLuint i = 0; i < int(imageSize); i += Bpp)
2512 // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
2513 GLbyte temp; // Temporary Variable
2514 temp = tex.data[i]; // Temporarily Store The Value At Image Data 'i'
2515 tex.data[i] = tex.data[i + 2]; // Set The 1st Byte To The Value Of The 3rd Byte
2516 tex.data[i + 2] = temp; // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
2524 ilDeleteImages(1, &iid);
2528 GLuint texid = ilutGLLoadImage(f);
2533 ilutGLBuildMipmaps()
2542 res = load_image(fname, tex);
2543 //if (!res) printf("failed to load %s\n", fname);
2549 void ScreenShot(const char * fname)
2552 ILstring f = strdup(fname);
2559 ilGenImages(1, &iid);
2565 ilDeleteImages(1, &iid);
2575 static bool load_image(const char *file_name, TGAImageRec &tex)
2577 char *ptr = strrchr((char *)file_name, '.');
2580 if (strcasecmp(ptr+1, "png") == 0)
2581 return load_png(file_name, tex);
2582 else if (strcasecmp(ptr+1, "jpg") == 0)
2583 return load_jpg(file_name, tex);
2586 STUBBED("Unsupported image type");
2591 struct my_error_mgr {
2592 struct jpeg_error_mgr pub; /* "public" fields */
2593 jmp_buf setjmp_buffer; /* for return to caller */
2595 typedef struct my_error_mgr * my_error_ptr;
2598 static void my_error_exit(j_common_ptr cinfo)
2600 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
2601 longjmp(err->setjmp_buffer, 1);
2604 /* stolen from public domain example.c code in libjpg distribution. */
2605 static bool load_jpg(const char *file_name, TGAImageRec &tex)
2607 struct jpeg_decompress_struct cinfo;
2608 struct my_error_mgr jerr;
2609 JSAMPROW buffer[1]; /* Output row buffer */
2610 int row_stride; /* physical row width in output buffer */
2611 FILE *infile = fopen(file_name, "rb");
2616 cinfo.err = jpeg_std_error(&jerr.pub);
2617 jerr.pub.error_exit = my_error_exit;
2618 if (setjmp(jerr.setjmp_buffer)) {
2619 jpeg_destroy_decompress(&cinfo);
2624 jpeg_create_decompress(&cinfo);
2625 jpeg_stdio_src(&cinfo, infile);
2626 (void) jpeg_read_header(&cinfo, TRUE);
2628 cinfo.out_color_space = JCS_RGB;
2629 cinfo.quantize_colors = 0;
2630 (void) jpeg_calc_output_dimensions(&cinfo);
2631 (void) jpeg_start_decompress(&cinfo);
2633 row_stride = cinfo.output_width * cinfo.output_components;
2634 tex.sizeX = cinfo.output_width;
2635 tex.sizeY = cinfo.output_height;
2638 while (cinfo.output_scanline < cinfo.output_height) {
2639 buffer[0] = (JSAMPROW)(char *)tex.data +
2640 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
2641 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
2644 (void) jpeg_finish_decompress(&cinfo);
2645 jpeg_destroy_decompress(&cinfo);
2652 /* stolen from public domain example.c code in libpng distribution. */
2653 static bool load_png(const char *file_name, TGAImageRec &tex)
2655 bool hasalpha = false;
2656 png_structp png_ptr = NULL;
2657 png_infop info_ptr = NULL;
2658 png_uint_32 width, height;
2659 int bit_depth, color_type, interlace_type;
2660 png_byte **rows = NULL;
2661 bool retval = false;
2662 png_byte **row_pointers = NULL;
2663 FILE *fp = fopen(file_name, "rb");
2668 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2669 if (png_ptr == NULL)
2672 info_ptr = png_create_info_struct(png_ptr);
2673 if (info_ptr == NULL)
2676 if (setjmp(png_jmpbuf(png_ptr)))
2679 png_init_io(png_ptr, fp);
2680 png_read_png(png_ptr, info_ptr,
2681 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
2683 png_get_IHDR(png_ptr, info_ptr, &width, &height,
2684 &bit_depth, &color_type, &interlace_type, NULL, NULL);
2686 if (bit_depth != 8) // transform SHOULD handle this...
2689 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
2692 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
2695 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
2696 row_pointers = png_get_rows(png_ptr, info_ptr);
2702 png_byte *dst = tex.data;
2703 for (int i = height-1; i >= 0; i--)
2705 png_byte *src = row_pointers[i];
2706 for (int j = 0; j < width; j++)
2720 png_byte *dst = tex.data;
2721 int pitch = width * 4;
2722 for (int i = height-1; i >= 0; i--, dst += pitch)
2723 memcpy(dst, row_pointers[i], pitch);
2732 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
2739 static bool save_image(const char *file_name)
2741 char *ptr = strrchr((char *)file_name, '.');
2744 if (strcasecmp(ptr+1, "png") == 0)
2745 return save_png(file_name);
2748 STUBBED("Unsupported image type");
2753 static bool save_png(const char *file_name)
2756 png_structp png_ptr = NULL;
2757 png_infop info_ptr = NULL;
2758 bool retval = false;
2760 fp = fopen(file_name, "wb");
2764 png_bytep *row_pointers = new png_bytep[kContextHeight];
2765 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
2766 if ((!screenshot) || (!row_pointers))
2770 glReadPixels(0, 0, kContextWidth, kContextHeight,
2771 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
2772 if (glGetError() != GL_NO_ERROR)
2775 for (int i = 0; i < kContextHeight; i++)
2776 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
2778 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2779 if (png_ptr == NULL)
2782 info_ptr = png_create_info_struct(png_ptr);
2783 if (info_ptr == NULL)
2786 if (setjmp(png_jmpbuf(png_ptr)))
2789 png_init_io(png_ptr, fp);
2791 if (setjmp(png_jmpbuf(png_ptr)))
2794 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
2795 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
2796 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2798 png_write_info(png_ptr, info_ptr);
2800 if (setjmp(png_jmpbuf(png_ptr)))
2803 png_write_image(png_ptr, row_pointers);
2805 if (setjmp(png_jmpbuf(png_ptr)))
2808 png_write_end(png_ptr, NULL);
2812 png_destroy_write_struct(&png_ptr, &info_ptr);
2813 delete[] screenshot;
2814 delete[] row_pointers;
2818 unlink(ConvertFileName(file_name));