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"
106 unsigned int resolutionDepths[8][2] = {0};
108 bool selectDetail(int & width, int & height, int & bpp, int & detail);
109 int closestResolution(int width, int height);
110 int resolutionID(int width, int height);
112 void ReportError (char * strError);
114 void SetupDSpFullScreen();
117 void DrawGL(Game & game);
119 void CreateGLWindow (void);
120 Boolean SetUp (Game & game);
121 void DoKey (SInt8 theKey, SInt8 theCode);
122 void DoUpdate (Game & game);
128 // statics/globals (internal only) ------------------------------------------
130 typedef struct tagPOINT {
137 #define GL_FUNC(ret,fn,params,call,rt) \
139 static ret GLAPIENTRY (*p##fn) params = NULL; \
140 ret GLAPIENTRY fn params { rt p##fn call; } \
145 static bool lookup_glsym(const char *funcname, void **func)
147 *func = SDL_GL_GetProcAddress(funcname);
150 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
156 static bool lookup_all_glsyms(void)
159 #define GL_FUNC(ret,fn,params,call,rt) \
160 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
166 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
173 void sdlGetCursorPos(POINT *pt)
176 SDL_GetMouseState(&x, &y);
180 #define GetCursorPos(x) sdlGetCursorPos(x)
181 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
182 #define ScreenToClient(x, pt)
183 #define ClientToScreen(x, pt)
184 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
190 static const char g_wndClassName[]={ "LUGARUWINDOWCLASS" };
191 static HINSTANCE g_appInstance;
192 static HWND g_windowHandle;
196 static bool g_button, fullscreen = true;
207 kForegroundSleep = 10,
208 kBackgroundSleep = 10000
215 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
218 char gcstrMode [256] = "";
220 UInt32 gSleepTime = kForegroundSleep;
221 Boolean gDone = false, gfFrontProcess = true;
226 static int _argc = 0;
227 static char **_argv = NULL;
229 bool cmdline(const char *cmd)
231 for (int i = 1; i < _argc; i++)
233 char *arg = _argv[i];
236 if (stricmp(arg, cmd) == 0)
244 // --------------------------------------------------------------------------
246 void ReportError (char * strError)
248 #ifdef WIN32 // !!! FIXME. --ryan.
249 throw std::exception( strError);
252 /* char errMsgCStr [256];
255 sprintf (errMsgCStr, "%s", strError);
257 // out as debug string
258 CToPStr (strErr, errMsgCStr);
263 void SetupDSpFullScreen ()
270 DEVMODE dmScreenSettings;
271 memset( &dmScreenSettings, 0, sizeof( dmScreenSettings));
272 dmScreenSettings.dmSize = sizeof( dmScreenSettings);
273 dmScreenSettings.dmPelsWidth = kContextWidth;
274 dmScreenSettings.dmPelsHeight = kContextHeight;
275 dmScreenSettings.dmBitsPerPel = kBitsPerPixel;
276 dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
279 if (ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
281 ReportError( "Could not set display mode");
298 ChangeDisplaySettings( NULL, 0);
306 //-----------------------------------------------------------------------------------------------------------------------
310 void DrawGL (Game & game)
321 static KeyMap g_theKeys;
323 void SetKey( int key)
325 g_theKeys[ key >> 3] |= (1 << (key & 7));
328 void ClearKey( int key)
330 g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
333 void GetKeys( unsigned char theKeys[16])
335 memcpy( theKeys, &g_theKeys, 16);
344 static void initSDLKeyTable(void) {}
346 #define MAX_SDLKEYS SDLK_LAST
347 static unsigned short KeyTable[MAX_SDLKEYS];
349 static void initSDLKeyTable(void)
351 memset(KeyTable, 0xFF, sizeof (KeyTable));
352 KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
353 KeyTable[SDLK_TAB] = MAC_TAB_KEY;
354 KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
355 KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
356 KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
357 KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
358 KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
359 KeyTable[SDLK_END] = MAC_END_KEY;
360 KeyTable[SDLK_HOME] = MAC_HOME_KEY;
361 KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
362 KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
363 KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
364 KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
365 KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
366 KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
367 KeyTable[SDLK_0] = MAC_0_KEY;
368 KeyTable[SDLK_1] = MAC_1_KEY;
369 KeyTable[SDLK_2] = MAC_2_KEY;
370 KeyTable[SDLK_3] = MAC_3_KEY;
371 KeyTable[SDLK_4] = MAC_4_KEY;
372 KeyTable[SDLK_5] = MAC_5_KEY;
373 KeyTable[SDLK_6] = MAC_6_KEY;
374 KeyTable[SDLK_7] = MAC_7_KEY;
375 KeyTable[SDLK_8] = MAC_8_KEY;
376 KeyTable[SDLK_9] = MAC_9_KEY;
377 KeyTable[SDLK_a] = MAC_A_KEY;
378 KeyTable[SDLK_b] = MAC_B_KEY;
379 KeyTable[SDLK_c] = MAC_C_KEY;
380 KeyTable[SDLK_d] = MAC_D_KEY;
381 KeyTable[SDLK_e] = MAC_E_KEY;
382 KeyTable[SDLK_f] = MAC_F_KEY;
383 KeyTable[SDLK_g] = MAC_G_KEY;
384 KeyTable[SDLK_h] = MAC_H_KEY;
385 KeyTable[SDLK_i] = MAC_I_KEY;
386 KeyTable[SDLK_j] = MAC_J_KEY;
387 KeyTable[SDLK_k] = MAC_K_KEY;
388 KeyTable[SDLK_l] = MAC_L_KEY;
389 KeyTable[SDLK_m] = MAC_M_KEY;
390 KeyTable[SDLK_n] = MAC_N_KEY;
391 KeyTable[SDLK_o] = MAC_O_KEY;
392 KeyTable[SDLK_p] = MAC_P_KEY;
393 KeyTable[SDLK_q] = MAC_Q_KEY;
394 KeyTable[SDLK_r] = MAC_R_KEY;
395 KeyTable[SDLK_s] = MAC_S_KEY;
396 KeyTable[SDLK_t] = MAC_T_KEY;
397 KeyTable[SDLK_u] = MAC_U_KEY;
398 KeyTable[SDLK_v] = MAC_V_KEY;
399 KeyTable[SDLK_w] = MAC_W_KEY;
400 KeyTable[SDLK_x] = MAC_X_KEY;
401 KeyTable[SDLK_y] = MAC_Y_KEY;
402 KeyTable[SDLK_z] = MAC_Z_KEY;
403 KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
404 KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
405 KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
406 KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
407 KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
408 KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
409 KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
410 KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
411 KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
412 KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
413 KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
414 KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
415 KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
416 KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
417 KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
418 KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
419 KeyTable[SDLK_F1] = MAC_F1_KEY;
420 KeyTable[SDLK_F2] = MAC_F2_KEY;
421 KeyTable[SDLK_F3] = MAC_F3_KEY;
422 KeyTable[SDLK_F4] = MAC_F4_KEY;
423 KeyTable[SDLK_F5] = MAC_F5_KEY;
424 KeyTable[SDLK_F6] = MAC_F6_KEY;
425 KeyTable[SDLK_F7] = MAC_F7_KEY;
426 KeyTable[SDLK_F8] = MAC_F8_KEY;
427 KeyTable[SDLK_F9] = MAC_F9_KEY;
428 KeyTable[SDLK_F10] = MAC_F10_KEY;
429 KeyTable[SDLK_F11] = MAC_F11_KEY;
430 KeyTable[SDLK_F12] = MAC_F12_KEY;
431 KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
432 KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
433 KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
434 KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
435 KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
436 KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
437 KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
438 KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
439 KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
440 KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
441 KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
444 static inline int clamp_sdl_mouse_button(Uint8 button)
446 if (button == 2) // right mouse button is button 3 in SDL.
448 else if (button == 3)
451 if ((button >= 1) && (button <= 3))
456 static void sdlEventProc(const SDL_Event &e, Game &game)
463 case SDL_MOUSEMOTION:
464 game.deltah += e.motion.xrel;
465 game.deltav += e.motion.yrel;
468 case SDL_MOUSEBUTTONDOWN:
470 val = clamp_sdl_mouse_button(e.button.button);
471 if ((val >= 0) && (val <= 2))
480 case SDL_MOUSEBUTTONUP:
482 val = clamp_sdl_mouse_button(e.button.button);
483 if ((val >= 0) && (val <= 2))
487 buttons[val] = false;
493 if (e.key.keysym.sym == SDLK_g)
495 if (e.key.keysym.mod & KMOD_CTRL)
497 SDL_GrabMode mode = SDL_GRAB_ON;
498 if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
500 mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
501 mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
503 SDL_WM_GrabInput(mode);
507 #if (defined(__APPLE__) && defined(__MACH__))
508 if (e.key.keysym.sym == SDLK_q)
510 if (e.key.keysym.mod & KMOD_META)
517 else if (e.key.keysym.sym == SDLK_RETURN)
519 if (e.key.keysym.mod & KMOD_ALT)
520 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
523 if (e.key.keysym.sym < SDLK_LAST)
525 if (KeyTable[e.key.keysym.sym] != 0xffff)
526 SetKey(KeyTable[e.key.keysym.sym]);
529 mod = SDL_GetModState();
531 SetKey(MAC_CONTROL_KEY);
533 SetKey(MAC_OPTION_KEY);
534 if (mod & KMOD_SHIFT)
535 SetKey(MAC_SHIFT_KEY);
537 SetKey(MAC_CAPS_LOCK_KEY);
542 if (e.key.keysym.sym < SDLK_LAST)
544 if (KeyTable[e.key.keysym.sym] != 0xffff)
545 ClearKey(KeyTable[e.key.keysym.sym]);
548 mod = SDL_GetModState();
549 if ((mod & KMOD_CTRL) == 0)
550 ClearKey(MAC_CONTROL_KEY);
551 if ((mod & KMOD_ALT) == 0)
552 ClearKey(MAC_OPTION_KEY);
553 if ((mod & KMOD_SHIFT) == 0)
554 ClearKey(MAC_SHIFT_KEY);
555 if ((mod & KMOD_CAPS) == 0)
556 ClearKey(MAC_CAPS_LOCK_KEY);
562 // --------------------------------------------------------------------------
564 static Point gMidPoint;
566 Boolean SetUp (Game & game)
572 randSeed = UpTime().lo;
575 ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
578 usermousesensitivity=1;
607 game.crouchkey=MAC_SHIFT_KEY;
608 game.jumpkey=MAC_SPACE_KEY;
609 game.leftkey=MAC_A_KEY;
610 game.forwardkey=MAC_W_KEY;
611 game.backkey=MAC_S_KEY;
612 game.rightkey=MAC_D_KEY;
613 game.drawkey=MAC_E_KEY;
614 game.throwkey=MAC_Q_KEY;
615 game.attackkey=MAC_MOUSEBUTTON1;
616 game.chatkey=MAC_T_KEY;
622 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
625 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
626 opstream << "Screenwidth:\n";
627 opstream << kContextWidth;
628 opstream << "\nScreenheight:\n";
629 opstream << kContextHeight;
630 opstream << "\nMouse sensitivity:\n";
631 opstream << usermousesensitivity;
632 opstream << "\nBlur(0,1):\n";
633 opstream << ismotionblur;
634 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
636 opstream << "\nFloating jump:\n";
637 opstream << floatjump;
638 opstream << "\nMouse jump:\n";
639 opstream << mousejump;
640 opstream << "\nAmbient sound:\n";
641 opstream << ambientsound;
642 opstream << "\nBlood (0,1,2):\n";
643 opstream << bloodtoggle;
644 opstream << "\nAuto slomo:\n";
645 opstream << autoslomo;
646 opstream << "\nFoliage:\n";
648 opstream << "\nMusic:\n";
649 opstream << musictoggle;
650 opstream << "\nTrilinear:\n";
651 opstream << trilinear;
652 opstream << "\nDecals(shadows,blood puddles,etc):\n";
654 opstream << "\nInvert mouse:\n";
655 opstream << invertmouse;
656 opstream << "\nGamespeed:\n";
657 opstream << gamespeed;
658 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
659 opstream << difficulty;
660 opstream << "\nDamage effects(blackout, doublevision):\n";
661 opstream << damageeffects;
662 opstream << "\nText:\n";
663 opstream << texttoggle;
664 opstream << "\nDebug:\n";
665 opstream << debugmode;
666 opstream << "\nVBL Sync:\n";
668 opstream << "\nShow Points:\n";
669 opstream << showpoints;
670 opstream << "\nAlways Blur:\n";
671 opstream << alwaysblur;
672 opstream << "\nImmediate mode (turn on on G5):\n";
673 opstream << immediate;
674 opstream << "\nVelocity blur:\n";
675 opstream << velocityblur;
676 opstream << "\nVolume:\n";
678 opstream << "\nForward key:\n";
679 opstream << KeyToChar(game.forwardkey);
680 opstream << "\nBack key:\n";
681 opstream << KeyToChar(game.backkey);
682 opstream << "\nLeft key:\n";
683 opstream << KeyToChar(game.leftkey);
684 opstream << "\nRight key:\n";
685 opstream << KeyToChar(game.rightkey);
686 opstream << "\nJump key:\n";
687 opstream << KeyToChar(game.jumpkey);
688 opstream << "\nCrouch key:\n";
689 opstream << KeyToChar(game.crouchkey);
690 opstream << "\nDraw key:\n";
691 opstream << KeyToChar(game.drawkey);
692 opstream << "\nThrow key:\n";
693 opstream << KeyToChar(game.throwkey);
694 opstream << "\nAttack key:\n";
695 opstream << KeyToChar(game.attackkey);
696 opstream << "\nChat key:\n";
697 opstream << KeyToChar(game.chatkey);
702 ipstream.ignore(256,'\n');
703 ipstream >> kContextWidth;
704 ipstream.ignore(256,'\n');
705 ipstream.ignore(256,'\n');
706 ipstream >> kContextHeight;
707 ipstream.ignore(256,'\n');
708 ipstream.ignore(256,'\n');
709 ipstream >> usermousesensitivity;
710 ipstream.ignore(256,'\n');
711 ipstream.ignore(256,'\n');
713 ismotionblur = (i != 0);
714 ipstream.ignore(256,'\n');
715 ipstream.ignore(256,'\n');
717 if(detail!=0)kBitsPerPixel=32;
718 else kBitsPerPixel=16;
719 ipstream.ignore(256,'\n');
720 ipstream.ignore(256,'\n');
722 floatjump = (i != 0);
723 ipstream.ignore(256,'\n');
724 ipstream.ignore(256,'\n');
726 mousejump = (i != 0);
727 ipstream.ignore(256,'\n');
728 ipstream.ignore(256,'\n');
730 ambientsound = (i != 0);
731 ipstream.ignore(256,'\n');
732 ipstream.ignore(256,'\n');
733 ipstream >> bloodtoggle;
734 ipstream.ignore(256,'\n');
735 ipstream.ignore(256,'\n');
737 autoslomo = (i != 0);
738 ipstream.ignore(256,'\n');
739 ipstream.ignore(256,'\n');
742 ipstream.ignore(256,'\n');
743 ipstream.ignore(256,'\n');
745 musictoggle = (i != 0);
746 ipstream.ignore(256,'\n');
747 ipstream.ignore(256,'\n');
749 trilinear = (i != 0);
750 ipstream.ignore(256,'\n');
751 ipstream.ignore(256,'\n');
754 ipstream.ignore(256,'\n');
755 ipstream.ignore(256,'\n');
757 invertmouse = (i != 0);
758 ipstream.ignore(256,'\n');
759 ipstream.ignore(256,'\n');
760 ipstream >> gamespeed;
761 oldgamespeed=gamespeed;
766 ipstream.ignore(256,'\n');
767 ipstream.ignore(256,'\n');
768 ipstream >> difficulty;
769 ipstream.ignore(256,'\n');
770 ipstream.ignore(256,'\n');
772 damageeffects = (i != 0);
773 ipstream.ignore(256,'\n');
774 ipstream.ignore(256,'\n');
776 texttoggle = (i != 0);
777 ipstream.ignore(256,'\n');
778 ipstream.ignore(256,'\n');
780 debugmode = (i != 0);
781 ipstream.ignore(256,'\n');
782 ipstream.ignore(256,'\n');
785 ipstream.ignore(256,'\n');
786 ipstream.ignore(256,'\n');
788 showpoints = (i != 0);
789 ipstream.ignore(256,'\n');
790 ipstream.ignore(256,'\n');
792 alwaysblur = (i != 0);
793 ipstream.ignore(256,'\n');
794 ipstream.ignore(256,'\n');
796 immediate = (i != 0);
797 ipstream.ignore(256,'\n');
798 ipstream.ignore(256,'\n');
800 velocityblur = (i != 0);
801 ipstream.ignore(256,'\n');
802 ipstream.ignore(256,'\n');
804 ipstream.ignore(256,'\n');
805 ipstream.ignore(256,'\n');
807 game.forwardkey=CharToKey(string);
808 ipstream.ignore(256,'\n');
809 ipstream.ignore(256,'\n');
811 game.backkey=CharToKey(string);
812 ipstream.ignore(256,'\n');
813 ipstream.ignore(256,'\n');
815 game.leftkey=CharToKey(string);
816 ipstream.ignore(256,'\n');
817 ipstream.ignore(256,'\n');
819 game.rightkey=CharToKey(string);
820 ipstream.ignore(256,'\n');
821 ipstream.ignore(256,'\n');
823 game.jumpkey=CharToKey(string);
824 ipstream.ignore(256,'\n');
825 ipstream.ignore(256,'\n');
827 game.crouchkey=CharToKey(string);
828 ipstream.ignore(256,'\n');
829 ipstream.ignore(256,'\n');
831 game.drawkey=CharToKey(string);
832 ipstream.ignore(256,'\n');
833 ipstream.ignore(256,'\n');
835 game.throwkey=CharToKey(string);
836 ipstream.ignore(256,'\n');
837 ipstream.ignore(256,'\n');
839 game.attackkey=CharToKey(string);
840 ipstream.ignore(256,'\n');
841 ipstream.ignore(256,'\n');
843 game.chatkey=CharToKey(string);
846 if(detail>2)detail=2;
847 if(detail<0)detail=0;
848 if(screenwidth>3000)screenwidth=640;
849 if(screenwidth<0)screenwidth=640;
850 if(screenheight>3000)screenheight=480;
851 if(screenheight<0)screenheight=480;
853 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
858 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
860 SetupDSpFullScreen();
863 if (!SDL_WasInit(SDL_INIT_VIDEO))
865 if (SDL_Init(SDL_INIT_VIDEO) == -1)
867 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
871 if (SDL_GL_LoadLibrary(NULL) == -1)
873 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
879 Uint32 sdlflags = SDL_OPENGL;
880 if (!cmdline("windowed"))
881 sdlflags |= SDL_FULLSCREEN;
883 SDL_WM_SetCaption("Lugaru", "Lugaru");
887 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
889 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
890 fprintf(stderr, "forcing 640x480...\n");
892 kContextHeight = 480;
893 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
895 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
896 fprintf(stderr, "forcing 640x480 windowed mode...\n");
897 sdlflags &= ~SDL_FULLSCREEN;
898 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
900 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
906 if (!lookup_all_glsyms())
912 if (!cmdline("nomousegrab"))
913 SDL_WM_GrabInput(SDL_GRAB_ON);
915 #elif (defined WIN32)
916 //------------------------------------------------------------------
919 RECT r = {0, 0, kContextWidth-1, kContextHeight-1};
920 DWORD dwStyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE;
921 DWORD dwExStyle = WS_EX_APPWINDOW;
930 dwStyle |= WS_OVERLAPPEDWINDOW;
931 dwExStyle |= WS_EX_WINDOWEDGE;
934 AdjustWindowRectEx(&r, dwStyle, FALSE, dwExStyle);
938 x = (GetSystemMetrics(SM_CXSCREEN) >> 1) - ((r.right - r.left + 1) >> 1);
939 y = (GetSystemMetrics(SM_CYSCREEN) >> 1) - ((r.bottom - r.top + 1) >> 1);
942 g_windowHandle=CreateWindowEx(
944 g_wndClassName, "Lugaru", dwStyle,
946 // kContextWidth, kContextHeight,
947 r.right - r.left + 1, r.bottom - r.top + 1,
948 NULL,NULL,g_appInstance,NULL );
951 ReportError("Could not create window");
955 //------------------------------------------------------------------
958 static PIXELFORMATDESCRIPTOR pfd =
960 sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
962 PFD_DRAW_TO_WINDOW | // Format Must Support Window
963 PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
964 PFD_DOUBLEBUFFER, // Must Support Double Buffering
965 PFD_TYPE_RGBA, // Request An RGBA Format
966 kBitsPerPixel, // Select Our Color Depth
967 0, 0, 0, 0, 0, 0, // Color Bits Ignored
968 0, // No Alpha Buffer
969 0, // Shift Bit Ignored
970 0, // No Accumulation Buffer
971 0, 0, 0, 0, // Accumulation Bits Ignored
972 16, // 16Bit Z-Buffer (Depth Buffer)
973 0, // No Stencil Buffer
974 0, // No Auxiliary Buffer
975 PFD_MAIN_PLANE, // Main Drawing Layer
977 0, 0, 0 // Layer Masks Ignored
980 if (!(hDC = GetDC( g_windowHandle)))
981 ReportError( "Could not get device context");
984 if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))
986 ReportError( "Could not find appropriate pixel format");
990 if (!DescribePixelFormat(hDC, PixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd))
992 ReportError( "Could not retrieve pixel format");
996 if (!SetPixelFormat( hDC, PixelFormat, &pfd))
998 ReportError( "Could not set pixel format");
1002 if (!(hRC = wglCreateContext(hDC)))
1004 ReportError( "Could not create rendering context");
1008 if (!wglMakeCurrent(hDC, hRC))
1010 ReportError( "Could not activate rendering context");
1016 // Place the window above all topmost windows
1017 SetWindowPos( g_windowHandle, HWND_TOPMOST, 0,0,0,0,
1018 SWP_NOMOVE | SWP_NOSIZE );
1021 SetForegroundWindow(g_windowHandle);
1022 SetFocus(g_windowHandle);
1025 glClear( GL_COLOR_BUFFER_BIT );
1029 glDisable( GL_ALPHA_TEST);
1030 glDisable( GL_BLEND);
1031 glDisable( GL_DEPTH_TEST);
1032 // glDisable( GL_DITHER);
1034 glDisable( GL_LIGHTING);
1035 glDisable( GL_LOGIC_OP);
1036 glDisable( GL_STENCIL_TEST);
1037 glDisable( GL_TEXTURE_1D);
1038 glDisable( GL_TEXTURE_2D);
1039 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
1040 glPixelTransferi( GL_RED_SCALE, 1);
1041 glPixelTransferi( GL_RED_BIAS, 0);
1042 glPixelTransferi( GL_GREEN_SCALE, 1);
1043 glPixelTransferi( GL_GREEN_BIAS, 0);
1044 glPixelTransferi( GL_BLUE_SCALE, 1);
1045 glPixelTransferi( GL_BLUE_BIAS, 0);
1046 glPixelTransferi( GL_ALPHA_SCALE, 1);
1047 glPixelTransferi( GL_ALPHA_BIAS, 0);
1049 // set initial rendering states
1050 glShadeModel( GL_SMOOTH);
1051 glClearDepth( 1.0f);
1052 glDepthFunc( GL_LEQUAL);
1053 glDepthMask( GL_TRUE);
1054 // glDepthRange( FRONT_CLIP, BACK_CLIP);
1055 glEnable( GL_DEPTH_TEST);
1056 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
1057 glCullFace( GL_FRONT);
1058 glEnable( GL_CULL_FACE);
1059 glEnable( GL_LIGHTING);
1060 // glEnable( GL_LIGHT_MODEL_AMBIENT);
1061 glEnable( GL_DITHER);
1062 glEnable( GL_COLOR_MATERIAL);
1063 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1064 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1065 glAlphaFunc( GL_GREATER, 0.5f);
1068 if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION ||
1069 iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION ||
1070 ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION)
1072 ReportError("DevIL version is different...exiting!\n");
1080 ilutRenderer(ILUT_OPENGL);
1082 ilEnable(IL_ORIGIN_SET);
1083 ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
1086 GLint width = kContextWidth;
1087 GLint height = kContextHeight;
1088 gMidPoint.h = width / 2;
1089 gMidPoint.v = height / 2;
1091 screenheight=height;
1093 game.newdetail=detail;
1094 game.newscreenwidth=screenwidth;
1095 game.newscreenheight=screenheight;
1103 static void DoMouse(Game & game)
1106 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1108 game.deltah *= usermousesensitivity;
1109 game.deltav *= usermousesensitivity;
1110 game.mousecoordh += game.deltah;
1111 game.mousecoordv += game.deltav;
1112 if (game.mousecoordh < 0)
1113 game.mousecoordh = 0;
1114 else if (game.mousecoordh >= kContextWidth)
1115 game.mousecoordh = kContextWidth - 1;
1116 if (game.mousecoordv < 0)
1117 game.mousecoordv = 0;
1118 else if (game.mousecoordv >= kContextHeight)
1119 game.mousecoordv = kContextHeight - 1;
1122 static Point lastMouse = {-1,-1};
1127 ScreenToClient(g_windowHandle, &pos);
1128 globalMouse.h = pos.x;
1129 globalMouse.v = pos.y;
1131 if (lastMouse.h == globalMouse.h && lastMouse.v == globalMouse.v)
1138 static Point virtualMouse = {0,0};
1139 delta = globalMouse;
1141 delta.h -= lastMouse.h;
1142 delta.v -= lastMouse.v;
1143 lastMouse.h = pos.x;
1144 lastMouse.v = pos.y;
1146 if(mainmenu||(abs(delta.h)<10*realmultiplier*1000&&abs(delta.v)<10*realmultiplier*1000)){
1147 game.deltah=delta.h*usermousesensitivity;
1148 game.deltav=delta.v*usermousesensitivity;
1149 game.mousecoordh=globalMouse.h;
1150 game.mousecoordv=globalMouse.v;
1155 if(lastMouse.h>gMidPoint.h+100||lastMouse.h<gMidPoint.h-100||lastMouse.v>gMidPoint.v+100||lastMouse.v<gMidPoint.v-100){
1156 pos.x = gMidPoint.h;
1157 pos.y = gMidPoint.v;
1158 ClientToScreen(g_windowHandle, &pos);
1159 //SetCursorPos( gMidPoint.h,gMidPoint.v);
1160 SetCursorPos(pos.x, pos.y);
1161 lastMouse = gMidPoint;
1170 // --------------------------------------------------------------------------
1172 void DoKey (SInt8 theKey, SInt8 theCode)
1177 // --------------------------------------------------------------------------
1181 void DoFrameRate (int update)
1183 static long frames = 0;
1185 static AbsoluteTime time = {0,0};
1186 static AbsoluteTime frametime = {0,0};
1187 AbsoluteTime currTime = UpTime ();
1188 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1190 if (0 > deltaTime) // if negative microseconds
1191 deltaTime /= -1000000.0;
1192 else // else milliseconds
1193 deltaTime /= 1000.0;
1195 multiplier=deltaTime;
1196 if(multiplier<.001)multiplier=.001;
1197 if(multiplier>10)multiplier=10;
1198 if(update)frametime = currTime; // reset for next time interval
1200 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1202 if (0 > deltaTime) // if negative microseconds
1203 deltaTime /= -1000000.0;
1204 else // else milliseconds
1205 deltaTime /= 1000.0;
1207 if (0.001 <= deltaTime) // has update interval passed
1210 time = currTime; // reset for next time interval
1217 void DoUpdate (Game & game)
1219 static float sps=200;
1221 static float oldmult;
1224 if(multiplier>.6)multiplier=.6;
1226 game.fps=1/multiplier;
1228 count = multiplier*sps;
1230 //if(count>10)count=10;
1232 realmultiplier=multiplier;
1233 multiplier*=gamespeed;
1234 if(difficulty==1)multiplier*=.9;
1235 if(difficulty==0)multiplier*=.8;
1237 if(game.loading==4)multiplier*=.00001;
1239 if(slomo&&!mainmenu)multiplier*=slomospeed;
1240 //if(freeze)multiplier*=0.00001;
1242 multiplier/=(float)count;
1248 for(int i=0;i<count;i++)
1254 game.TickOnceAfter();
1255 /* - Debug code to test how many channels were active on average per frame
1256 static long frames = 0;
1258 static AbsoluteTime start = {0,0};
1259 AbsoluteTime currTime = UpTime ();
1260 static int num_channels = 0;
1262 num_channels += FSOUND_GetChannelsPlaying();
1263 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1265 if (0 > deltaTime) // if negative microseconds
1266 deltaTime /= -1000000.0;
1267 else // else milliseconds
1268 deltaTime /= 1000.0;
1275 float avg_channels = (float)num_channels / (float)frames;
1277 ofstream opstream("log.txt",ios::app);
1278 opstream << "Average frame count: ";
1280 opstream << " frames - ";
1281 opstream << avg_channels;
1282 opstream << " per frame.\n";
1292 // --------------------------------------------------------------------------
1307 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1308 #include "glstubs.h"
1310 // cheat here...static destructors are calling glDeleteTexture() after
1311 // the context is destroyed and libGL unloaded by SDL_Quit().
1312 pglDeleteTextures = glDeleteTextures_doNothing;
1314 #elif (defined WIN32)
1317 wglMakeCurrent( NULL, NULL);
1318 wglDeleteContext( hRC);
1324 ReleaseDC( g_windowHandle, hDC);
1330 ShowWindow( g_windowHandle, SW_HIDE );
1331 DestroyWindow( g_windowHandle);
1332 g_windowHandle = NULL;
1340 // --------------------------------------------------------------------------
1342 static bool g_focused = true;
1345 static bool IsFocused()
1351 if (GetActiveWindow() != g_windowHandle)
1354 if (IsIconic( g_windowHandle))
1362 static void launch_web_browser(const char *url)
1365 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1367 #elif (defined(__APPLE__) && defined(__MACH__))
1368 const char *fmt = "open '%s'";
1369 const size_t len = strlen(fmt) + strlen(url) + 16;
1370 char *buf = new char[len];
1371 snprintf(buf, len, fmt, url);
1375 #elif PLATFORM_LINUX
1376 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1377 const size_t len = strlen(fmt) + strlen(url) + 16;
1378 char *buf = new char[len];
1379 snprintf(buf, len, fmt, url);
1387 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1388 static char *findBinaryInPath(const char *bin, char *envr)
1390 size_t alloc_size = 0;
1398 ptr = strchr(start, ':'); /* find next $PATH separator. */
1402 size = strlen(start) + strlen(bin) + 2;
1403 if (size > alloc_size)
1405 char *x = (char *) realloc(exe, size);
1417 /* build full binary path... */
1419 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1423 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
1425 strcpy(exe, start); /* i'm lazy. piss off. */
1429 start = ptr + 1; /* start points to beginning of next element. */
1430 } while (ptr != NULL);
1435 return(NULL); /* doesn't exist in path. */
1436 } /* findBinaryInPath */
1439 char *calcBaseDir(const char *argv0)
1441 /* If there isn't a path on argv0, then look through the $PATH for it. */
1445 char *ptr = strrchr(argv0, '/');
1446 if (strchr(argv0, '/'))
1448 retval = strdup(argv0);
1450 *(strrchr(retval, '/')) = '\0';
1454 envr = getenv("PATH");
1455 if (!envr) return NULL;
1456 envr = strdup(envr);
1457 if (!envr) return NULL;
1458 retval = findBinaryInPath(argv0, envr);
1463 static inline void chdirToAppPath(const char *argv0)
1465 char *dir = calcBaseDir(argv0);
1468 #if (defined(__APPLE__) && defined(__MACH__))
1469 // Chop off /Contents/MacOS if it's at the end of the string, so we
1470 // land in the base of the app bundle.
1471 const size_t len = strlen(dir);
1472 const char *bundledirs = "/Contents/MacOS";
1473 const size_t bundledirslen = strlen(bundledirs);
1474 if (len > bundledirslen)
1476 char *ptr = (dir + len) - bundledirslen;
1477 if (strcasecmp(ptr, bundledirs) == 0)
1488 int main(int argc, char **argv)
1493 chdirToAppPath(argv[0]);
1498 #ifndef WIN32 // this is in WinMain, too.
1500 memset( &g_theKeys, 0, sizeof( KeyMap));
1507 bool regnow = false;
1512 //ofstream os("error.txt");
1514 //ofstream os("log.txt");
1520 while (!gDone&&!game.quit&&(!game.tryquit||!game.registered))
1526 // check windows messages
1532 while( SDL_PollEvent( &e ) )
1534 if( e.type == SDL_QUIT )
1539 sdlEventProc(e, game);
1542 #elif (defined WIN32)
1545 while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE | PM_NOYIELD ) )
1547 if( msg.message == WM_QUIT )
1554 TranslateMessage( &msg );
1555 DispatchMessage( &msg );
1567 // allow game chance to pause
1568 gameFocused = false;
1572 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1576 //if (GetMessage( &msg, g_windowHandle, 0, 0 ))
1577 /*if (GetMessage( &msg, NULL, 0, 0 ))
1579 TranslateMessage(&msg);
1580 DispatchMessage(&msg);
1582 if ( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
1586 // handle the error and possibly exit
1591 TranslateMessage(&msg);
1592 DispatchMessage(&msg);
1596 STUBBED("give up CPU but sniff the event queue");
1601 regnow = game.registernow;
1606 // if(game.registernow){
1609 #if (defined(__APPLE__) && defined(__MACH__))
1610 launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1611 #elif PLATFORM_LINUX
1612 launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1614 launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1618 #if PLATFORM_LINUX // (this may not be necessary any more.)
1619 _exit(0); // !!! FIXME: hack...crashes on exit!
1623 catch (const std::exception& error)
1627 std::string e = "Caught exception: ";
1630 LOG(e, Logger::LOG_ERR);
1632 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1642 // --------------------------------------------------------------------------
1645 #define MAX_WINKEYS 256
1646 static unsigned short KeyTable[MAX_WINKEYS]=
1649 MAC_MOUSEBUTTON1, // VK_LBUTTON (1)
1650 MAC_MOUSEBUTTON2, // VK_RBUTTON (2)
1651 0xffff, // VK_CANCEL (3)
1652 0xffff, // VK_MBUTTON (4)
1656 MAC_DELETE_KEY, // VK_BACK (8)
1657 MAC_TAB_KEY, // VK_TAB (9)
1660 0xffff, // VK_CLEAR (12)
1661 MAC_RETURN_KEY, // VK_RETURN (13)
1664 MAC_SHIFT_KEY, // VK_SHIFT (16)
1665 MAC_CONTROL_KEY, // VK_CONTROL (17)
1666 MAC_OPTION_KEY, // VK_MENU (18)
1667 0xffff, // VK_PAUSE (19)
1668 MAC_CAPS_LOCK_KEY, // #define VK_CAPITAL (20)
1675 MAC_ESCAPE_KEY, // VK_ESCAPE (27)
1680 MAC_SPACE_KEY, // VK_SPACE (32)
1681 MAC_PAGE_UP_KEY, // VK_PRIOR (33)
1682 MAC_PAGE_DOWN_KEY, // VK_NEXT (34)
1683 MAC_END_KEY, // VK_END (35)
1684 MAC_HOME_KEY, // VK_HOME (36)
1685 MAC_ARROW_LEFT_KEY, // VK_LEFT (37)
1686 MAC_ARROW_UP_KEY, // VK_UP (38)
1687 MAC_ARROW_RIGHT_KEY, // VK_RIGHT (39)
1688 MAC_ARROW_DOWN_KEY, // VK_DOWN (40)
1689 0xffff, // VK_SELECT (41)
1690 0xffff, // VK_PRINT (42)
1691 0xffff, // VK_EXECUTE (43)
1692 0xffff, // VK_SNAPSHOT (44)
1693 MAC_INSERT_KEY, // VK_INSERT (45)
1694 MAC_DEL_KEY, // VK_DELETE (46)
1695 0xffff, // VK_HELP (47)
1696 MAC_0_KEY, // VK_0 (48)
1697 MAC_1_KEY, // VK_1 (49)
1698 MAC_2_KEY, // VK_2 (50)
1699 MAC_3_KEY, // VK_3 (51)
1700 MAC_4_KEY, // VK_4 (52)
1701 MAC_5_KEY, // VK_5 (53)
1702 MAC_6_KEY, // VK_6 (54)
1703 MAC_7_KEY, // VK_7 (55)
1704 MAC_8_KEY, // VK_8 (56)
1705 MAC_9_KEY, // VK_9 (57)
1713 MAC_A_KEY, // VK_A (65)
1714 MAC_B_KEY, // VK_B (66)
1715 MAC_C_KEY, // VK_C (67)
1716 MAC_D_KEY, // VK_D (68)
1717 MAC_E_KEY, // VK_E (69)
1718 MAC_F_KEY, // VK_F (70)
1719 MAC_G_KEY, // VK_G (71)
1720 MAC_H_KEY, // VK_H (72)
1721 MAC_I_KEY, // VK_I (73)
1722 MAC_J_KEY, // VK_J (74)
1723 MAC_K_KEY, // VK_K (75)
1724 MAC_L_KEY, // VK_L (76)
1725 MAC_M_KEY, // VK_M (77)
1726 MAC_N_KEY, // VK_N (78)
1727 MAC_O_KEY, // VK_O (79)
1728 MAC_P_KEY, // VK_P (80)
1729 MAC_Q_KEY, // VK_Q (81)
1730 MAC_R_KEY, // VK_R (82)
1731 MAC_S_KEY, // VK_S (83)
1732 MAC_T_KEY, // VK_T (84)
1733 MAC_U_KEY, // VK_U (85)
1734 MAC_V_KEY, // VK_V (86)
1735 MAC_W_KEY, // VK_W (87)
1736 MAC_X_KEY, // VK_X (88)
1737 MAC_Y_KEY, // VK_Y (89)
1738 MAC_Z_KEY, // VK_Z (90)
1744 MAC_NUMPAD_0_KEY, // VK_NUMPAD0 (96)
1745 MAC_NUMPAD_1_KEY, // VK_NUMPAD1 (97)
1746 MAC_NUMPAD_2_KEY, // VK_NUMPAD2 (98)
1747 MAC_NUMPAD_3_KEY, // VK_NUMPAD3 (99)
1748 MAC_NUMPAD_4_KEY, // VK_NUMPAD4 (100)
1749 MAC_NUMPAD_5_KEY, // VK_NUMPAD5 (101)
1750 MAC_NUMPAD_6_KEY, // VK_NUMPAD6 (102)
1751 MAC_NUMPAD_7_KEY, // VK_NUMPAD7 (103)
1752 MAC_NUMPAD_8_KEY, // VK_NUMPAD8 (104)
1753 MAC_NUMPAD_9_KEY, // VK_NUMPAD9 (105)
1754 MAC_NUMPAD_ASTERISK_KEY, // VK_MULTIPLY (106)
1755 MAC_NUMPAD_PLUS_KEY, // VK_ADD (107)
1756 MAC_NUMPAD_ENTER_KEY, // VK_SEPARATOR (108)
1757 MAC_NUMPAD_MINUS_KEY, // VK_SUBTRACT (109)
1758 MAC_NUMPAD_PERIOD_KEY, // VK_DECIMAL (110)
1759 MAC_NUMPAD_SLASH_KEY, // VK_DIVIDE (111)
1760 MAC_F1_KEY, // VK_F1 (112)
1761 MAC_F2_KEY, // VK_F2 (113)
1762 MAC_F3_KEY, // VK_F3 (114)
1763 MAC_F4_KEY, // VK_F4 (115)
1764 MAC_F5_KEY, // VK_F5 (116)
1765 MAC_F6_KEY, // VK_F6 (117)
1766 MAC_F7_KEY, // VK_F7 (118)
1767 MAC_F8_KEY, // VK_F8 (119)
1768 MAC_F9_KEY, // VK_F9 (120)
1769 MAC_F10_KEY, // VK_F10 (121)
1770 MAC_F11_KEY, // VK_F11 (122)
1771 MAC_F12_KEY, // VK_F12 (123)
1792 0xffff, // VK_NUMLOCK (144)
1793 0xffff, // VK_SCROLL (145)
1808 MAC_SHIFT_KEY, // VK_LSHIFT (160)
1809 MAC_SHIFT_KEY, // VK_RSHIFT (161)
1810 MAC_CONTROL_KEY, // VK_LCONTROL (162)
1811 MAC_CONTROL_KEY, // VK_RCONTROL (163)
1812 MAC_OPTION_KEY, // VK_LMENU (164)
1813 MAC_OPTION_KEY, // VK_RMENU (165)
1834 MAC_SEMICOLON_KEY, // (186)
1835 MAC_PLUS_KEY, // (187)
1836 MAC_COMMA_KEY, // (188)
1837 MAC_MINUS_KEY, // (189)
1838 MAC_PERIOD_KEY, // (190)
1839 MAC_SLASH_KEY, // (191)
1840 MAC_TILDE_KEY, // (192)
1867 MAC_LEFTBRACKET_KEY, // (219)
1868 MAC_BACKSLASH_KEY, // (220)
1869 MAC_RIGHTBRACKET_KEY, // (221)
1870 MAC_APOSTROPHE_KEY, // (222)
1906 void ClipMouseToWindow(HWND window)
1910 GetClientRect(window, &wRect);
1912 ClientToScreen(window, (LPPOINT)&wRect.left);
1913 ClientToScreen(window, (LPPOINT)&wRect.right);
1920 LRESULT FAR PASCAL AppWndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
1922 /* this is where we receive all messages concerning this window
1923 * we can either process a message or pass it on to the default
1924 * message handler of windows */
1926 static PAINTSTRUCT ps;
1930 case WM_ACTIVATE: // Watch For Window Activate Message
1932 // Check Minimization State
1933 BOOL iconified = HIWORD(wParam) ? TRUE : FALSE;
1935 if (LOWORD(wParam) == WA_INACTIVE)
1944 CloseWindow( hWnd );
1946 // The window is now iconified
1947 iconified = GL_TRUE;
1953 g_focused=false; // Program Is Active
1957 SetupDSpFullScreen();
1964 // The window is now iconified
1965 iconified = GL_FALSE;
1968 ShowWindow( hWnd, SW_SHOW );
1969 SetForegroundWindow( hWnd );
1973 ClipMouseToWindow(hWnd);
1974 g_focused=true; // Program Is No Longer Active
1977 return 0; // Return To The Message Loop
1983 // check for Alt-F4 (exit hotkey)
1984 if (wParam == VK_F4)
1986 if (GetKeyState( VK_MENU) & 0x8080)
1992 if (wParam < MAX_WINKEYS)
1994 if (KeyTable[wParam] != 0xffff)
1995 SetKey( KeyTable[wParam]);
2003 if (wParam < MAX_WINKEYS)
2004 if (KeyTable[wParam] != 0xffff)
2005 ClearKey( KeyTable[wParam]);
2012 case WM_SYSDEADCHAR:
2015 case WM_NCLBUTTONDOWN:
2016 case WM_LBUTTONDOWN:
2023 case WM_NCRBUTTONDOWN:
2024 case WM_RBUTTONDOWN:
2030 case WM_NCMBUTTONDOWN:
2031 case WM_MBUTTONDOWN:
2037 case WM_NCLBUTTONUP:
2041 buttons[ 0] = false;
2045 case WM_NCRBUTTONUP:
2048 buttons[ 1] = false;
2052 case WM_NCMBUTTONUP:
2055 buttons[ 2] = false;
2059 case WM_NCLBUTTONDBLCLK:
2060 case WM_NCRBUTTONDBLCLK:
2061 case WM_NCMBUTTONDBLCLK:
2062 case WM_LBUTTONDBLCLK:
2064 case WM_RBUTTONDBLCLK:
2065 case WM_MBUTTONDBLCLK:
2068 case WM_NCMOUSEMOVE:
2070 /* ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseX = (signed short)(lParam & 0xffff);
2071 ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseY = (signed short)(lParam >> 16);
2072 if (g_lastWindow->m_mouseCallbacksEnabled) g_lastWindow->MouseMoveCallback();
2073 */// goto winmessage;
2076 case WM_SYSCOMMAND: // Intercept System Commands
2078 switch (wParam) // Check System Calls
2080 case SC_SCREENSAVE: // Screensaver Trying To Start?
2081 case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
2082 return 0; // Prevent From Happening
2084 // User trying to access application menu using ALT?
2093 // ReleaseCapture();
2094 // ClipMouseToWindow(hWnd);
2111 PostQuitMessage(0); /* Terminate Application */
2119 // BeginPaint( g_windowHandle,&ps);
2120 // EndPaint( g_windowHandle,&ps);
2127 /* We processed the message and there
2128 * is no processing by Windows necessary */
2130 /* We didn't process the message so let Windows do it */
2131 return DefWindowProc(hWnd,msg,wParam,lParam);
2135 static BOOL RegisterWindowClasses(HINSTANCE hFirstInstance)
2138 memset( &wc, 0, sizeof( wc));
2140 /* Register the window class. */
2141 wc.cbSize = sizeof(wc);
2143 wc.style = (CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_OWNDC); /* Combination of Class Styles */
2144 wc.lpfnWndProc = AppWndProc; /* Adress of Window Procedure */
2145 wc.cbClsExtra = 0; /* Extra Bytes allocated for this Class */
2146 wc.cbWndExtra = 0; /* Extra Bytes allocated for each Window */
2147 wc.hInstance = hFirstInstance; /* Handle of program instance */
2148 wc.hIcon = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2149 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2150 wc.hbrBackground = NULL;
2151 wc.lpszMenuName = NULL;
2152 wc.lpszClassName = g_wndClassName; /* Name of the Window Class */
2153 wc.hIconSm = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2155 if (!RegisterClassEx(&wc)) return FALSE; /* Register Class failed */
2161 int resolutionID(int width, int height)
2165 if(width==640 && height==480)whichres=0;
2166 if(width==800 && height==600)whichres=1;
2167 if(width==1024 && height==768)whichres=2;
2168 if(width==1280 && height==1024)whichres=3;
2169 if(width==1600 && height==1200)whichres=4;
2170 if(width==840 && height==524)whichres=5;
2171 if(width==1024 && height==640)whichres=6;
2172 if(width==1344 && height==840)whichres=7;
2173 if(width==1920 && height==1200)whichres=8;
2178 int closestResolution(int width, int height)
2182 if(width>=640 && height>=480)whichres=0;
2183 if(width>=800 && height>=600)whichres=1;
2184 if(width>=1024 && height>=768)whichres=2;
2185 if(width>=1280 && height>=1024)whichres=3;
2186 if(width>=1600 && height>=1200)whichres=4;
2187 if(width==840 && height==524)whichres=5;
2188 if(width==1024 && height==640)whichres=6;
2189 if(width==1344 && height==840)whichres=7;
2190 if(width>=1920 && height>=1200)whichres=8;
2195 bool selectDetail(int & width, int & height, int & bpp, int & detail)
2198 int whichres = closestResolution(width, height);
2202 if(whichres<=0 || whichres>8){
2240 // currently with SDL, we just use whatever the native bitdepth
2241 // of the display is and don't care.
2246 if ((detail != 0) && (resolutionDepths[whichres][1] != 0))
2250 else if ((detail == 0) && (resolutionDepths[whichres][0] != 0))
2254 else if ((detail != 0) && (resolutionDepths[whichres][0] != 0))
2270 bpp = resolutionDepths[whichres][(detail != 0)];
2276 int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
2279 LPWSTR * cl = CommandLineToArgvW(GetCommandLineW(), &argc);
2282 if (0 == _wcsicmp(cl[1], L"-windowed"))
2290 memset( &g_theKeys, 0, sizeof( KeyMap));
2294 memset(&mode, 0, sizeof(mode));
2295 mode.dmSize = sizeof(mode);
2296 while (EnumDisplaySettings(NULL, i++, &mode))
2298 if (mode.dmBitsPerPel < 16)
2303 int res = resolutionID(mode.dmPelsWidth, mode.dmPelsHeight);
2305 if (res > -1 && res < 8)
2307 if (DISP_CHANGE_SUCCESSFUL != ChangeDisplaySettings(&mode, CDS_TEST))
2312 switch(mode.dmBitsPerPel)
2316 resolutionDepths[res][1] = mode.dmBitsPerPel;
2319 resolutionDepths[res][0] = mode.dmBitsPerPel;
2325 /* if there is no Instance of our program in memory then register the window class */
2326 if (hPrevInstance == NULL && !RegisterWindowClasses(hInstance))
2327 return FALSE; /* registration failed! */
2329 g_appInstance=hInstance;
2333 UnregisterClass( g_wndClassName, hInstance);
2340 extern int channels[100];
2341 extern FSOUND_SAMPLE * samp[100];
2342 extern FSOUND_STREAM * strm[20];
2344 extern "C" void PlaySoundEx(int chan, FSOUND_SAMPLE *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2346 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2347 if (currSample && currSample == samp[chan])
2349 if (FSOUND_GetPaused(channels[chan]))
2351 FSOUND_StopSound(channels[chan]);
2352 channels[chan] = FSOUND_FREE;
2354 else if (FSOUND_IsPlaying(channels[chan]))
2356 int loop_mode = FSOUND_GetLoopMode(channels[chan]);
2357 if (loop_mode & FSOUND_LOOP_OFF)
2359 channels[chan] = FSOUND_FREE;
2365 channels[chan] = FSOUND_FREE;
2368 channels[chan] = FSOUND_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
2369 if (channels[chan] < 0)
2371 channels[chan] = FSOUND_PlaySoundEx(FSOUND_FREE, sptr, dsp, startpaused);
2375 extern "C" void PlayStreamEx(int chan, FSOUND_STREAM *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2377 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2378 if (currSample && currSample == FSOUND_Stream_GetSample(sptr))
2380 FSOUND_StopSound(channels[chan]);
2381 FSOUND_Stream_Stop(sptr);
2385 FSOUND_Stream_Stop(sptr);
2386 channels[chan] = FSOUND_FREE;
2389 channels[chan] = FSOUND_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
2390 if (channels[chan] < 0)
2392 channels[chan] = FSOUND_Stream_PlayEx(FSOUND_FREE, sptr, dsp, startpaused);
2396 bool LoadImage(const char * fname, TGAImageRec & tex)
2400 if ( tex.data == NULL )
2406 ILstring f = strdup(ConvertFileName(fname));
2413 ilGenImages(1, &iid);
2418 tex.sizeX = ilGetInteger(IL_IMAGE_WIDTH);
2419 tex.sizeY = ilGetInteger(IL_IMAGE_HEIGHT);
2420 tex.bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
2421 ILuint Bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL),
2422 imageSize = tex.sizeX * tex.sizeY * Bpp;
2423 ILubyte *Data = ilGetData();
2424 memcpy(tex.data, Data, imageSize);
2426 // Truvision Targa files are stored as BGR colors
2427 // We want RGB so Blue and Red bytes are switched
2428 if (IL_TGA == ilGetInteger(IL_IMAGE_FORMAT))
2430 // Loop Through The Image Data
2431 for (GLuint i = 0; i < int(imageSize); i += Bpp)
2433 // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
2434 GLbyte temp; // Temporary Variable
2435 temp = tex.data[i]; // Temporarily Store The Value At Image Data 'i'
2436 tex.data[i] = tex.data[i + 2]; // Set The 1st Byte To The Value Of The 3rd Byte
2437 tex.data[i + 2] = temp; // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
2445 ilDeleteImages(1, &iid);
2449 GLuint texid = ilutGLLoadImage(f);
2454 ilutGLBuildMipmaps()
2463 res = load_image(fname, tex);
2464 //if (!res) printf("failed to load %s\n", fname);
2470 void ScreenShot(const char * fname)
2473 ILstring f = strdup(fname);
2480 ilGenImages(1, &iid);
2486 ilDeleteImages(1, &iid);
2496 static bool load_image(const char *file_name, TGAImageRec &tex)
2498 char *ptr = strrchr(file_name, '.');
2501 if (stricmp(ptr+1, "png") == 0)
2502 return load_png(file_name, tex);
2503 else if (stricmp(ptr+1, "jpg") == 0)
2504 return load_jpg(file_name, tex);
2507 STUBBED("Unsupported image type");
2512 struct my_error_mgr {
2513 struct jpeg_error_mgr pub; /* "public" fields */
2514 jmp_buf setjmp_buffer; /* for return to caller */
2516 typedef struct my_error_mgr * my_error_ptr;
2519 static void my_error_exit(j_common_ptr cinfo)
2521 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
2522 longjmp(err->setjmp_buffer, 1);
2525 /* stolen from public domain example.c code in libjpg distribution. */
2526 static bool load_jpg(const char *file_name, TGAImageRec &tex)
2528 struct jpeg_decompress_struct cinfo;
2529 struct my_error_mgr jerr;
2530 JSAMPROW buffer[1]; /* Output row buffer */
2531 int row_stride; /* physical row width in output buffer */
2532 FILE *infile = fopen(file_name, "rb");
2537 cinfo.err = jpeg_std_error(&jerr.pub);
2538 jerr.pub.error_exit = my_error_exit;
2539 if (setjmp(jerr.setjmp_buffer)) {
2540 jpeg_destroy_decompress(&cinfo);
2545 jpeg_create_decompress(&cinfo);
2546 jpeg_stdio_src(&cinfo, infile);
2547 (void) jpeg_read_header(&cinfo, TRUE);
2549 cinfo.out_color_space = JCS_RGB;
2550 cinfo.quantize_colors = 0;
2551 (void) jpeg_calc_output_dimensions(&cinfo);
2552 (void) jpeg_start_decompress(&cinfo);
2554 row_stride = cinfo.output_width * cinfo.output_components;
2555 tex.sizeX = cinfo.output_width;
2556 tex.sizeY = cinfo.output_height;
2559 while (cinfo.output_scanline < cinfo.output_height) {
2560 buffer[0] = (JSAMPROW)(char *)tex.data +
2561 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
2562 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
2565 (void) jpeg_finish_decompress(&cinfo);
2566 jpeg_destroy_decompress(&cinfo);
2573 /* stolen from public domain example.c code in libpng distribution. */
2574 static bool load_png(const char *file_name, TGAImageRec &tex)
2576 bool hasalpha = false;
2577 png_structp png_ptr = NULL;
2578 png_infop info_ptr = NULL;
2579 png_uint_32 width, height;
2580 int bit_depth, color_type, interlace_type;
2581 png_byte **rows = NULL;
2582 bool retval = false;
2583 png_byte **row_pointers = NULL;
2584 FILE *fp = fopen(file_name, "rb");
2589 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2590 if (png_ptr == NULL)
2593 info_ptr = png_create_info_struct(png_ptr);
2594 if (info_ptr == NULL)
2597 if (setjmp(png_jmpbuf(png_ptr)))
2600 png_init_io(png_ptr, fp);
2601 png_read_png(png_ptr, info_ptr,
2602 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
2604 png_get_IHDR(png_ptr, info_ptr, &width, &height,
2605 &bit_depth, &color_type, &interlace_type, NULL, NULL);
2607 if (bit_depth != 8) // transform SHOULD handle this...
2610 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
2613 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
2616 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
2617 row_pointers = png_get_rows(png_ptr, info_ptr);
2623 png_byte *dst = tex.data;
2624 for (int i = height-1; i >= 0; i--)
2626 png_byte *src = row_pointers[i];
2627 for (int j = 0; j < width; j++)
2641 png_byte *dst = tex.data;
2642 int pitch = width * 4;
2643 for (int i = height-1; i >= 0; i--, dst += pitch)
2644 memcpy(dst, row_pointers[i], pitch);
2653 png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
2660 static bool save_image(const char *file_name)
2662 char *ptr = strrchr(file_name, '.');
2665 if (stricmp(ptr+1, "png") == 0)
2666 return save_png(file_name);
2669 STUBBED("Unsupported image type");
2674 static bool save_png(const char *file_name)
2677 png_structp png_ptr = NULL;
2678 png_infop info_ptr = NULL;
2679 bool retval = false;
2681 fp = fopen(file_name, "wb");
2685 png_bytep *row_pointers = new png_bytep[kContextHeight];
2686 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
2687 if ((!screenshot) || (!row_pointers))
2691 glReadPixels(0, 0, kContextWidth, kContextHeight,
2692 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
2693 if (glGetError() != GL_NO_ERROR)
2696 for (int i = 0; i < kContextHeight; i++)
2697 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
2699 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2700 if (png_ptr == NULL)
2703 info_ptr = png_create_info_struct(png_ptr);
2704 if (info_ptr == NULL)
2707 if (setjmp(png_jmpbuf(png_ptr)))
2710 png_init_io(png_ptr, fp);
2712 if (setjmp(png_jmpbuf(png_ptr)))
2715 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
2716 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
2717 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2719 png_write_info(png_ptr, info_ptr);
2721 if (setjmp(png_jmpbuf(png_ptr)))
2724 png_write_image(png_ptr, row_pointers);
2726 if (setjmp(png_jmpbuf(png_ptr)))
2729 png_write_end(png_ptr, NULL);
2733 png_destroy_write_struct(&png_ptr, &info_ptr);
2734 delete[] screenshot;
2735 delete[] row_pointers;
2739 unlink(ConvertFileName(file_name));