19 // just use libpng and libjpg directly; it's lighter-weight and easier
20 // to manage the dependencies on Linux...
25 static bool load_image(const char * fname, TGAImageRec & tex);
26 static bool load_png(const char * fname, TGAImageRec & tex);
27 static bool load_jpg(const char * fname, TGAImageRec & tex);
28 static bool save_image(const char * fname);
29 static bool save_png(const char * fname);
34 #pragma comment(lib, "opengl32.lib")
35 #pragma comment(lib, "glu32.lib")
36 #pragma comment(lib, "glaux.lib")
39 extern bool buttons[3];
40 extern float multiplier;
41 extern float screenwidth,screenheight;
43 extern float realmultiplier;
45 extern bool ismotionblur;
46 extern float usermousesensitivity;
48 extern bool floatjump;
49 extern bool cellophane;
51 //extern int terraindetail;
52 //extern int texdetail;
53 extern float terraindetail;
54 extern float texdetail;
55 extern int bloodtoggle;
57 extern bool autoslomo;
59 extern bool musictoggle;
60 extern bool trilinear;
61 extern float gamespeed;
62 extern int difficulty;
63 extern bool damageeffects;
64 extern int numplayers;
66 extern bool invertmouse;
67 extern bool texttoggle;
68 extern bool ambientsound;
69 extern bool mousejump;
71 extern Person player[maxplayers];
73 extern bool stillloading;
74 extern bool showpoints;
75 extern bool alwaysblur;
76 extern bool immediate;
77 extern bool velocityblur;
78 extern bool debugmode;
80 /*extern*/ bool gameFocused;
81 extern int kBitsPerPixel;
82 extern float slomospeed;
83 extern float slomofreq;
84 extern float oldgamespeed;
93 #include "MacCompatibility.h"
101 #include "res/resource.h"
107 SDL_Rect **resolutions = NULL;
108 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
109 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
110 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
111 static SDL_Rect *hardcoded_resolutions[] = {
120 unsigned int resolutionDepths[8][2] = {0};
122 bool selectDetail(int & width, int & height, int & bpp, int & detail);
123 int closestResolution(int width, int height);
124 int resolutionID(int width, int height);
126 void ReportError (char * strError);
128 void SetupDSpFullScreen();
131 void DrawGL(Game & game);
133 void CreateGLWindow (void);
134 Boolean SetUp (Game & game);
135 void DoKey (SInt8 theKey, SInt8 theCode);
136 void DoUpdate (Game & game);
142 // statics/globals (internal only) ------------------------------------------
144 typedef struct tagPOINT {
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; } \
159 static bool lookup_glsym(const char *funcname, void **func)
161 *func = SDL_GL_GetProcAddress(funcname);
164 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
170 static bool lookup_all_glsyms(void)
173 #define GL_FUNC(ret,fn,params,call,rt) \
174 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
180 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
187 void sdlGetCursorPos(POINT *pt)
190 SDL_GetMouseState(&x, &y);
194 #define GetCursorPos(x) sdlGetCursorPos(x)
195 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
196 #define ScreenToClient(x, pt)
197 #define ClientToScreen(x, pt)
198 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
204 static const char g_wndClassName[]={ "LUGARUWINDOWCLASS" };
205 static HINSTANCE g_appInstance;
206 static HWND g_windowHandle;
210 static bool g_button, fullscreen = true;
221 kForegroundSleep = 10,
222 kBackgroundSleep = 10000
229 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
232 char gcstrMode [256] = "";
234 UInt32 gSleepTime = kForegroundSleep;
235 Boolean gDone = false, gfFrontProcess = true;
240 static int _argc = 0;
241 static char **_argv = NULL;
243 bool cmdline(const char *cmd)
245 for (int i = 1; i < _argc; i++)
247 char *arg = _argv[i];
250 if (stricmp(arg, cmd) == 0)
258 // --------------------------------------------------------------------------
260 void ReportError (char * strError)
262 #ifdef WIN32 // !!! FIXME. --ryan.
263 throw std::exception( strError);
266 /* char errMsgCStr [256];
269 sprintf (errMsgCStr, "%s", strError);
271 // out as debug string
272 CToPStr (strErr, errMsgCStr);
277 void SetupDSpFullScreen ()
284 DEVMODE dmScreenSettings;
285 memset( &dmScreenSettings, 0, sizeof( dmScreenSettings));
286 dmScreenSettings.dmSize = sizeof( dmScreenSettings);
287 dmScreenSettings.dmPelsWidth = kContextWidth;
288 dmScreenSettings.dmPelsHeight = kContextHeight;
289 dmScreenSettings.dmBitsPerPel = kBitsPerPixel;
290 dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
293 if (ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
295 ReportError( "Could not set display mode");
312 ChangeDisplaySettings( NULL, 0);
320 //-----------------------------------------------------------------------------------------------------------------------
324 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)
477 case SDL_MOUSEMOTION:
478 game.deltah += e.motion.xrel;
479 game.deltav += e.motion.yrel;
482 case SDL_MOUSEBUTTONDOWN:
484 val = clamp_sdl_mouse_button(e.button.button);
485 if ((val >= 0) && (val <= 2))
494 case SDL_MOUSEBUTTONUP:
496 val = clamp_sdl_mouse_button(e.button.button);
497 if ((val >= 0) && (val <= 2))
501 buttons[val] = false;
507 if (e.key.keysym.sym == SDLK_g)
509 if (e.key.keysym.mod & KMOD_CTRL)
511 SDL_GrabMode mode = SDL_GRAB_ON;
512 if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
514 mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
515 mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
517 SDL_WM_GrabInput(mode);
521 else if (e.key.keysym.sym == SDLK_RETURN)
523 if (e.key.keysym.mod & KMOD_ALT)
524 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
527 if (e.key.keysym.sym < SDLK_LAST)
529 if (KeyTable[e.key.keysym.sym] != 0xffff)
530 SetKey(KeyTable[e.key.keysym.sym]);
533 mod = SDL_GetModState();
535 SetKey(MAC_CONTROL_KEY);
537 SetKey(MAC_OPTION_KEY);
539 SetKey(MAC_COMMAND_KEY);
540 if (mod & KMOD_SHIFT)
541 SetKey(MAC_SHIFT_KEY);
543 SetKey(MAC_CAPS_LOCK_KEY);
548 if (e.key.keysym.sym < SDLK_LAST)
550 if (KeyTable[e.key.keysym.sym] != 0xffff)
551 ClearKey(KeyTable[e.key.keysym.sym]);
554 mod = SDL_GetModState();
555 if ((mod & KMOD_CTRL) == 0)
556 ClearKey(MAC_CONTROL_KEY);
557 if ((mod & KMOD_ALT) == 0)
558 ClearKey(MAC_OPTION_KEY);
559 if ((mod & KMOD_SHIFT) == 0)
560 ClearKey(MAC_SHIFT_KEY);
561 if ((mod & KMOD_CAPS) == 0)
562 ClearKey(MAC_CAPS_LOCK_KEY);
568 // --------------------------------------------------------------------------
570 static Point gMidPoint;
572 Boolean SetUp (Game & game)
578 randSeed = UpTime().lo;
581 ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
584 usermousesensitivity=1;
613 game.crouchkey=MAC_SHIFT_KEY;
614 game.jumpkey=MAC_SPACE_KEY;
615 game.leftkey=MAC_A_KEY;
616 game.forwardkey=MAC_W_KEY;
617 game.backkey=MAC_S_KEY;
618 game.rightkey=MAC_D_KEY;
619 game.drawkey=MAC_E_KEY;
620 game.throwkey=MAC_Q_KEY;
621 game.attackkey=MAC_MOUSEBUTTON1;
622 game.chatkey=MAC_T_KEY;
628 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
631 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
632 opstream << "Screenwidth:\n";
633 opstream << kContextWidth;
634 opstream << "\nScreenheight:\n";
635 opstream << kContextHeight;
636 opstream << "\nMouse sensitivity:\n";
637 opstream << usermousesensitivity;
638 opstream << "\nBlur(0,1):\n";
639 opstream << ismotionblur;
640 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
642 opstream << "\nFloating jump:\n";
643 opstream << floatjump;
644 opstream << "\nMouse jump:\n";
645 opstream << mousejump;
646 opstream << "\nAmbient sound:\n";
647 opstream << ambientsound;
648 opstream << "\nBlood (0,1,2):\n";
649 opstream << bloodtoggle;
650 opstream << "\nAuto slomo:\n";
651 opstream << autoslomo;
652 opstream << "\nFoliage:\n";
654 opstream << "\nMusic:\n";
655 opstream << musictoggle;
656 opstream << "\nTrilinear:\n";
657 opstream << trilinear;
658 opstream << "\nDecals(shadows,blood puddles,etc):\n";
660 opstream << "\nInvert mouse:\n";
661 opstream << invertmouse;
662 opstream << "\nGamespeed:\n";
663 opstream << gamespeed;
664 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
665 opstream << difficulty;
666 opstream << "\nDamage effects(blackout, doublevision):\n";
667 opstream << damageeffects;
668 opstream << "\nText:\n";
669 opstream << texttoggle;
670 opstream << "\nDebug:\n";
671 opstream << debugmode;
672 opstream << "\nVBL Sync:\n";
674 opstream << "\nShow Points:\n";
675 opstream << showpoints;
676 opstream << "\nAlways Blur:\n";
677 opstream << alwaysblur;
678 opstream << "\nImmediate mode (turn on on G5):\n";
679 opstream << immediate;
680 opstream << "\nVelocity blur:\n";
681 opstream << velocityblur;
682 opstream << "\nVolume:\n";
684 opstream << "\nForward key:\n";
685 opstream << KeyToChar(game.forwardkey);
686 opstream << "\nBack key:\n";
687 opstream << KeyToChar(game.backkey);
688 opstream << "\nLeft key:\n";
689 opstream << KeyToChar(game.leftkey);
690 opstream << "\nRight key:\n";
691 opstream << KeyToChar(game.rightkey);
692 opstream << "\nJump key:\n";
693 opstream << KeyToChar(game.jumpkey);
694 opstream << "\nCrouch key:\n";
695 opstream << KeyToChar(game.crouchkey);
696 opstream << "\nDraw key:\n";
697 opstream << KeyToChar(game.drawkey);
698 opstream << "\nThrow key:\n";
699 opstream << KeyToChar(game.throwkey);
700 opstream << "\nAttack key:\n";
701 opstream << KeyToChar(game.attackkey);
702 opstream << "\nChat key:\n";
703 opstream << KeyToChar(game.chatkey);
708 ipstream.ignore(256,'\n');
709 ipstream >> kContextWidth;
710 ipstream.ignore(256,'\n');
711 ipstream.ignore(256,'\n');
712 ipstream >> kContextHeight;
713 ipstream.ignore(256,'\n');
714 ipstream.ignore(256,'\n');
715 ipstream >> usermousesensitivity;
716 ipstream.ignore(256,'\n');
717 ipstream.ignore(256,'\n');
719 ismotionblur = (i != 0);
720 ipstream.ignore(256,'\n');
721 ipstream.ignore(256,'\n');
723 if(detail!=0)kBitsPerPixel=32;
724 else kBitsPerPixel=16;
725 ipstream.ignore(256,'\n');
726 ipstream.ignore(256,'\n');
728 floatjump = (i != 0);
729 ipstream.ignore(256,'\n');
730 ipstream.ignore(256,'\n');
732 mousejump = (i != 0);
733 ipstream.ignore(256,'\n');
734 ipstream.ignore(256,'\n');
736 ambientsound = (i != 0);
737 ipstream.ignore(256,'\n');
738 ipstream.ignore(256,'\n');
739 ipstream >> bloodtoggle;
740 ipstream.ignore(256,'\n');
741 ipstream.ignore(256,'\n');
743 autoslomo = (i != 0);
744 ipstream.ignore(256,'\n');
745 ipstream.ignore(256,'\n');
748 ipstream.ignore(256,'\n');
749 ipstream.ignore(256,'\n');
751 musictoggle = (i != 0);
752 ipstream.ignore(256,'\n');
753 ipstream.ignore(256,'\n');
755 trilinear = (i != 0);
756 ipstream.ignore(256,'\n');
757 ipstream.ignore(256,'\n');
760 ipstream.ignore(256,'\n');
761 ipstream.ignore(256,'\n');
763 invertmouse = (i != 0);
764 ipstream.ignore(256,'\n');
765 ipstream.ignore(256,'\n');
766 ipstream >> gamespeed;
767 oldgamespeed=gamespeed;
772 ipstream.ignore(256,'\n');
773 ipstream.ignore(256,'\n');
774 ipstream >> difficulty;
775 ipstream.ignore(256,'\n');
776 ipstream.ignore(256,'\n');
778 damageeffects = (i != 0);
779 ipstream.ignore(256,'\n');
780 ipstream.ignore(256,'\n');
782 texttoggle = (i != 0);
783 ipstream.ignore(256,'\n');
784 ipstream.ignore(256,'\n');
786 debugmode = (i != 0);
787 ipstream.ignore(256,'\n');
788 ipstream.ignore(256,'\n');
791 ipstream.ignore(256,'\n');
792 ipstream.ignore(256,'\n');
794 showpoints = (i != 0);
795 ipstream.ignore(256,'\n');
796 ipstream.ignore(256,'\n');
798 alwaysblur = (i != 0);
799 ipstream.ignore(256,'\n');
800 ipstream.ignore(256,'\n');
802 immediate = (i != 0);
803 ipstream.ignore(256,'\n');
804 ipstream.ignore(256,'\n');
806 velocityblur = (i != 0);
807 ipstream.ignore(256,'\n');
808 ipstream.ignore(256,'\n');
810 ipstream.ignore(256,'\n');
811 ipstream.ignore(256,'\n');
813 game.forwardkey=CharToKey(string);
814 ipstream.ignore(256,'\n');
815 ipstream.ignore(256,'\n');
817 game.backkey=CharToKey(string);
818 ipstream.ignore(256,'\n');
819 ipstream.ignore(256,'\n');
821 game.leftkey=CharToKey(string);
822 ipstream.ignore(256,'\n');
823 ipstream.ignore(256,'\n');
825 game.rightkey=CharToKey(string);
826 ipstream.ignore(256,'\n');
827 ipstream.ignore(256,'\n');
829 game.jumpkey=CharToKey(string);
830 ipstream.ignore(256,'\n');
831 ipstream.ignore(256,'\n');
833 game.crouchkey=CharToKey(string);
834 ipstream.ignore(256,'\n');
835 ipstream.ignore(256,'\n');
837 game.drawkey=CharToKey(string);
838 ipstream.ignore(256,'\n');
839 ipstream.ignore(256,'\n');
841 game.throwkey=CharToKey(string);
842 ipstream.ignore(256,'\n');
843 ipstream.ignore(256,'\n');
845 game.attackkey=CharToKey(string);
846 ipstream.ignore(256,'\n');
847 ipstream.ignore(256,'\n');
849 game.chatkey=CharToKey(string);
852 if(detail>2)detail=2;
853 if(detail<0)detail=0;
854 if(screenwidth<0)screenwidth=640;
855 if(screenheight<0)screenheight=480;
856 #if !USE_SDL // we'll take anything that works.
857 if(screenwidth>3000)screenwidth=640;
858 if(screenheight>3000)screenheight=480;
861 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
866 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
868 SetupDSpFullScreen();
871 if (!SDL_WasInit(SDL_INIT_VIDEO))
873 if (SDL_Init(SDL_INIT_VIDEO) == -1)
875 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
879 if (SDL_GL_LoadLibrary(NULL) == -1)
881 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
886 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
887 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
888 res = hardcoded_resolutions;
890 // reverse list (it was sorted biggest to smallest by SDL)...
892 for (count = 0; res[count]; count++)
894 if ((res[count]->w < 640) || (res[count]->h < 480))
895 break; // sane lower limit.
898 static SDL_Rect *resolutions_block = NULL;
899 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
900 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
901 if ((resolutions_block == NULL) || (resolutions == NULL))
904 fprintf(stderr, "Out of memory!\n");
908 resolutions[count--] = NULL;
909 for (int i = 0; count >= 0; i++, count--)
911 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
912 resolutions[count] = &resolutions_block[count];
915 if (cmdline("showresolutions"))
917 printf("Resolutions we think are okay:\n");
918 for (int i = 0; resolutions[i]; i++)
919 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
923 Uint32 sdlflags = SDL_OPENGL;
924 if (!cmdline("windowed"))
925 sdlflags |= SDL_FULLSCREEN;
927 SDL_WM_SetCaption("Lugaru", "Lugaru");
931 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
933 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
934 fprintf(stderr, "forcing 640x480...\n");
936 kContextHeight = 480;
937 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
939 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
940 fprintf(stderr, "forcing 640x480 windowed mode...\n");
941 sdlflags &= ~SDL_FULLSCREEN;
942 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
944 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
950 if (!lookup_all_glsyms())
956 if (!cmdline("nomousegrab"))
957 SDL_WM_GrabInput(SDL_GRAB_ON);
959 #elif (defined WIN32)
960 //------------------------------------------------------------------
963 RECT r = {0, 0, kContextWidth-1, kContextHeight-1};
964 DWORD dwStyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE;
965 DWORD dwExStyle = WS_EX_APPWINDOW;
974 dwStyle |= WS_OVERLAPPEDWINDOW;
975 dwExStyle |= WS_EX_WINDOWEDGE;
978 AdjustWindowRectEx(&r, dwStyle, FALSE, dwExStyle);
982 x = (GetSystemMetrics(SM_CXSCREEN) >> 1) - ((r.right - r.left + 1) >> 1);
983 y = (GetSystemMetrics(SM_CYSCREEN) >> 1) - ((r.bottom - r.top + 1) >> 1);
986 g_windowHandle=CreateWindowEx(
988 g_wndClassName, "Lugaru", dwStyle,
990 // kContextWidth, kContextHeight,
991 r.right - r.left + 1, r.bottom - r.top + 1,
992 NULL,NULL,g_appInstance,NULL );
995 ReportError("Could not create window");
999 //------------------------------------------------------------------
1002 static PIXELFORMATDESCRIPTOR pfd =
1004 sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1005 1, // Version Number
1006 PFD_DRAW_TO_WINDOW | // Format Must Support Window
1007 PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
1008 PFD_DOUBLEBUFFER, // Must Support Double Buffering
1009 PFD_TYPE_RGBA, // Request An RGBA Format
1010 kBitsPerPixel, // Select Our Color Depth
1011 0, 0, 0, 0, 0, 0, // Color Bits Ignored
1012 0, // No Alpha Buffer
1013 0, // Shift Bit Ignored
1014 0, // No Accumulation Buffer
1015 0, 0, 0, 0, // Accumulation Bits Ignored
1016 16, // 16Bit Z-Buffer (Depth Buffer)
1017 0, // No Stencil Buffer
1018 0, // No Auxiliary Buffer
1019 PFD_MAIN_PLANE, // Main Drawing Layer
1021 0, 0, 0 // Layer Masks Ignored
1024 if (!(hDC = GetDC( g_windowHandle)))
1025 ReportError( "Could not get device context");
1028 if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))
1030 ReportError( "Could not find appropriate pixel format");
1034 if (!DescribePixelFormat(hDC, PixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd))
1036 ReportError( "Could not retrieve pixel format");
1040 if (!SetPixelFormat( hDC, PixelFormat, &pfd))
1042 ReportError( "Could not set pixel format");
1046 if (!(hRC = wglCreateContext(hDC)))
1048 ReportError( "Could not create rendering context");
1052 if (!wglMakeCurrent(hDC, hRC))
1054 ReportError( "Could not activate rendering context");
1060 // Place the window above all topmost windows
1061 SetWindowPos( g_windowHandle, HWND_TOPMOST, 0,0,0,0,
1062 SWP_NOMOVE | SWP_NOSIZE );
1065 SetForegroundWindow(g_windowHandle);
1066 SetFocus(g_windowHandle);
1069 glClear( GL_COLOR_BUFFER_BIT );
1073 glDisable( GL_ALPHA_TEST);
1074 glDisable( GL_BLEND);
1075 glDisable( GL_DEPTH_TEST);
1076 // glDisable( GL_DITHER);
1078 glDisable( GL_LIGHTING);
1079 glDisable( GL_LOGIC_OP);
1080 glDisable( GL_STENCIL_TEST);
1081 glDisable( GL_TEXTURE_1D);
1082 glDisable( GL_TEXTURE_2D);
1083 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
1084 glPixelTransferi( GL_RED_SCALE, 1);
1085 glPixelTransferi( GL_RED_BIAS, 0);
1086 glPixelTransferi( GL_GREEN_SCALE, 1);
1087 glPixelTransferi( GL_GREEN_BIAS, 0);
1088 glPixelTransferi( GL_BLUE_SCALE, 1);
1089 glPixelTransferi( GL_BLUE_BIAS, 0);
1090 glPixelTransferi( GL_ALPHA_SCALE, 1);
1091 glPixelTransferi( GL_ALPHA_BIAS, 0);
1093 // set initial rendering states
1094 glShadeModel( GL_SMOOTH);
1095 glClearDepth( 1.0f);
1096 glDepthFunc( GL_LEQUAL);
1097 glDepthMask( GL_TRUE);
1098 // glDepthRange( FRONT_CLIP, BACK_CLIP);
1099 glEnable( GL_DEPTH_TEST);
1100 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
1101 glCullFace( GL_FRONT);
1102 glEnable( GL_CULL_FACE);
1103 glEnable( GL_LIGHTING);
1104 // glEnable( GL_LIGHT_MODEL_AMBIENT);
1105 glEnable( GL_DITHER);
1106 glEnable( GL_COLOR_MATERIAL);
1107 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1108 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1109 glAlphaFunc( GL_GREATER, 0.5f);
1112 if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION ||
1113 iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION ||
1114 ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION)
1116 ReportError("DevIL version is different...exiting!\n");
1124 ilutRenderer(ILUT_OPENGL);
1126 ilEnable(IL_ORIGIN_SET);
1127 ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
1130 GLint width = kContextWidth;
1131 GLint height = kContextHeight;
1132 gMidPoint.h = width / 2;
1133 gMidPoint.v = height / 2;
1135 screenheight=height;
1137 game.newdetail=detail;
1138 game.newscreenwidth=screenwidth;
1139 game.newscreenheight=screenheight;
1147 static void DoMouse(Game & game)
1150 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1152 game.deltah *= usermousesensitivity;
1153 game.deltav *= usermousesensitivity;
1154 game.mousecoordh += game.deltah;
1155 game.mousecoordv += game.deltav;
1156 if (game.mousecoordh < 0)
1157 game.mousecoordh = 0;
1158 else if (game.mousecoordh >= kContextWidth)
1159 game.mousecoordh = kContextWidth - 1;
1160 if (game.mousecoordv < 0)
1161 game.mousecoordv = 0;
1162 else if (game.mousecoordv >= kContextHeight)
1163 game.mousecoordv = kContextHeight - 1;
1166 static Point lastMouse = {-1,-1};
1171 ScreenToClient(g_windowHandle, &pos);
1172 globalMouse.h = pos.x;
1173 globalMouse.v = pos.y;
1175 if (lastMouse.h == globalMouse.h && lastMouse.v == globalMouse.v)
1182 static Point virtualMouse = {0,0};
1183 delta = globalMouse;
1185 delta.h -= lastMouse.h;
1186 delta.v -= lastMouse.v;
1187 lastMouse.h = pos.x;
1188 lastMouse.v = pos.y;
1190 if(mainmenu||(abs(delta.h)<10*realmultiplier*1000&&abs(delta.v)<10*realmultiplier*1000)){
1191 game.deltah=delta.h*usermousesensitivity;
1192 game.deltav=delta.v*usermousesensitivity;
1193 game.mousecoordh=globalMouse.h;
1194 game.mousecoordv=globalMouse.v;
1199 if(lastMouse.h>gMidPoint.h+100||lastMouse.h<gMidPoint.h-100||lastMouse.v>gMidPoint.v+100||lastMouse.v<gMidPoint.v-100){
1200 pos.x = gMidPoint.h;
1201 pos.y = gMidPoint.v;
1202 ClientToScreen(g_windowHandle, &pos);
1203 //SetCursorPos( gMidPoint.h,gMidPoint.v);
1204 SetCursorPos(pos.x, pos.y);
1205 lastMouse = gMidPoint;
1214 // --------------------------------------------------------------------------
1216 void DoKey (SInt8 theKey, SInt8 theCode)
1221 // --------------------------------------------------------------------------
1225 void DoFrameRate (int update)
1227 static long frames = 0;
1229 static AbsoluteTime time = {0,0};
1230 static AbsoluteTime frametime = {0,0};
1231 AbsoluteTime currTime = UpTime ();
1232 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1234 if (0 > deltaTime) // if negative microseconds
1235 deltaTime /= -1000000.0;
1236 else // else milliseconds
1237 deltaTime /= 1000.0;
1239 multiplier=deltaTime;
1240 if(multiplier<.001)multiplier=.001;
1241 if(multiplier>10)multiplier=10;
1242 if(update)frametime = currTime; // reset for next time interval
1244 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1246 if (0 > deltaTime) // if negative microseconds
1247 deltaTime /= -1000000.0;
1248 else // else milliseconds
1249 deltaTime /= 1000.0;
1251 if (0.001 <= deltaTime) // has update interval passed
1254 time = currTime; // reset for next time interval
1261 void DoUpdate (Game & game)
1263 static float sps=200;
1265 static float oldmult;
1268 if(multiplier>.6)multiplier=.6;
1270 game.fps=1/multiplier;
1272 count = multiplier*sps;
1274 //if(count>10)count=10;
1276 realmultiplier=multiplier;
1277 multiplier*=gamespeed;
1278 if(difficulty==1)multiplier*=.9;
1279 if(difficulty==0)multiplier*=.8;
1281 if(game.loading==4)multiplier*=.00001;
1283 if(slomo&&!mainmenu)multiplier*=slomospeed;
1284 //if(freeze)multiplier*=0.00001;
1286 multiplier/=(float)count;
1292 for(int i=0;i<count;i++)
1298 game.TickOnceAfter();
1299 /* - Debug code to test how many channels were active on average per frame
1300 static long frames = 0;
1302 static AbsoluteTime start = {0,0};
1303 AbsoluteTime currTime = UpTime ();
1304 static int num_channels = 0;
1306 num_channels += FSOUND_GetChannelsPlaying();
1307 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1309 if (0 > deltaTime) // if negative microseconds
1310 deltaTime /= -1000000.0;
1311 else // else milliseconds
1312 deltaTime /= 1000.0;
1319 float avg_channels = (float)num_channels / (float)frames;
1321 ofstream opstream("log.txt",ios::app);
1322 opstream << "Average frame count: ";
1324 opstream << " frames - ";
1325 opstream << avg_channels;
1326 opstream << " per frame.\n";
1336 // --------------------------------------------------------------------------
1351 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1352 #include "glstubs.h"
1354 // cheat here...static destructors are calling glDeleteTexture() after
1355 // the context is destroyed and libGL unloaded by SDL_Quit().
1356 pglDeleteTextures = glDeleteTextures_doNothing;
1358 #elif (defined WIN32)
1361 wglMakeCurrent( NULL, NULL);
1362 wglDeleteContext( hRC);
1368 ReleaseDC( g_windowHandle, hDC);
1374 ShowWindow( g_windowHandle, SW_HIDE );
1375 DestroyWindow( g_windowHandle);
1376 g_windowHandle = NULL;
1384 // --------------------------------------------------------------------------
1386 static bool g_focused = true;
1389 static bool IsFocused()
1395 if (GetActiveWindow() != g_windowHandle)
1398 if (IsIconic( g_windowHandle))
1406 static void launch_web_browser(const char *url)
1409 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1411 #elif (defined(__APPLE__) && defined(__MACH__))
1412 const char *fmt = "open '%s'";
1413 const size_t len = strlen(fmt) + strlen(url) + 16;
1414 char *buf = new char[len];
1415 snprintf(buf, len, fmt, url);
1419 #elif PLATFORM_LINUX
1420 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1421 const size_t len = strlen(fmt) + strlen(url) + 16;
1422 char *buf = new char[len];
1423 snprintf(buf, len, fmt, url);
1431 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1432 static char *findBinaryInPath(const char *bin, char *envr)
1434 size_t alloc_size = 0;
1442 ptr = strchr(start, ':'); /* find next $PATH separator. */
1446 size = strlen(start) + strlen(bin) + 2;
1447 if (size > alloc_size)
1449 char *x = (char *) realloc(exe, size);
1461 /* build full binary path... */
1463 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1467 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
1469 strcpy(exe, start); /* i'm lazy. piss off. */
1473 start = ptr + 1; /* start points to beginning of next element. */
1474 } while (ptr != NULL);
1479 return(NULL); /* doesn't exist in path. */
1480 } /* findBinaryInPath */
1483 char *calcBaseDir(const char *argv0)
1485 /* If there isn't a path on argv0, then look through the $PATH for it. */
1489 char *ptr = strrchr(argv0, '/');
1490 if (strchr(argv0, '/'))
1492 retval = strdup(argv0);
1494 *(strrchr(retval, '/')) = '\0';
1498 envr = getenv("PATH");
1499 if (!envr) return NULL;
1500 envr = strdup(envr);
1501 if (!envr) return NULL;
1502 retval = findBinaryInPath(argv0, envr);
1507 static inline void chdirToAppPath(const char *argv0)
1509 char *dir = calcBaseDir(argv0);
1512 #if (defined(__APPLE__) && defined(__MACH__))
1513 // Chop off /Contents/MacOS if it's at the end of the string, so we
1514 // land in the base of the app bundle.
1515 const size_t len = strlen(dir);
1516 const char *bundledirs = "/Contents/MacOS";
1517 const size_t bundledirslen = strlen(bundledirs);
1518 if (len > bundledirslen)
1520 char *ptr = (dir + len) - bundledirslen;
1521 if (strcasecmp(ptr, bundledirs) == 0)
1532 int main(int argc, char **argv)
1537 chdirToAppPath(argv[0]);
1542 #ifndef WIN32 // this is in WinMain, too.
1544 memset( &g_theKeys, 0, sizeof( KeyMap));
1551 bool regnow = false;
1556 //ofstream os("error.txt");
1558 //ofstream os("log.txt");
1564 while (!gDone&&!game.quit&&(!game.tryquit||!game.registered))
1570 // check windows messages
1576 while( SDL_PollEvent( &e ) )
1578 if( e.type == SDL_QUIT )
1583 sdlEventProc(e, game);
1586 #elif (defined WIN32)
1589 while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE | PM_NOYIELD ) )
1591 if( msg.message == WM_QUIT )
1598 TranslateMessage( &msg );
1599 DispatchMessage( &msg );
1611 // allow game chance to pause
1612 gameFocused = false;
1616 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1620 //if (GetMessage( &msg, g_windowHandle, 0, 0 ))
1621 /*if (GetMessage( &msg, NULL, 0, 0 ))
1623 TranslateMessage(&msg);
1624 DispatchMessage(&msg);
1626 if ( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
1630 // handle the error and possibly exit
1635 TranslateMessage(&msg);
1636 DispatchMessage(&msg);
1640 STUBBED("give up CPU but sniff the event queue");
1645 regnow = game.registernow;
1650 // if(game.registernow){
1653 #if (defined(__APPLE__) && defined(__MACH__))
1654 launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1655 #elif PLATFORM_LINUX
1656 launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1658 launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1662 #if PLATFORM_LINUX // (this may not be necessary any more.)
1663 _exit(0); // !!! FIXME: hack...crashes on exit!
1667 catch (const std::exception& error)
1671 std::string e = "Caught exception: ";
1674 LOG(e, Logger::LOG_ERR);
1676 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1686 // --------------------------------------------------------------------------
1689 #define MAX_WINKEYS 256
1690 static unsigned short KeyTable[MAX_WINKEYS]=
1693 MAC_MOUSEBUTTON1, // VK_LBUTTON (1)
1694 MAC_MOUSEBUTTON2, // VK_RBUTTON (2)
1695 0xffff, // VK_CANCEL (3)
1696 0xffff, // VK_MBUTTON (4)
1700 MAC_DELETE_KEY, // VK_BACK (8)
1701 MAC_TAB_KEY, // VK_TAB (9)
1704 0xffff, // VK_CLEAR (12)
1705 MAC_RETURN_KEY, // VK_RETURN (13)
1708 MAC_SHIFT_KEY, // VK_SHIFT (16)
1709 MAC_CONTROL_KEY, // VK_CONTROL (17)
1710 MAC_OPTION_KEY, // VK_MENU (18)
1711 0xffff, // VK_PAUSE (19)
1712 MAC_CAPS_LOCK_KEY, // #define VK_CAPITAL (20)
1719 MAC_ESCAPE_KEY, // VK_ESCAPE (27)
1724 MAC_SPACE_KEY, // VK_SPACE (32)
1725 MAC_PAGE_UP_KEY, // VK_PRIOR (33)
1726 MAC_PAGE_DOWN_KEY, // VK_NEXT (34)
1727 MAC_END_KEY, // VK_END (35)
1728 MAC_HOME_KEY, // VK_HOME (36)
1729 MAC_ARROW_LEFT_KEY, // VK_LEFT (37)
1730 MAC_ARROW_UP_KEY, // VK_UP (38)
1731 MAC_ARROW_RIGHT_KEY, // VK_RIGHT (39)
1732 MAC_ARROW_DOWN_KEY, // VK_DOWN (40)
1733 0xffff, // VK_SELECT (41)
1734 0xffff, // VK_PRINT (42)
1735 0xffff, // VK_EXECUTE (43)
1736 0xffff, // VK_SNAPSHOT (44)
1737 MAC_INSERT_KEY, // VK_INSERT (45)
1738 MAC_DEL_KEY, // VK_DELETE (46)
1739 0xffff, // VK_HELP (47)
1740 MAC_0_KEY, // VK_0 (48)
1741 MAC_1_KEY, // VK_1 (49)
1742 MAC_2_KEY, // VK_2 (50)
1743 MAC_3_KEY, // VK_3 (51)
1744 MAC_4_KEY, // VK_4 (52)
1745 MAC_5_KEY, // VK_5 (53)
1746 MAC_6_KEY, // VK_6 (54)
1747 MAC_7_KEY, // VK_7 (55)
1748 MAC_8_KEY, // VK_8 (56)
1749 MAC_9_KEY, // VK_9 (57)
1757 MAC_A_KEY, // VK_A (65)
1758 MAC_B_KEY, // VK_B (66)
1759 MAC_C_KEY, // VK_C (67)
1760 MAC_D_KEY, // VK_D (68)
1761 MAC_E_KEY, // VK_E (69)
1762 MAC_F_KEY, // VK_F (70)
1763 MAC_G_KEY, // VK_G (71)
1764 MAC_H_KEY, // VK_H (72)
1765 MAC_I_KEY, // VK_I (73)
1766 MAC_J_KEY, // VK_J (74)
1767 MAC_K_KEY, // VK_K (75)
1768 MAC_L_KEY, // VK_L (76)
1769 MAC_M_KEY, // VK_M (77)
1770 MAC_N_KEY, // VK_N (78)
1771 MAC_O_KEY, // VK_O (79)
1772 MAC_P_KEY, // VK_P (80)
1773 MAC_Q_KEY, // VK_Q (81)
1774 MAC_R_KEY, // VK_R (82)
1775 MAC_S_KEY, // VK_S (83)
1776 MAC_T_KEY, // VK_T (84)
1777 MAC_U_KEY, // VK_U (85)
1778 MAC_V_KEY, // VK_V (86)
1779 MAC_W_KEY, // VK_W (87)
1780 MAC_X_KEY, // VK_X (88)
1781 MAC_Y_KEY, // VK_Y (89)
1782 MAC_Z_KEY, // VK_Z (90)
1788 MAC_NUMPAD_0_KEY, // VK_NUMPAD0 (96)
1789 MAC_NUMPAD_1_KEY, // VK_NUMPAD1 (97)
1790 MAC_NUMPAD_2_KEY, // VK_NUMPAD2 (98)
1791 MAC_NUMPAD_3_KEY, // VK_NUMPAD3 (99)
1792 MAC_NUMPAD_4_KEY, // VK_NUMPAD4 (100)
1793 MAC_NUMPAD_5_KEY, // VK_NUMPAD5 (101)
1794 MAC_NUMPAD_6_KEY, // VK_NUMPAD6 (102)
1795 MAC_NUMPAD_7_KEY, // VK_NUMPAD7 (103)
1796 MAC_NUMPAD_8_KEY, // VK_NUMPAD8 (104)
1797 MAC_NUMPAD_9_KEY, // VK_NUMPAD9 (105)
1798 MAC_NUMPAD_ASTERISK_KEY, // VK_MULTIPLY (106)
1799 MAC_NUMPAD_PLUS_KEY, // VK_ADD (107)
1800 MAC_NUMPAD_ENTER_KEY, // VK_SEPARATOR (108)
1801 MAC_NUMPAD_MINUS_KEY, // VK_SUBTRACT (109)
1802 MAC_NUMPAD_PERIOD_KEY, // VK_DECIMAL (110)
1803 MAC_NUMPAD_SLASH_KEY, // VK_DIVIDE (111)
1804 MAC_F1_KEY, // VK_F1 (112)
1805 MAC_F2_KEY, // VK_F2 (113)
1806 MAC_F3_KEY, // VK_F3 (114)
1807 MAC_F4_KEY, // VK_F4 (115)
1808 MAC_F5_KEY, // VK_F5 (116)
1809 MAC_F6_KEY, // VK_F6 (117)
1810 MAC_F7_KEY, // VK_F7 (118)
1811 MAC_F8_KEY, // VK_F8 (119)
1812 MAC_F9_KEY, // VK_F9 (120)
1813 MAC_F10_KEY, // VK_F10 (121)
1814 MAC_F11_KEY, // VK_F11 (122)
1815 MAC_F12_KEY, // VK_F12 (123)
1836 0xffff, // VK_NUMLOCK (144)
1837 0xffff, // VK_SCROLL (145)
1852 MAC_SHIFT_KEY, // VK_LSHIFT (160)
1853 MAC_SHIFT_KEY, // VK_RSHIFT (161)
1854 MAC_CONTROL_KEY, // VK_LCONTROL (162)
1855 MAC_CONTROL_KEY, // VK_RCONTROL (163)
1856 MAC_OPTION_KEY, // VK_LMENU (164)
1857 MAC_OPTION_KEY, // VK_RMENU (165)
1878 MAC_SEMICOLON_KEY, // (186)
1879 MAC_PLUS_KEY, // (187)
1880 MAC_COMMA_KEY, // (188)
1881 MAC_MINUS_KEY, // (189)
1882 MAC_PERIOD_KEY, // (190)
1883 MAC_SLASH_KEY, // (191)
1884 MAC_TILDE_KEY, // (192)
1911 MAC_LEFTBRACKET_KEY, // (219)
1912 MAC_BACKSLASH_KEY, // (220)
1913 MAC_RIGHTBRACKET_KEY, // (221)
1914 MAC_APOSTROPHE_KEY, // (222)
1950 void ClipMouseToWindow(HWND window)
1954 GetClientRect(window, &wRect);
1956 ClientToScreen(window, (LPPOINT)&wRect.left);
1957 ClientToScreen(window, (LPPOINT)&wRect.right);
1964 LRESULT FAR PASCAL AppWndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
1966 /* this is where we receive all messages concerning this window
1967 * we can either process a message or pass it on to the default
1968 * message handler of windows */
1970 static PAINTSTRUCT ps;
1974 case WM_ACTIVATE: // Watch For Window Activate Message
1976 // Check Minimization State
1977 BOOL iconified = HIWORD(wParam) ? TRUE : FALSE;
1979 if (LOWORD(wParam) == WA_INACTIVE)
1988 CloseWindow( hWnd );
1990 // The window is now iconified
1991 iconified = GL_TRUE;
1997 g_focused=false; // Program Is Active
2001 SetupDSpFullScreen();
2008 // The window is now iconified
2009 iconified = GL_FALSE;
2012 ShowWindow( hWnd, SW_SHOW );
2013 SetForegroundWindow( hWnd );
2017 ClipMouseToWindow(hWnd);
2018 g_focused=true; // Program Is No Longer Active
2021 return 0; // Return To The Message Loop
2027 // check for Alt-F4 (exit hotkey)
2028 if (wParam == VK_F4)
2030 if (GetKeyState( VK_MENU) & 0x8080)
2036 if (wParam < MAX_WINKEYS)
2038 if (KeyTable[wParam] != 0xffff)
2039 SetKey( KeyTable[wParam]);
2047 if (wParam < MAX_WINKEYS)
2048 if (KeyTable[wParam] != 0xffff)
2049 ClearKey( KeyTable[wParam]);
2056 case WM_SYSDEADCHAR:
2059 case WM_NCLBUTTONDOWN:
2060 case WM_LBUTTONDOWN:
2067 case WM_NCRBUTTONDOWN:
2068 case WM_RBUTTONDOWN:
2074 case WM_NCMBUTTONDOWN:
2075 case WM_MBUTTONDOWN:
2081 case WM_NCLBUTTONUP:
2085 buttons[ 0] = false;
2089 case WM_NCRBUTTONUP:
2092 buttons[ 1] = false;
2096 case WM_NCMBUTTONUP:
2099 buttons[ 2] = false;
2103 case WM_NCLBUTTONDBLCLK:
2104 case WM_NCRBUTTONDBLCLK:
2105 case WM_NCMBUTTONDBLCLK:
2106 case WM_LBUTTONDBLCLK:
2108 case WM_RBUTTONDBLCLK:
2109 case WM_MBUTTONDBLCLK:
2112 case WM_NCMOUSEMOVE:
2114 /* ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseX = (signed short)(lParam & 0xffff);
2115 ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseY = (signed short)(lParam >> 16);
2116 if (g_lastWindow->m_mouseCallbacksEnabled) g_lastWindow->MouseMoveCallback();
2117 */// goto winmessage;
2120 case WM_SYSCOMMAND: // Intercept System Commands
2122 switch (wParam) // Check System Calls
2124 case SC_SCREENSAVE: // Screensaver Trying To Start?
2125 case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
2126 return 0; // Prevent From Happening
2128 // User trying to access application menu using ALT?
2137 // ReleaseCapture();
2138 // ClipMouseToWindow(hWnd);
2155 PostQuitMessage(0); /* Terminate Application */
2163 // BeginPaint( g_windowHandle,&ps);
2164 // EndPaint( g_windowHandle,&ps);
2171 /* We processed the message and there
2172 * is no processing by Windows necessary */
2174 /* We didn't process the message so let Windows do it */
2175 return DefWindowProc(hWnd,msg,wParam,lParam);
2179 static BOOL RegisterWindowClasses(HINSTANCE hFirstInstance)
2182 memset( &wc, 0, sizeof( wc));
2184 /* Register the window class. */
2185 wc.cbSize = sizeof(wc);
2187 wc.style = (CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_OWNDC); /* Combination of Class Styles */
2188 wc.lpfnWndProc = AppWndProc; /* Adress of Window Procedure */
2189 wc.cbClsExtra = 0; /* Extra Bytes allocated for this Class */
2190 wc.cbWndExtra = 0; /* Extra Bytes allocated for each Window */
2191 wc.hInstance = hFirstInstance; /* Handle of program instance */
2192 wc.hIcon = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2193 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2194 wc.hbrBackground = NULL;
2195 wc.lpszMenuName = NULL;
2196 wc.lpszClassName = g_wndClassName; /* Name of the Window Class */
2197 wc.hIconSm = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2199 if (!RegisterClassEx(&wc)) return FALSE; /* Register Class failed */
2206 int resolutionID(int width, int height)
2210 if(width==640 && height==480)whichres=0;
2211 if(width==800 && height==600)whichres=1;
2212 if(width==1024 && height==768)whichres=2;
2213 if(width==1280 && height==1024)whichres=3;
2214 if(width==1600 && height==1200)whichres=4;
2215 if(width==840 && height==524)whichres=5;
2216 if(width==1024 && height==640)whichres=6;
2217 if(width==1344 && height==840)whichres=7;
2218 if(width==1920 && height==1200)whichres=8;
2223 int closestResolution(int width, int height)
2227 if(width>=640 && height>=480)whichres=0;
2228 if(width>=800 && height>=600)whichres=1;
2229 if(width>=1024 && height>=768)whichres=2;
2230 if(width>=1280 && height>=1024)whichres=3;
2231 if(width>=1600 && height>=1200)whichres=4;
2232 if(width==840 && height==524)whichres=5;
2233 if(width==1024 && height==640)whichres=6;
2234 if(width==1344 && height==840)whichres=7;
2235 if(width>=1920 && height>=1200)whichres=8;
2241 bool selectDetail(int & width, int & height, int & bpp, int & detail)
2245 // currently with SDL, we just use whatever is requested
2246 // and don't care. --ryan.
2248 int whichres = closestResolution(width, height);
2252 if(whichres<=0 || whichres>8){
2290 if ((detail != 0) && (resolutionDepths[whichres][1] != 0))
2294 else if ((detail == 0) && (resolutionDepths[whichres][0] != 0))
2298 else if ((detail != 0) && (resolutionDepths[whichres][0] != 0))
2314 bpp = resolutionDepths[whichres][(detail != 0)];
2321 int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
2324 LPWSTR * cl = CommandLineToArgvW(GetCommandLineW(), &argc);
2327 if (0 == _wcsicmp(cl[1], L"-windowed"))
2335 memset( &g_theKeys, 0, sizeof( KeyMap));
2339 memset(&mode, 0, sizeof(mode));
2340 mode.dmSize = sizeof(mode);
2341 while (EnumDisplaySettings(NULL, i++, &mode))
2343 if (mode.dmBitsPerPel < 16)
2348 int res = resolutionID(mode.dmPelsWidth, mode.dmPelsHeight);
2350 if (res > -1 && res < 8)
2352 if (DISP_CHANGE_SUCCESSFUL != ChangeDisplaySettings(&mode, CDS_TEST))
2357 switch(mode.dmBitsPerPel)
2361 resolutionDepths[res][1] = mode.dmBitsPerPel;
2364 resolutionDepths[res][0] = mode.dmBitsPerPel;
2370 /* if there is no Instance of our program in memory then register the window class */
2371 if (hPrevInstance == NULL && !RegisterWindowClasses(hInstance))
2372 return FALSE; /* registration failed! */
2374 g_appInstance=hInstance;
2378 UnregisterClass( g_wndClassName, hInstance);
2385 extern int channels[100];
2386 extern FSOUND_SAMPLE * samp[100];
2387 extern FSOUND_STREAM * strm[20];
2389 extern "C" void PlaySoundEx(int chan, FSOUND_SAMPLE *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2391 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2392 if (currSample && currSample == samp[chan])
2394 if (FSOUND_GetPaused(channels[chan]))
2396 FSOUND_StopSound(channels[chan]);
2397 channels[chan] = FSOUND_FREE;
2399 else if (FSOUND_IsPlaying(channels[chan]))
2401 int loop_mode = FSOUND_GetLoopMode(channels[chan]);
2402 if (loop_mode & FSOUND_LOOP_OFF)
2404 channels[chan] = FSOUND_FREE;
2410 channels[chan] = FSOUND_FREE;
2413 channels[chan] = FSOUND_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
2414 if (channels[chan] < 0)
2416 channels[chan] = FSOUND_PlaySoundEx(FSOUND_FREE, sptr, dsp, startpaused);
2420 extern "C" void PlayStreamEx(int chan, FSOUND_STREAM *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2422 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2423 if (currSample && currSample == FSOUND_Stream_GetSample(sptr))
2425 FSOUND_StopSound(channels[chan]);
2426 FSOUND_Stream_Stop(sptr);
2430 FSOUND_Stream_Stop(sptr);
2431 channels[chan] = FSOUND_FREE;
2434 channels[chan] = FSOUND_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
2435 if (channels[chan] < 0)
2437 channels[chan] = FSOUND_Stream_PlayEx(FSOUND_FREE, sptr, dsp, startpaused);
2441 bool LoadImage(const char * fname, TGAImageRec & tex)
2445 if ( tex.data == NULL )
2451 ILstring f = strdup(ConvertFileName(fname));
2458 ilGenImages(1, &iid);
2463 tex.sizeX = ilGetInteger(IL_IMAGE_WIDTH);
2464 tex.sizeY = ilGetInteger(IL_IMAGE_HEIGHT);
2465 tex.bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
2466 ILuint Bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL),
2467 imageSize = tex.sizeX * tex.sizeY * Bpp;
2468 ILubyte *Data = ilGetData();
2469 memcpy(tex.data, Data, imageSize);
2471 // Truvision Targa files are stored as BGR colors
2472 // We want RGB so Blue and Red bytes are switched
2473 if (IL_TGA == ilGetInteger(IL_IMAGE_FORMAT))
2475 // Loop Through The Image Data
2476 for (GLuint i = 0; i < int(imageSize); i += Bpp)
2478 // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
2479 GLbyte temp; // Temporary Variable
2480 temp = tex.data[i]; // Temporarily Store The Value At Image Data 'i'
2481 tex.data[i] = tex.data[i + 2]; // Set The 1st Byte To The Value Of The 3rd Byte
2482 tex.data[i + 2] = temp; // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
2490 ilDeleteImages(1, &iid);
2494 GLuint texid = ilutGLLoadImage(f);
2499 ilutGLBuildMipmaps()
2508 res = load_image(fname, tex);
2509 //if (!res) printf("failed to load %s\n", fname);
2515 void ScreenShot(const char * fname)
2518 ILstring f = strdup(fname);
2525 ilGenImages(1, &iid);
2531 ilDeleteImages(1, &iid);
2541 static bool load_image(const char *file_name, TGAImageRec &tex)
2543 char *ptr = strrchr(file_name, '.');
2546 if (stricmp(ptr+1, "png") == 0)
2547 return load_png(file_name, tex);
2548 else if (stricmp(ptr+1, "jpg") == 0)
2549 return load_jpg(file_name, tex);
2552 STUBBED("Unsupported image type");
2557 struct my_error_mgr {
2558 struct jpeg_error_mgr pub; /* "public" fields */
2559 jmp_buf setjmp_buffer; /* for return to caller */
2561 typedef struct my_error_mgr * my_error_ptr;
2564 static void my_error_exit(j_common_ptr cinfo)
2566 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
2567 longjmp(err->setjmp_buffer, 1);
2570 /* stolen from public domain example.c code in libjpg distribution. */
2571 static bool load_jpg(const char *file_name, TGAImageRec &tex)
2573 struct jpeg_decompress_struct cinfo;
2574 struct my_error_mgr jerr;
2575 JSAMPROW buffer[1]; /* Output row buffer */
2576 int row_stride; /* physical row width in output buffer */
2577 FILE *infile = fopen(file_name, "rb");
2582 cinfo.err = jpeg_std_error(&jerr.pub);
2583 jerr.pub.error_exit = my_error_exit;
2584 if (setjmp(jerr.setjmp_buffer)) {
2585 jpeg_destroy_decompress(&cinfo);
2590 jpeg_create_decompress(&cinfo);
2591 jpeg_stdio_src(&cinfo, infile);
2592 (void) jpeg_read_header(&cinfo, TRUE);
2594 cinfo.out_color_space = JCS_RGB;
2595 cinfo.quantize_colors = 0;
2596 (void) jpeg_calc_output_dimensions(&cinfo);
2597 (void) jpeg_start_decompress(&cinfo);
2599 row_stride = cinfo.output_width * cinfo.output_components;
2600 tex.sizeX = cinfo.output_width;
2601 tex.sizeY = cinfo.output_height;
2604 while (cinfo.output_scanline < cinfo.output_height) {
2605 buffer[0] = (JSAMPROW)(char *)tex.data +
2606 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
2607 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
2610 (void) jpeg_finish_decompress(&cinfo);
2611 jpeg_destroy_decompress(&cinfo);
2618 /* stolen from public domain example.c code in libpng distribution. */
2619 static bool load_png(const char *file_name, TGAImageRec &tex)
2621 bool hasalpha = false;
2622 png_structp png_ptr = NULL;
2623 png_infop info_ptr = NULL;
2624 png_uint_32 width, height;
2625 int bit_depth, color_type, interlace_type;
2626 png_byte **rows = NULL;
2627 bool retval = false;
2628 png_byte **row_pointers = NULL;
2629 FILE *fp = fopen(file_name, "rb");
2634 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2635 if (png_ptr == NULL)
2638 info_ptr = png_create_info_struct(png_ptr);
2639 if (info_ptr == NULL)
2642 if (setjmp(png_jmpbuf(png_ptr)))
2645 png_init_io(png_ptr, fp);
2646 png_read_png(png_ptr, info_ptr,
2647 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
2649 png_get_IHDR(png_ptr, info_ptr, &width, &height,
2650 &bit_depth, &color_type, &interlace_type, NULL, NULL);
2652 if (bit_depth != 8) // transform SHOULD handle this...
2655 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
2658 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
2661 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
2662 row_pointers = png_get_rows(png_ptr, info_ptr);
2668 png_byte *dst = tex.data;
2669 for (int i = height-1; i >= 0; i--)
2671 png_byte *src = row_pointers[i];
2672 for (int j = 0; j < width; j++)
2686 png_byte *dst = tex.data;
2687 int pitch = width * 4;
2688 for (int i = height-1; i >= 0; i--, dst += pitch)
2689 memcpy(dst, row_pointers[i], pitch);
2698 png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
2705 static bool save_image(const char *file_name)
2707 char *ptr = strrchr(file_name, '.');
2710 if (stricmp(ptr+1, "png") == 0)
2711 return save_png(file_name);
2714 STUBBED("Unsupported image type");
2719 static bool save_png(const char *file_name)
2722 png_structp png_ptr = NULL;
2723 png_infop info_ptr = NULL;
2724 bool retval = false;
2726 fp = fopen(file_name, "wb");
2730 png_bytep *row_pointers = new png_bytep[kContextHeight];
2731 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
2732 if ((!screenshot) || (!row_pointers))
2736 glReadPixels(0, 0, kContextWidth, kContextHeight,
2737 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
2738 if (glGetError() != GL_NO_ERROR)
2741 for (int i = 0; i < kContextHeight; i++)
2742 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
2744 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2745 if (png_ptr == NULL)
2748 info_ptr = png_create_info_struct(png_ptr);
2749 if (info_ptr == NULL)
2752 if (setjmp(png_jmpbuf(png_ptr)))
2755 png_init_io(png_ptr, fp);
2757 if (setjmp(png_jmpbuf(png_ptr)))
2760 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
2761 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
2762 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2764 png_write_info(png_ptr, info_ptr);
2766 if (setjmp(png_jmpbuf(png_ptr)))
2769 png_write_image(png_ptr, row_pointers);
2771 if (setjmp(png_jmpbuf(png_ptr)))
2774 png_write_end(png_ptr, NULL);
2778 png_destroy_write_struct(&png_ptr, &info_ptr);
2779 delete[] screenshot;
2780 delete[] row_pointers;
2784 unlink(ConvertFileName(file_name));