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, const char *libname)
147 *func = SDL_GL_GetProcAddress(funcname);
150 fprintf(stderr, "Failed to find OpenGL symbol \"%s\" in \"%s\"\n",
157 static bool lookup_all_glsyms(const char *libname)
160 #define GL_FUNC(ret,fn,params,call,rt) \
161 if (!lookup_glsym(#fn, (void **) &p##fn, libname)) retval = false;
167 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
174 void sdlGetCursorPos(POINT *pt)
177 SDL_GetMouseState(&x, &y);
181 #define GetCursorPos(x) sdlGetCursorPos(x)
182 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
183 #define ScreenToClient(x, pt)
184 #define ClientToScreen(x, pt)
185 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
191 static const char g_wndClassName[]={ "LUGARUWINDOWCLASS" };
192 static HINSTANCE g_appInstance;
193 static HWND g_windowHandle;
197 static bool g_button, fullscreen = true;
208 kForegroundSleep = 10,
209 kBackgroundSleep = 10000
216 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
219 char gcstrMode [256] = "";
221 UInt32 gSleepTime = kForegroundSleep;
222 Boolean gDone = false, gfFrontProcess = true;
227 static int _argc = 0;
228 static char **_argv = NULL;
230 bool cmdline(const char *cmd)
232 for (int i = 1; i < _argc; i++)
234 char *arg = _argv[i];
237 if (stricmp(arg, cmd) == 0)
245 // --------------------------------------------------------------------------
247 void ReportError (char * strError)
249 #ifdef WIN32 // !!! FIXME. --ryan.
250 throw std::exception( strError);
253 /* char errMsgCStr [256];
256 sprintf (errMsgCStr, "%s", strError);
258 // out as debug string
259 CToPStr (strErr, errMsgCStr);
264 void SetupDSpFullScreen ()
271 DEVMODE dmScreenSettings;
272 memset( &dmScreenSettings, 0, sizeof( dmScreenSettings));
273 dmScreenSettings.dmSize = sizeof( dmScreenSettings);
274 dmScreenSettings.dmPelsWidth = kContextWidth;
275 dmScreenSettings.dmPelsHeight = kContextHeight;
276 dmScreenSettings.dmBitsPerPel = kBitsPerPixel;
277 dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
280 if (ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
282 ReportError( "Could not set display mode");
299 ChangeDisplaySettings( NULL, 0);
307 //-----------------------------------------------------------------------------------------------------------------------
311 void DrawGL (Game & game)
322 static KeyMap g_theKeys;
324 void SetKey( int key)
326 g_theKeys[ key >> 3] |= (1 << (key & 7));
329 void ClearKey( int key)
331 g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
334 void GetKeys( unsigned char theKeys[16])
336 memcpy( theKeys, &g_theKeys, 16);
345 static void initSDLKeyTable(void) {}
347 #define MAX_SDLKEYS SDLK_LAST
348 static unsigned short KeyTable[MAX_SDLKEYS];
350 static void initSDLKeyTable(void)
352 memset(KeyTable, 0xFF, sizeof (KeyTable));
353 KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
354 KeyTable[SDLK_TAB] = MAC_TAB_KEY;
355 KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
356 KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
357 KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
358 KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
359 KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
360 KeyTable[SDLK_END] = MAC_END_KEY;
361 KeyTable[SDLK_HOME] = MAC_HOME_KEY;
362 KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
363 KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
364 KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
365 KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
366 KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
367 KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
368 KeyTable[SDLK_0] = MAC_0_KEY;
369 KeyTable[SDLK_1] = MAC_1_KEY;
370 KeyTable[SDLK_2] = MAC_2_KEY;
371 KeyTable[SDLK_3] = MAC_3_KEY;
372 KeyTable[SDLK_4] = MAC_4_KEY;
373 KeyTable[SDLK_5] = MAC_5_KEY;
374 KeyTable[SDLK_6] = MAC_6_KEY;
375 KeyTable[SDLK_7] = MAC_7_KEY;
376 KeyTable[SDLK_8] = MAC_8_KEY;
377 KeyTable[SDLK_9] = MAC_9_KEY;
378 KeyTable[SDLK_a] = MAC_A_KEY;
379 KeyTable[SDLK_b] = MAC_B_KEY;
380 KeyTable[SDLK_c] = MAC_C_KEY;
381 KeyTable[SDLK_d] = MAC_D_KEY;
382 KeyTable[SDLK_e] = MAC_E_KEY;
383 KeyTable[SDLK_f] = MAC_F_KEY;
384 KeyTable[SDLK_g] = MAC_G_KEY;
385 KeyTable[SDLK_h] = MAC_H_KEY;
386 KeyTable[SDLK_i] = MAC_I_KEY;
387 KeyTable[SDLK_j] = MAC_J_KEY;
388 KeyTable[SDLK_k] = MAC_K_KEY;
389 KeyTable[SDLK_l] = MAC_L_KEY;
390 KeyTable[SDLK_m] = MAC_M_KEY;
391 KeyTable[SDLK_n] = MAC_N_KEY;
392 KeyTable[SDLK_o] = MAC_O_KEY;
393 KeyTable[SDLK_p] = MAC_P_KEY;
394 KeyTable[SDLK_q] = MAC_Q_KEY;
395 KeyTable[SDLK_r] = MAC_R_KEY;
396 KeyTable[SDLK_s] = MAC_S_KEY;
397 KeyTable[SDLK_t] = MAC_T_KEY;
398 KeyTable[SDLK_u] = MAC_U_KEY;
399 KeyTable[SDLK_v] = MAC_V_KEY;
400 KeyTable[SDLK_w] = MAC_W_KEY;
401 KeyTable[SDLK_x] = MAC_X_KEY;
402 KeyTable[SDLK_y] = MAC_Y_KEY;
403 KeyTable[SDLK_z] = MAC_Z_KEY;
404 KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
405 KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
406 KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
407 KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
408 KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
409 KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
410 KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
411 KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
412 KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
413 KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
414 KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
415 KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
416 KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
417 KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
418 KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
419 KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
420 KeyTable[SDLK_F1] = MAC_F1_KEY;
421 KeyTable[SDLK_F2] = MAC_F2_KEY;
422 KeyTable[SDLK_F3] = MAC_F3_KEY;
423 KeyTable[SDLK_F4] = MAC_F4_KEY;
424 KeyTable[SDLK_F5] = MAC_F5_KEY;
425 KeyTable[SDLK_F6] = MAC_F6_KEY;
426 KeyTable[SDLK_F7] = MAC_F7_KEY;
427 KeyTable[SDLK_F8] = MAC_F8_KEY;
428 KeyTable[SDLK_F9] = MAC_F9_KEY;
429 KeyTable[SDLK_F10] = MAC_F10_KEY;
430 KeyTable[SDLK_F11] = MAC_F11_KEY;
431 KeyTable[SDLK_F12] = MAC_F12_KEY;
432 KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
433 KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
434 KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
435 KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
436 KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
437 KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
438 KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
439 KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
440 KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
441 KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
442 KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
445 static inline int clamp_sdl_mouse_button(Uint8 button)
447 if (button == 2) // right mouse button is button 3 in SDL.
449 else if (button == 3)
452 if ((button >= 1) && (button <= 3))
457 static void sdlEventProc(const SDL_Event &e, Game &game)
464 case SDL_MOUSEMOTION:
465 game.deltah += e.motion.xrel;
466 game.deltav += e.motion.yrel;
469 case SDL_MOUSEBUTTONDOWN:
471 val = clamp_sdl_mouse_button(e.button.button);
477 SetKey(MAC_MOUSEBUTTON1);
481 SetKey(MAC_MOUSEBUTTON2);
488 case SDL_MOUSEBUTTONUP:
490 val = clamp_sdl_mouse_button(e.button.button);
496 ClearKey(MAC_MOUSEBUTTON1);
500 ClearKey(MAC_MOUSEBUTTON2);
502 buttons[val] = false;
508 if (e.key.keysym.sym == SDLK_g)
510 if (e.key.keysym.mod & KMOD_CTRL)
512 SDL_GrabMode mode = SDL_GRAB_ON;
513 if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
515 mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
516 mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
518 SDL_WM_GrabInput(mode);
522 else if (e.key.keysym.sym == SDLK_RETURN)
524 if (e.key.keysym.mod & KMOD_ALT)
525 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
528 if (e.key.keysym.sym < SDLK_LAST)
530 if (KeyTable[e.key.keysym.sym] != 0xffff)
531 SetKey(KeyTable[e.key.keysym.sym]);
534 mod = SDL_GetModState();
536 SetKey(MAC_CONTROL_KEY);
538 SetKey(MAC_OPTION_KEY);
539 if (mod & KMOD_SHIFT)
540 SetKey(MAC_SHIFT_KEY);
542 SetKey(MAC_CAPS_LOCK_KEY);
547 if (e.key.keysym.sym < SDLK_LAST)
549 if (KeyTable[e.key.keysym.sym] != 0xffff)
550 ClearKey(KeyTable[e.key.keysym.sym]);
553 mod = SDL_GetModState();
554 if ((mod & KMOD_CTRL) == 0)
555 ClearKey(MAC_CONTROL_KEY);
556 if ((mod & KMOD_ALT) == 0)
557 ClearKey(MAC_OPTION_KEY);
558 if ((mod & KMOD_SHIFT) == 0)
559 ClearKey(MAC_SHIFT_KEY);
560 if ((mod & KMOD_CAPS) == 0)
561 ClearKey(MAC_CAPS_LOCK_KEY);
567 // --------------------------------------------------------------------------
569 static Point gMidPoint;
571 Boolean SetUp (Game & game)
577 randSeed = UpTime().lo;
580 ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
583 usermousesensitivity=1;
612 game.crouchkey=MAC_SHIFT_KEY;
613 game.jumpkey=MAC_SPACE_KEY;
614 game.leftkey=MAC_A_KEY;
615 game.forwardkey=MAC_W_KEY;
616 game.backkey=MAC_S_KEY;
617 game.rightkey=MAC_D_KEY;
618 game.drawkey=MAC_E_KEY;
619 game.throwkey=MAC_Q_KEY;
620 game.attackkey=MAC_MOUSEBUTTON1;
621 game.chatkey=MAC_T_KEY;
627 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
630 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
631 opstream << "Screenwidth:\n";
632 opstream << kContextWidth;
633 opstream << "\nScreenheight:\n";
634 opstream << kContextHeight;
635 opstream << "\nMouse sensitivity:\n";
636 opstream << usermousesensitivity;
637 opstream << "\nBlur(0,1):\n";
638 opstream << ismotionblur;
639 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
641 opstream << "\nFloating jump:\n";
642 opstream << floatjump;
643 opstream << "\nMouse jump:\n";
644 opstream << mousejump;
645 opstream << "\nAmbient sound:\n";
646 opstream << ambientsound;
647 opstream << "\nBlood (0,1,2):\n";
648 opstream << bloodtoggle;
649 opstream << "\nAuto slomo:\n";
650 opstream << autoslomo;
651 opstream << "\nFoliage:\n";
653 opstream << "\nMusic:\n";
654 opstream << musictoggle;
655 opstream << "\nTrilinear:\n";
656 opstream << trilinear;
657 opstream << "\nDecals(shadows,blood puddles,etc):\n";
659 opstream << "\nInvert mouse:\n";
660 opstream << invertmouse;
661 opstream << "\nGamespeed:\n";
662 opstream << gamespeed;
663 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
664 opstream << difficulty;
665 opstream << "\nDamage effects(blackout, doublevision):\n";
666 opstream << damageeffects;
667 opstream << "\nText:\n";
668 opstream << texttoggle;
669 opstream << "\nDebug:\n";
670 opstream << debugmode;
671 opstream << "\nVBL Sync:\n";
673 opstream << "\nShow Points:\n";
674 opstream << showpoints;
675 opstream << "\nAlways Blur:\n";
676 opstream << alwaysblur;
677 opstream << "\nImmediate mode (turn on on G5):\n";
678 opstream << immediate;
679 opstream << "\nVelocity blur:\n";
680 opstream << velocityblur;
681 opstream << "\nVolume:\n";
683 opstream << "\nForward key:\n";
684 opstream << KeyToChar(game.forwardkey);
685 opstream << "\nBack key:\n";
686 opstream << KeyToChar(game.backkey);
687 opstream << "\nLeft key:\n";
688 opstream << KeyToChar(game.leftkey);
689 opstream << "\nRight key:\n";
690 opstream << KeyToChar(game.rightkey);
691 opstream << "\nJump key:\n";
692 opstream << KeyToChar(game.jumpkey);
693 opstream << "\nCrouch key:\n";
694 opstream << KeyToChar(game.crouchkey);
695 opstream << "\nDraw key:\n";
696 opstream << KeyToChar(game.drawkey);
697 opstream << "\nThrow key:\n";
698 opstream << KeyToChar(game.throwkey);
699 opstream << "\nAttack key:\n";
700 opstream << KeyToChar(game.attackkey);
701 opstream << "\nChat key:\n";
702 opstream << KeyToChar(game.chatkey);
707 ipstream.ignore(256,'\n');
708 ipstream >> kContextWidth;
709 ipstream.ignore(256,'\n');
710 ipstream.ignore(256,'\n');
711 ipstream >> kContextHeight;
712 ipstream.ignore(256,'\n');
713 ipstream.ignore(256,'\n');
714 ipstream >> usermousesensitivity;
715 ipstream.ignore(256,'\n');
716 ipstream.ignore(256,'\n');
718 ismotionblur = (i != 0);
719 ipstream.ignore(256,'\n');
720 ipstream.ignore(256,'\n');
722 if(detail!=0)kBitsPerPixel=32;
723 else kBitsPerPixel=16;
724 ipstream.ignore(256,'\n');
725 ipstream.ignore(256,'\n');
727 floatjump = (i != 0);
728 ipstream.ignore(256,'\n');
729 ipstream.ignore(256,'\n');
731 mousejump = (i != 0);
732 ipstream.ignore(256,'\n');
733 ipstream.ignore(256,'\n');
735 ambientsound = (i != 0);
736 ipstream.ignore(256,'\n');
737 ipstream.ignore(256,'\n');
738 ipstream >> bloodtoggle;
739 ipstream.ignore(256,'\n');
740 ipstream.ignore(256,'\n');
742 autoslomo = (i != 0);
743 ipstream.ignore(256,'\n');
744 ipstream.ignore(256,'\n');
747 ipstream.ignore(256,'\n');
748 ipstream.ignore(256,'\n');
750 musictoggle = (i != 0);
751 ipstream.ignore(256,'\n');
752 ipstream.ignore(256,'\n');
754 trilinear = (i != 0);
755 ipstream.ignore(256,'\n');
756 ipstream.ignore(256,'\n');
759 ipstream.ignore(256,'\n');
760 ipstream.ignore(256,'\n');
762 invertmouse = (i != 0);
763 ipstream.ignore(256,'\n');
764 ipstream.ignore(256,'\n');
765 ipstream >> gamespeed;
766 oldgamespeed=gamespeed;
771 ipstream.ignore(256,'\n');
772 ipstream.ignore(256,'\n');
773 ipstream >> difficulty;
774 ipstream.ignore(256,'\n');
775 ipstream.ignore(256,'\n');
777 damageeffects = (i != 0);
778 ipstream.ignore(256,'\n');
779 ipstream.ignore(256,'\n');
781 texttoggle = (i != 0);
782 ipstream.ignore(256,'\n');
783 ipstream.ignore(256,'\n');
785 debugmode = (i != 0);
786 ipstream.ignore(256,'\n');
787 ipstream.ignore(256,'\n');
790 ipstream.ignore(256,'\n');
791 ipstream.ignore(256,'\n');
793 showpoints = (i != 0);
794 ipstream.ignore(256,'\n');
795 ipstream.ignore(256,'\n');
797 alwaysblur = (i != 0);
798 ipstream.ignore(256,'\n');
799 ipstream.ignore(256,'\n');
801 immediate = (i != 0);
802 ipstream.ignore(256,'\n');
803 ipstream.ignore(256,'\n');
805 velocityblur = (i != 0);
806 ipstream.ignore(256,'\n');
807 ipstream.ignore(256,'\n');
809 ipstream.ignore(256,'\n');
810 ipstream.ignore(256,'\n');
812 game.forwardkey=CharToKey(string);
813 ipstream.ignore(256,'\n');
814 ipstream.ignore(256,'\n');
816 game.backkey=CharToKey(string);
817 ipstream.ignore(256,'\n');
818 ipstream.ignore(256,'\n');
820 game.leftkey=CharToKey(string);
821 ipstream.ignore(256,'\n');
822 ipstream.ignore(256,'\n');
824 game.rightkey=CharToKey(string);
825 ipstream.ignore(256,'\n');
826 ipstream.ignore(256,'\n');
828 game.jumpkey=CharToKey(string);
829 ipstream.ignore(256,'\n');
830 ipstream.ignore(256,'\n');
832 game.crouchkey=CharToKey(string);
833 ipstream.ignore(256,'\n');
834 ipstream.ignore(256,'\n');
836 game.drawkey=CharToKey(string);
837 ipstream.ignore(256,'\n');
838 ipstream.ignore(256,'\n');
840 game.throwkey=CharToKey(string);
841 ipstream.ignore(256,'\n');
842 ipstream.ignore(256,'\n');
844 game.attackkey=CharToKey(string);
845 ipstream.ignore(256,'\n');
846 ipstream.ignore(256,'\n');
848 game.chatkey=CharToKey(string);
851 if(detail>2)detail=2;
852 if(detail<0)detail=0;
853 if(screenwidth>3000)screenwidth=640;
854 if(screenwidth<0)screenwidth=640;
855 if(screenheight>3000)screenheight=480;
856 if(screenheight<0)screenheight=480;
858 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
863 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
865 SetupDSpFullScreen();
868 if (!SDL_WasInit(SDL_INIT_VIDEO))
870 if (SDL_Init(SDL_INIT_VIDEO) == -1)
872 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
876 const char *libname = "libGL.so.1"; // !!! FIXME: Linux specific!
877 if (SDL_GL_LoadLibrary(libname) == -1)
879 fprintf(stderr, "SDL_GL_LoadLibrary(\"%s\") failed: %s\n",
880 libname, SDL_GetError());
884 if (!lookup_all_glsyms(libname))
888 Uint32 sdlflags = SDL_OPENGL;
889 if (!cmdline("windowed"))
890 sdlflags |= SDL_FULLSCREEN;
892 SDL_WM_SetCaption("Lugaru", "lugaru");
896 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
898 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
902 if (!cmdline("nomousegrab"))
903 SDL_WM_GrabInput(SDL_GRAB_ON);
905 #elif (defined WIN32)
906 //------------------------------------------------------------------
909 RECT r = {0, 0, kContextWidth-1, kContextHeight-1};
910 DWORD dwStyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE;
911 DWORD dwExStyle = WS_EX_APPWINDOW;
920 dwStyle |= WS_OVERLAPPEDWINDOW;
921 dwExStyle |= WS_EX_WINDOWEDGE;
924 AdjustWindowRectEx(&r, dwStyle, FALSE, dwExStyle);
928 x = (GetSystemMetrics(SM_CXSCREEN) >> 1) - ((r.right - r.left + 1) >> 1);
929 y = (GetSystemMetrics(SM_CYSCREEN) >> 1) - ((r.bottom - r.top + 1) >> 1);
932 g_windowHandle=CreateWindowEx(
934 g_wndClassName, "Lugaru", dwStyle,
936 // kContextWidth, kContextHeight,
937 r.right - r.left + 1, r.bottom - r.top + 1,
938 NULL,NULL,g_appInstance,NULL );
941 ReportError("Could not create window");
945 //------------------------------------------------------------------
948 static PIXELFORMATDESCRIPTOR pfd =
950 sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
952 PFD_DRAW_TO_WINDOW | // Format Must Support Window
953 PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
954 PFD_DOUBLEBUFFER, // Must Support Double Buffering
955 PFD_TYPE_RGBA, // Request An RGBA Format
956 kBitsPerPixel, // Select Our Color Depth
957 0, 0, 0, 0, 0, 0, // Color Bits Ignored
958 0, // No Alpha Buffer
959 0, // Shift Bit Ignored
960 0, // No Accumulation Buffer
961 0, 0, 0, 0, // Accumulation Bits Ignored
962 16, // 16Bit Z-Buffer (Depth Buffer)
963 0, // No Stencil Buffer
964 0, // No Auxiliary Buffer
965 PFD_MAIN_PLANE, // Main Drawing Layer
967 0, 0, 0 // Layer Masks Ignored
970 if (!(hDC = GetDC( g_windowHandle)))
971 ReportError( "Could not get device context");
974 if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))
976 ReportError( "Could not find appropriate pixel format");
980 if (!DescribePixelFormat(hDC, PixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd))
982 ReportError( "Could not retrieve pixel format");
986 if (!SetPixelFormat( hDC, PixelFormat, &pfd))
988 ReportError( "Could not set pixel format");
992 if (!(hRC = wglCreateContext(hDC)))
994 ReportError( "Could not create rendering context");
998 if (!wglMakeCurrent(hDC, hRC))
1000 ReportError( "Could not activate rendering context");
1006 // Place the window above all topmost windows
1007 SetWindowPos( g_windowHandle, HWND_TOPMOST, 0,0,0,0,
1008 SWP_NOMOVE | SWP_NOSIZE );
1011 SetForegroundWindow(g_windowHandle);
1012 SetFocus(g_windowHandle);
1015 glClear( GL_COLOR_BUFFER_BIT );
1019 glDisable( GL_ALPHA_TEST);
1020 glDisable( GL_BLEND);
1021 glDisable( GL_DEPTH_TEST);
1022 // glDisable( GL_DITHER);
1024 glDisable( GL_LIGHTING);
1025 glDisable( GL_LOGIC_OP);
1026 glDisable( GL_STENCIL_TEST);
1027 glDisable( GL_TEXTURE_1D);
1028 glDisable( GL_TEXTURE_2D);
1029 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
1030 glPixelTransferi( GL_RED_SCALE, 1);
1031 glPixelTransferi( GL_RED_BIAS, 0);
1032 glPixelTransferi( GL_GREEN_SCALE, 1);
1033 glPixelTransferi( GL_GREEN_BIAS, 0);
1034 glPixelTransferi( GL_BLUE_SCALE, 1);
1035 glPixelTransferi( GL_BLUE_BIAS, 0);
1036 glPixelTransferi( GL_ALPHA_SCALE, 1);
1037 glPixelTransferi( GL_ALPHA_BIAS, 0);
1039 // set initial rendering states
1040 glShadeModel( GL_SMOOTH);
1041 glClearDepth( 1.0f);
1042 glDepthFunc( GL_LEQUAL);
1043 glDepthMask( GL_TRUE);
1044 // glDepthRange( FRONT_CLIP, BACK_CLIP);
1045 glEnable( GL_DEPTH_TEST);
1046 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
1047 glCullFace( GL_FRONT);
1048 glEnable( GL_CULL_FACE);
1049 glEnable( GL_LIGHTING);
1050 // glEnable( GL_LIGHT_MODEL_AMBIENT);
1051 glEnable( GL_DITHER);
1052 glEnable( GL_COLOR_MATERIAL);
1053 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1054 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1055 glAlphaFunc( GL_GREATER, 0.5f);
1058 if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION ||
1059 iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION ||
1060 ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION)
1062 ReportError("DevIL version is different...exiting!\n");
1070 ilutRenderer(ILUT_OPENGL);
1072 ilEnable(IL_ORIGIN_SET);
1073 ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
1076 GLint width = kContextWidth;
1077 GLint height = kContextHeight;
1078 gMidPoint.h = width / 2;
1079 gMidPoint.v = height / 2;
1081 screenheight=height;
1083 game.newdetail=detail;
1084 game.newscreenwidth=screenwidth;
1085 game.newscreenheight=screenheight;
1093 static void DoMouse(Game & game)
1096 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1098 game.deltah *= usermousesensitivity;
1099 game.deltav *= usermousesensitivity;
1100 game.mousecoordh += game.deltah;
1101 game.mousecoordv += game.deltav;
1102 if (game.mousecoordh < 0)
1103 game.mousecoordh = 0;
1104 else if (game.mousecoordh >= kContextWidth)
1105 game.mousecoordh = kContextWidth - 1;
1106 if (game.mousecoordv < 0)
1107 game.mousecoordv = 0;
1108 else if (game.mousecoordv >= kContextHeight)
1109 game.mousecoordv = kContextHeight - 1;
1112 static Point lastMouse = {-1,-1};
1117 ScreenToClient(g_windowHandle, &pos);
1118 globalMouse.h = pos.x;
1119 globalMouse.v = pos.y;
1121 if (lastMouse.h == globalMouse.h && lastMouse.v == globalMouse.v)
1128 static Point virtualMouse = {0,0};
1129 delta = globalMouse;
1131 delta.h -= lastMouse.h;
1132 delta.v -= lastMouse.v;
1133 lastMouse.h = pos.x;
1134 lastMouse.v = pos.y;
1136 if(mainmenu||(abs(delta.h)<10*realmultiplier*1000&&abs(delta.v)<10*realmultiplier*1000)){
1137 game.deltah=delta.h*usermousesensitivity;
1138 game.deltav=delta.v*usermousesensitivity;
1139 game.mousecoordh=globalMouse.h;
1140 game.mousecoordv=globalMouse.v;
1145 if(lastMouse.h>gMidPoint.h+100||lastMouse.h<gMidPoint.h-100||lastMouse.v>gMidPoint.v+100||lastMouse.v<gMidPoint.v-100){
1146 pos.x = gMidPoint.h;
1147 pos.y = gMidPoint.v;
1148 ClientToScreen(g_windowHandle, &pos);
1149 //SetCursorPos( gMidPoint.h,gMidPoint.v);
1150 SetCursorPos(pos.x, pos.y);
1151 lastMouse = gMidPoint;
1160 // --------------------------------------------------------------------------
1162 void DoKey (SInt8 theKey, SInt8 theCode)
1167 // --------------------------------------------------------------------------
1171 void DoFrameRate (int update)
1173 static long frames = 0;
1175 static AbsoluteTime time = {0,0};
1176 static AbsoluteTime frametime = {0,0};
1177 AbsoluteTime currTime = UpTime ();
1178 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1180 if (0 > deltaTime) // if negative microseconds
1181 deltaTime /= -1000000.0;
1182 else // else milliseconds
1183 deltaTime /= 1000.0;
1185 multiplier=deltaTime;
1186 if(multiplier<.001)multiplier=.001;
1187 if(multiplier>10)multiplier=10;
1188 if(update)frametime = currTime; // reset for next time interval
1190 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1192 if (0 > deltaTime) // if negative microseconds
1193 deltaTime /= -1000000.0;
1194 else // else milliseconds
1195 deltaTime /= 1000.0;
1197 if (0.001 <= deltaTime) // has update interval passed
1200 time = currTime; // reset for next time interval
1207 void DoUpdate (Game & game)
1209 static float sps=200;
1211 static float oldmult;
1214 if(multiplier>.6)multiplier=.6;
1216 game.fps=1/multiplier;
1218 count = multiplier*sps;
1220 //if(count>10)count=10;
1222 realmultiplier=multiplier;
1223 multiplier*=gamespeed;
1224 if(difficulty==1)multiplier*=.9;
1225 if(difficulty==0)multiplier*=.8;
1227 if(game.loading==4)multiplier*=.00001;
1229 if(slomo&&!mainmenu)multiplier*=slomospeed;
1230 //if(freeze)multiplier*=0.00001;
1232 multiplier/=(float)count;
1238 for(int i=0;i<count;i++)
1244 game.TickOnceAfter();
1245 /* - Debug code to test how many channels were active on average per frame
1246 static long frames = 0;
1248 static AbsoluteTime start = {0,0};
1249 AbsoluteTime currTime = UpTime ();
1250 static int num_channels = 0;
1252 num_channels += FSOUND_GetChannelsPlaying();
1253 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1255 if (0 > deltaTime) // if negative microseconds
1256 deltaTime /= -1000000.0;
1257 else // else milliseconds
1258 deltaTime /= 1000.0;
1265 float avg_channels = (float)num_channels / (float)frames;
1267 ofstream opstream("log.txt",ios::app);
1268 opstream << "Average frame count: ";
1270 opstream << " frames - ";
1271 opstream << avg_channels;
1272 opstream << " per frame.\n";
1282 // --------------------------------------------------------------------------
1297 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1298 #include "glstubs.h"
1300 // cheat here...static destructors are calling glDeleteTexture() after
1301 // the context is destroyed and libGL unloaded by SDL_Quit().
1302 pglDeleteTextures = glDeleteTextures_doNothing;
1304 #elif (defined WIN32)
1307 wglMakeCurrent( NULL, NULL);
1308 wglDeleteContext( hRC);
1314 ReleaseDC( g_windowHandle, hDC);
1320 ShowWindow( g_windowHandle, SW_HIDE );
1321 DestroyWindow( g_windowHandle);
1322 g_windowHandle = NULL;
1330 // --------------------------------------------------------------------------
1332 static bool g_focused = true;
1335 static bool IsFocused()
1341 if (GetActiveWindow() != g_windowHandle)
1344 if (IsIconic( g_windowHandle))
1356 static bool try_launch_browser(const char *browser, const char *url)
1358 // make sure string isn't empty...
1359 while ( (*browser) && (isspace(*browser)) ) browser++;
1360 if (*browser == '\0') return false;
1362 bool seenurl = false;
1363 char buf[4096]; // !!! FIXME: we aren't checking for overflow here!
1367 char ch = *(browser++);
1373 else if (ch == 's') // "%s" == insert URL here.
1381 // (not %% or %s? Drop the char.)
1396 #define MAX_BROWSER_ARGS 512
1397 char *args[MAX_BROWSER_ARGS];
1399 memset(args, '\0', sizeof (args));
1400 path = args[0] = strtok(buf, " ");
1405 for (i = 1; i < MAX_BROWSER_ARGS; i++)
1407 args[i] = strtok(NULL, " ");
1408 if (args[i] == NULL)
1412 if (i == MAX_BROWSER_ARGS)
1414 #undef MAX_BROWSER_ARGS
1416 //printf("calling execvp(\"%s\"", path);
1417 //for (i = 0; args[i]; i++)
1418 // printf(", \"%s\"", args[i]);
1419 //printf("); ...\n\n\n");
1422 return(false); // exec shouldn't return unless there's an error.
1427 static void launch_web_browser(const char *url)
1430 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1432 // lousy linux doesn't have a clean way to do this, but you can point people
1433 // to docs on the BROWSER variable:
1434 // http://www.catb.org/~esr/BROWSER/
1435 #elif PLATFORM_LINUX
1436 if (strchr(url, '\'') != NULL) // Prevent simple shell injection.
1439 const char *envr = getenv("BROWSER");
1440 if (envr == NULL) // not specified? We'll try a pseudo-sane list...
1441 envr = "opera:mozilla:konqueror:firefox:netscape:xterm -e links:xterm -e lynx:";
1443 char *ptr = (char *) alloca(strlen(envr) + 1);
1449 while ((ptr = strchr(envr, ':')) != NULL)
1452 if (try_launch_browser(envr, url))
1457 try_launch_browser(envr, url);
1463 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1464 static char *findBinaryInPath(const char *bin, char *envr)
1466 size_t alloc_size = 0;
1474 ptr = strchr(start, ':'); /* find next $PATH separator. */
1478 size = strlen(start) + strlen(bin) + 2;
1479 if (size > alloc_size)
1481 char *x = (char *) realloc(exe, size);
1493 /* build full binary path... */
1495 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1499 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
1501 strcpy(exe, start); /* i'm lazy. piss off. */
1505 start = ptr + 1; /* start points to beginning of next element. */
1506 } while (ptr != NULL);
1511 return(NULL); /* doesn't exist in path. */
1512 } /* findBinaryInPath */
1515 char *calcBaseDir(const char *argv0)
1517 /* If there isn't a path on argv0, then look through the $PATH for it. */
1521 char *ptr = strrchr(argv0, '/');
1522 if (strchr(argv0, '/'))
1524 retval = strdup(argv0);
1526 *(strrchr(retval, '/')) = '\0';
1530 envr = getenv("PATH");
1531 if (!envr) return NULL;
1532 envr = strdup(envr);
1533 if (!envr) return NULL;
1534 retval = findBinaryInPath(argv0, envr);
1539 static inline void chdirToAppPath(const char *argv0)
1541 char *dir = calcBaseDir(argv0);
1551 int main(int argc, char **argv)
1556 chdirToAppPath(argv[0]);
1561 #ifndef WIN32 // this is in WinMain, too.
1563 memset( &g_theKeys, 0, sizeof( KeyMap));
1570 bool regnow = false;
1575 //ofstream os("error.txt");
1577 //ofstream os("log.txt");
1583 while (!gDone&&!game.quit&&(!game.tryquit||!game.registered))
1589 // check windows messages
1595 while( SDL_PollEvent( &e ) )
1597 if( e.type == SDL_QUIT )
1602 sdlEventProc(e, game);
1605 #elif (defined WIN32)
1608 while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE | PM_NOYIELD ) )
1610 if( msg.message == WM_QUIT )
1617 TranslateMessage( &msg );
1618 DispatchMessage( &msg );
1630 // allow game chance to pause
1631 gameFocused = false;
1635 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1639 //if (GetMessage( &msg, g_windowHandle, 0, 0 ))
1640 /*if (GetMessage( &msg, NULL, 0, 0 ))
1642 TranslateMessage(&msg);
1643 DispatchMessage(&msg);
1645 if ( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
1649 // handle the error and possibly exit
1654 TranslateMessage(&msg);
1655 DispatchMessage(&msg);
1659 STUBBED("give up CPU but sniff the event queue");
1664 regnow = game.registernow;
1669 // if(game.registernow){
1672 #if PLATFORM_LINUX // (this may not be necessary any more.)
1673 launch_web_browser("http://www.wolfire.com/registerlinux.html");
1675 launch_web_browser("http://www.wolfire.com/registerpc.html");
1679 #if PLATFORM_LINUX // (this may not be necessary any more.)
1680 _exit(0); // !!! FIXME: hack...crashes on exit!
1684 catch (const std::exception& error)
1688 std::string e = "Caught exception: ";
1691 LOG(e, Logger::LOG_ERR);
1693 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1703 // --------------------------------------------------------------------------
1706 #define MAX_WINKEYS 256
1707 static unsigned short KeyTable[MAX_WINKEYS]=
1710 MAC_MOUSEBUTTON1, // VK_LBUTTON (1)
1711 MAC_MOUSEBUTTON2, // VK_RBUTTON (2)
1712 0xffff, // VK_CANCEL (3)
1713 0xffff, // VK_MBUTTON (4)
1717 MAC_DELETE_KEY, // VK_BACK (8)
1718 MAC_TAB_KEY, // VK_TAB (9)
1721 0xffff, // VK_CLEAR (12)
1722 MAC_RETURN_KEY, // VK_RETURN (13)
1725 MAC_SHIFT_KEY, // VK_SHIFT (16)
1726 MAC_CONTROL_KEY, // VK_CONTROL (17)
1727 MAC_OPTION_KEY, // VK_MENU (18)
1728 0xffff, // VK_PAUSE (19)
1729 MAC_CAPS_LOCK_KEY, // #define VK_CAPITAL (20)
1736 MAC_ESCAPE_KEY, // VK_ESCAPE (27)
1741 MAC_SPACE_KEY, // VK_SPACE (32)
1742 MAC_PAGE_UP_KEY, // VK_PRIOR (33)
1743 MAC_PAGE_DOWN_KEY, // VK_NEXT (34)
1744 MAC_END_KEY, // VK_END (35)
1745 MAC_HOME_KEY, // VK_HOME (36)
1746 MAC_ARROW_LEFT_KEY, // VK_LEFT (37)
1747 MAC_ARROW_UP_KEY, // VK_UP (38)
1748 MAC_ARROW_RIGHT_KEY, // VK_RIGHT (39)
1749 MAC_ARROW_DOWN_KEY, // VK_DOWN (40)
1750 0xffff, // VK_SELECT (41)
1751 0xffff, // VK_PRINT (42)
1752 0xffff, // VK_EXECUTE (43)
1753 0xffff, // VK_SNAPSHOT (44)
1754 MAC_INSERT_KEY, // VK_INSERT (45)
1755 MAC_DEL_KEY, // VK_DELETE (46)
1756 0xffff, // VK_HELP (47)
1757 MAC_0_KEY, // VK_0 (48)
1758 MAC_1_KEY, // VK_1 (49)
1759 MAC_2_KEY, // VK_2 (50)
1760 MAC_3_KEY, // VK_3 (51)
1761 MAC_4_KEY, // VK_4 (52)
1762 MAC_5_KEY, // VK_5 (53)
1763 MAC_6_KEY, // VK_6 (54)
1764 MAC_7_KEY, // VK_7 (55)
1765 MAC_8_KEY, // VK_8 (56)
1766 MAC_9_KEY, // VK_9 (57)
1774 MAC_A_KEY, // VK_A (65)
1775 MAC_B_KEY, // VK_B (66)
1776 MAC_C_KEY, // VK_C (67)
1777 MAC_D_KEY, // VK_D (68)
1778 MAC_E_KEY, // VK_E (69)
1779 MAC_F_KEY, // VK_F (70)
1780 MAC_G_KEY, // VK_G (71)
1781 MAC_H_KEY, // VK_H (72)
1782 MAC_I_KEY, // VK_I (73)
1783 MAC_J_KEY, // VK_J (74)
1784 MAC_K_KEY, // VK_K (75)
1785 MAC_L_KEY, // VK_L (76)
1786 MAC_M_KEY, // VK_M (77)
1787 MAC_N_KEY, // VK_N (78)
1788 MAC_O_KEY, // VK_O (79)
1789 MAC_P_KEY, // VK_P (80)
1790 MAC_Q_KEY, // VK_Q (81)
1791 MAC_R_KEY, // VK_R (82)
1792 MAC_S_KEY, // VK_S (83)
1793 MAC_T_KEY, // VK_T (84)
1794 MAC_U_KEY, // VK_U (85)
1795 MAC_V_KEY, // VK_V (86)
1796 MAC_W_KEY, // VK_W (87)
1797 MAC_X_KEY, // VK_X (88)
1798 MAC_Y_KEY, // VK_Y (89)
1799 MAC_Z_KEY, // VK_Z (90)
1805 MAC_NUMPAD_0_KEY, // VK_NUMPAD0 (96)
1806 MAC_NUMPAD_1_KEY, // VK_NUMPAD1 (97)
1807 MAC_NUMPAD_2_KEY, // VK_NUMPAD2 (98)
1808 MAC_NUMPAD_3_KEY, // VK_NUMPAD3 (99)
1809 MAC_NUMPAD_4_KEY, // VK_NUMPAD4 (100)
1810 MAC_NUMPAD_5_KEY, // VK_NUMPAD5 (101)
1811 MAC_NUMPAD_6_KEY, // VK_NUMPAD6 (102)
1812 MAC_NUMPAD_7_KEY, // VK_NUMPAD7 (103)
1813 MAC_NUMPAD_8_KEY, // VK_NUMPAD8 (104)
1814 MAC_NUMPAD_9_KEY, // VK_NUMPAD9 (105)
1815 MAC_NUMPAD_ASTERISK_KEY, // VK_MULTIPLY (106)
1816 MAC_NUMPAD_PLUS_KEY, // VK_ADD (107)
1817 MAC_NUMPAD_ENTER_KEY, // VK_SEPARATOR (108)
1818 MAC_NUMPAD_MINUS_KEY, // VK_SUBTRACT (109)
1819 MAC_NUMPAD_PERIOD_KEY, // VK_DECIMAL (110)
1820 MAC_NUMPAD_SLASH_KEY, // VK_DIVIDE (111)
1821 MAC_F1_KEY, // VK_F1 (112)
1822 MAC_F2_KEY, // VK_F2 (113)
1823 MAC_F3_KEY, // VK_F3 (114)
1824 MAC_F4_KEY, // VK_F4 (115)
1825 MAC_F5_KEY, // VK_F5 (116)
1826 MAC_F6_KEY, // VK_F6 (117)
1827 MAC_F7_KEY, // VK_F7 (118)
1828 MAC_F8_KEY, // VK_F8 (119)
1829 MAC_F9_KEY, // VK_F9 (120)
1830 MAC_F10_KEY, // VK_F10 (121)
1831 MAC_F11_KEY, // VK_F11 (122)
1832 MAC_F12_KEY, // VK_F12 (123)
1853 0xffff, // VK_NUMLOCK (144)
1854 0xffff, // VK_SCROLL (145)
1869 MAC_SHIFT_KEY, // VK_LSHIFT (160)
1870 MAC_SHIFT_KEY, // VK_RSHIFT (161)
1871 MAC_CONTROL_KEY, // VK_LCONTROL (162)
1872 MAC_CONTROL_KEY, // VK_RCONTROL (163)
1873 MAC_OPTION_KEY, // VK_LMENU (164)
1874 MAC_OPTION_KEY, // VK_RMENU (165)
1895 MAC_SEMICOLON_KEY, // (186)
1896 MAC_PLUS_KEY, // (187)
1897 MAC_COMMA_KEY, // (188)
1898 MAC_MINUS_KEY, // (189)
1899 MAC_PERIOD_KEY, // (190)
1900 MAC_SLASH_KEY, // (191)
1901 MAC_TILDE_KEY, // (192)
1928 MAC_LEFTBRACKET_KEY, // (219)
1929 MAC_BACKSLASH_KEY, // (220)
1930 MAC_RIGHTBRACKET_KEY, // (221)
1931 MAC_APOSTROPHE_KEY, // (222)
1967 void ClipMouseToWindow(HWND window)
1971 GetClientRect(window, &wRect);
1973 ClientToScreen(window, (LPPOINT)&wRect.left);
1974 ClientToScreen(window, (LPPOINT)&wRect.right);
1981 LRESULT FAR PASCAL AppWndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
1983 /* this is where we receive all messages concerning this window
1984 * we can either process a message or pass it on to the default
1985 * message handler of windows */
1987 static PAINTSTRUCT ps;
1991 case WM_ACTIVATE: // Watch For Window Activate Message
1993 // Check Minimization State
1994 BOOL iconified = HIWORD(wParam) ? TRUE : FALSE;
1996 if (LOWORD(wParam) == WA_INACTIVE)
2005 CloseWindow( hWnd );
2007 // The window is now iconified
2008 iconified = GL_TRUE;
2014 g_focused=false; // Program Is Active
2018 SetupDSpFullScreen();
2025 // The window is now iconified
2026 iconified = GL_FALSE;
2029 ShowWindow( hWnd, SW_SHOW );
2030 SetForegroundWindow( hWnd );
2034 ClipMouseToWindow(hWnd);
2035 g_focused=true; // Program Is No Longer Active
2038 return 0; // Return To The Message Loop
2044 // check for Alt-F4 (exit hotkey)
2045 if (wParam == VK_F4)
2047 if (GetKeyState( VK_MENU) & 0x8080)
2053 if (wParam < MAX_WINKEYS)
2055 if (KeyTable[wParam] != 0xffff)
2056 SetKey( KeyTable[wParam]);
2064 if (wParam < MAX_WINKEYS)
2065 if (KeyTable[wParam] != 0xffff)
2066 ClearKey( KeyTable[wParam]);
2073 case WM_SYSDEADCHAR:
2076 case WM_NCLBUTTONDOWN:
2077 case WM_LBUTTONDOWN:
2084 case WM_NCRBUTTONDOWN:
2085 case WM_RBUTTONDOWN:
2091 case WM_NCMBUTTONDOWN:
2092 case WM_MBUTTONDOWN:
2098 case WM_NCLBUTTONUP:
2102 buttons[ 0] = false;
2106 case WM_NCRBUTTONUP:
2109 buttons[ 1] = false;
2113 case WM_NCMBUTTONUP:
2116 buttons[ 2] = false;
2120 case WM_NCLBUTTONDBLCLK:
2121 case WM_NCRBUTTONDBLCLK:
2122 case WM_NCMBUTTONDBLCLK:
2123 case WM_LBUTTONDBLCLK:
2125 case WM_RBUTTONDBLCLK:
2126 case WM_MBUTTONDBLCLK:
2129 case WM_NCMOUSEMOVE:
2131 /* ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseX = (signed short)(lParam & 0xffff);
2132 ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseY = (signed short)(lParam >> 16);
2133 if (g_lastWindow->m_mouseCallbacksEnabled) g_lastWindow->MouseMoveCallback();
2134 */// goto winmessage;
2137 case WM_SYSCOMMAND: // Intercept System Commands
2139 switch (wParam) // Check System Calls
2141 case SC_SCREENSAVE: // Screensaver Trying To Start?
2142 case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
2143 return 0; // Prevent From Happening
2145 // User trying to access application menu using ALT?
2154 // ReleaseCapture();
2155 // ClipMouseToWindow(hWnd);
2172 PostQuitMessage(0); /* Terminate Application */
2180 // BeginPaint( g_windowHandle,&ps);
2181 // EndPaint( g_windowHandle,&ps);
2188 /* We processed the message and there
2189 * is no processing by Windows necessary */
2191 /* We didn't process the message so let Windows do it */
2192 return DefWindowProc(hWnd,msg,wParam,lParam);
2196 static BOOL RegisterWindowClasses(HINSTANCE hFirstInstance)
2199 memset( &wc, 0, sizeof( wc));
2201 /* Register the window class. */
2202 wc.cbSize = sizeof(wc);
2204 wc.style = (CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_OWNDC); /* Combination of Class Styles */
2205 wc.lpfnWndProc = AppWndProc; /* Adress of Window Procedure */
2206 wc.cbClsExtra = 0; /* Extra Bytes allocated for this Class */
2207 wc.cbWndExtra = 0; /* Extra Bytes allocated for each Window */
2208 wc.hInstance = hFirstInstance; /* Handle of program instance */
2209 wc.hIcon = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2210 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2211 wc.hbrBackground = NULL;
2212 wc.lpszMenuName = NULL;
2213 wc.lpszClassName = g_wndClassName; /* Name of the Window Class */
2214 wc.hIconSm = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2216 if (!RegisterClassEx(&wc)) return FALSE; /* Register Class failed */
2222 int resolutionID(int width, int height)
2226 if(width==640 && height==480)whichres=0;
2227 if(width==800 && height==600)whichres=1;
2228 if(width==1024 && height==768)whichres=2;
2229 if(width==1280 && height==1024)whichres=3;
2230 if(width==1600 && height==1200)whichres=4;
2231 if(width==840 && height==524)whichres=5;
2232 if(width==1024 && height==640)whichres=6;
2233 if(width==1344 && height==840)whichres=7;
2234 if(width==1920 && height==1200)whichres=8;
2239 int closestResolution(int width, int height)
2243 if(width>=640 && height>=480)whichres=0;
2244 if(width>=800 && height>=600)whichres=1;
2245 if(width>=1024 && height>=768)whichres=2;
2246 if(width>=1280 && height>=1024)whichres=3;
2247 if(width>=1600 && height>=1200)whichres=4;
2248 if(width==840 && height==524)whichres=5;
2249 if(width==1024 && height==640)whichres=6;
2250 if(width==1344 && height==840)whichres=7;
2251 if(width>=1920 && height>=1200)whichres=8;
2256 bool selectDetail(int & width, int & height, int & bpp, int & detail)
2259 int whichres = closestResolution(width, height);
2263 if(whichres<=0 || whichres>8){
2301 // currently with SDL, we just use whatever the native bitdepth
2302 // of the display is and don't care.
2307 if ((detail != 0) && (resolutionDepths[whichres][1] != 0))
2311 else if ((detail == 0) && (resolutionDepths[whichres][0] != 0))
2315 else if ((detail != 0) && (resolutionDepths[whichres][0] != 0))
2331 bpp = resolutionDepths[whichres][(detail != 0)];
2337 int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
2340 LPWSTR * cl = CommandLineToArgvW(GetCommandLineW(), &argc);
2343 if (0 == _wcsicmp(cl[1], L"-windowed"))
2351 memset( &g_theKeys, 0, sizeof( KeyMap));
2355 memset(&mode, 0, sizeof(mode));
2356 mode.dmSize = sizeof(mode);
2357 while (EnumDisplaySettings(NULL, i++, &mode))
2359 if (mode.dmBitsPerPel < 16)
2364 int res = resolutionID(mode.dmPelsWidth, mode.dmPelsHeight);
2366 if (res > -1 && res < 8)
2368 if (DISP_CHANGE_SUCCESSFUL != ChangeDisplaySettings(&mode, CDS_TEST))
2373 switch(mode.dmBitsPerPel)
2377 resolutionDepths[res][1] = mode.dmBitsPerPel;
2380 resolutionDepths[res][0] = mode.dmBitsPerPel;
2386 /* if there is no Instance of our program in memory then register the window class */
2387 if (hPrevInstance == NULL && !RegisterWindowClasses(hInstance))
2388 return FALSE; /* registration failed! */
2390 g_appInstance=hInstance;
2394 UnregisterClass( g_wndClassName, hInstance);
2401 extern int channels[100];
2402 extern FSOUND_SAMPLE * samp[100];
2403 extern FSOUND_STREAM * strm[20];
2405 extern "C" void PlaySoundEx(int chan, FSOUND_SAMPLE *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2407 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2408 if (currSample && currSample == samp[chan])
2410 if (FSOUND_GetPaused(channels[chan]))
2412 FSOUND_StopSound(channels[chan]);
2413 channels[chan] = FSOUND_FREE;
2415 else if (FSOUND_IsPlaying(channels[chan]))
2417 int loop_mode = FSOUND_GetLoopMode(channels[chan]);
2418 if (loop_mode & FSOUND_LOOP_OFF)
2420 channels[chan] = FSOUND_FREE;
2426 channels[chan] = FSOUND_FREE;
2429 channels[chan] = FSOUND_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
2430 if (channels[chan] < 0)
2432 channels[chan] = FSOUND_PlaySoundEx(FSOUND_FREE, sptr, dsp, startpaused);
2436 extern "C" void PlayStreamEx(int chan, FSOUND_STREAM *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2438 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2439 if (currSample && currSample == FSOUND_Stream_GetSample(sptr))
2441 FSOUND_StopSound(channels[chan]);
2442 FSOUND_Stream_Stop(sptr);
2446 FSOUND_Stream_Stop(sptr);
2447 channels[chan] = FSOUND_FREE;
2450 channels[chan] = FSOUND_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
2451 if (channels[chan] < 0)
2453 channels[chan] = FSOUND_Stream_PlayEx(FSOUND_FREE, sptr, dsp, startpaused);
2457 bool LoadImage(const char * fname, TGAImageRec & tex)
2461 if ( tex.data == NULL )
2467 ILstring f = strdup(ConvertFileName(fname));
2474 ilGenImages(1, &iid);
2479 tex.sizeX = ilGetInteger(IL_IMAGE_WIDTH);
2480 tex.sizeY = ilGetInteger(IL_IMAGE_HEIGHT);
2481 tex.bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
2482 ILuint Bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL),
2483 imageSize = tex.sizeX * tex.sizeY * Bpp;
2484 ILubyte *Data = ilGetData();
2485 memcpy(tex.data, Data, imageSize);
2487 // Truvision Targa files are stored as BGR colors
2488 // We want RGB so Blue and Red bytes are switched
2489 if (IL_TGA == ilGetInteger(IL_IMAGE_FORMAT))
2491 // Loop Through The Image Data
2492 for (GLuint i = 0; i < int(imageSize); i += Bpp)
2494 // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
2495 GLbyte temp; // Temporary Variable
2496 temp = tex.data[i]; // Temporarily Store The Value At Image Data 'i'
2497 tex.data[i] = tex.data[i + 2]; // Set The 1st Byte To The Value Of The 3rd Byte
2498 tex.data[i + 2] = temp; // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
2506 ilDeleteImages(1, &iid);
2510 GLuint texid = ilutGLLoadImage(f);
2515 ilutGLBuildMipmaps()
2524 res = load_image(fname, tex);
2525 //if (!res) printf("failed to load %s\n", fname);
2531 void ScreenShot(const char * fname)
2534 ILstring f = strdup(fname);
2541 ilGenImages(1, &iid);
2547 ilDeleteImages(1, &iid);
2557 static bool load_image(const char *file_name, TGAImageRec &tex)
2559 char *ptr = strrchr(file_name, '.');
2562 if (stricmp(ptr+1, "png") == 0)
2563 return load_png(file_name, tex);
2564 else if (stricmp(ptr+1, "jpg") == 0)
2565 return load_jpg(file_name, tex);
2568 STUBBED("Unsupported image type");
2573 struct my_error_mgr {
2574 struct jpeg_error_mgr pub; /* "public" fields */
2575 jmp_buf setjmp_buffer; /* for return to caller */
2577 typedef struct my_error_mgr * my_error_ptr;
2580 static void my_error_exit(j_common_ptr cinfo)
2582 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
2583 longjmp(err->setjmp_buffer, 1);
2586 /* stolen from public domain example.c code in libjpg distribution. */
2587 static bool load_jpg(const char *file_name, TGAImageRec &tex)
2589 struct jpeg_decompress_struct cinfo;
2590 struct my_error_mgr jerr;
2591 JSAMPROW buffer[1]; /* Output row buffer */
2592 int row_stride; /* physical row width in output buffer */
2593 FILE *infile = fopen(file_name, "rb");
2598 cinfo.err = jpeg_std_error(&jerr.pub);
2599 jerr.pub.error_exit = my_error_exit;
2600 if (setjmp(jerr.setjmp_buffer)) {
2601 jpeg_destroy_decompress(&cinfo);
2606 jpeg_create_decompress(&cinfo);
2607 jpeg_stdio_src(&cinfo, infile);
2608 (void) jpeg_read_header(&cinfo, TRUE);
2610 cinfo.out_color_space = JCS_RGB;
2611 cinfo.quantize_colors = 0;
2612 (void) jpeg_calc_output_dimensions(&cinfo);
2613 (void) jpeg_start_decompress(&cinfo);
2615 row_stride = cinfo.output_width * cinfo.output_components;
2616 tex.sizeX = cinfo.output_width;
2617 tex.sizeY = cinfo.output_height;
2620 while (cinfo.output_scanline < cinfo.output_height) {
2621 buffer[0] = (JSAMPROW)(char *)tex.data +
2622 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
2623 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
2626 (void) jpeg_finish_decompress(&cinfo);
2627 jpeg_destroy_decompress(&cinfo);
2634 /* stolen from public domain example.c code in libpng distribution. */
2635 static bool load_png(const char *file_name, TGAImageRec &tex)
2637 bool hasalpha = false;
2638 png_structp png_ptr = NULL;
2639 png_infop info_ptr = NULL;
2640 png_uint_32 width, height;
2641 int bit_depth, color_type, interlace_type;
2642 png_byte **rows = NULL;
2643 bool retval = false;
2644 png_byte **row_pointers = NULL;
2645 FILE *fp = fopen(file_name, "rb");
2650 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2651 if (png_ptr == NULL)
2654 info_ptr = png_create_info_struct(png_ptr);
2655 if (info_ptr == NULL)
2658 if (setjmp(png_jmpbuf(png_ptr)))
2661 png_init_io(png_ptr, fp);
2662 png_read_png(png_ptr, info_ptr,
2663 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
2665 png_get_IHDR(png_ptr, info_ptr, &width, &height,
2666 &bit_depth, &color_type, &interlace_type, NULL, NULL);
2668 if (bit_depth != 8) // transform SHOULD handle this...
2671 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
2674 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
2677 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
2678 row_pointers = png_get_rows(png_ptr, info_ptr);
2684 png_byte *dst = tex.data;
2685 for (int i = height-1; i >= 0; i--)
2687 png_byte *src = row_pointers[i];
2688 for (int j = 0; j < width; j++)
2702 png_byte *dst = tex.data;
2703 int pitch = width * 4;
2704 for (int i = height-1; i >= 0; i--, dst += pitch)
2705 memcpy(dst, row_pointers[i], pitch);
2714 png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
2721 static bool save_image(const char *file_name)
2723 char *ptr = strrchr(file_name, '.');
2726 if (stricmp(ptr+1, "png") == 0)
2727 return save_png(file_name);
2730 STUBBED("Unsupported image type");
2735 static bool save_png(const char *file_name)
2738 png_structp png_ptr = NULL;
2739 png_infop info_ptr = NULL;
2740 bool retval = false;
2742 fp = fopen(file_name, "wb");
2746 png_bytep *row_pointers = new png_bytep[kContextHeight];
2747 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
2748 if ((!screenshot) || (!row_pointers))
2752 glReadPixels(0, 0, kContextWidth, kContextHeight,
2753 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
2754 if (glGetError() != GL_NO_ERROR)
2757 for (int i = 0; i < kContextHeight; i++)
2758 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
2760 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2761 if (png_ptr == NULL)
2764 info_ptr = png_create_info_struct(png_ptr);
2765 if (info_ptr == NULL)
2768 if (setjmp(png_jmpbuf(png_ptr)))
2771 png_init_io(png_ptr, fp);
2773 if (setjmp(png_jmpbuf(png_ptr)))
2776 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
2777 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
2778 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2780 png_write_info(png_ptr, info_ptr);
2782 if (setjmp(png_jmpbuf(png_ptr)))
2785 png_write_image(png_ptr, row_pointers);
2787 if (setjmp(png_jmpbuf(png_ptr)))
2790 png_write_end(png_ptr, NULL);
2794 png_destroy_write_struct(&png_ptr, &info_ptr);
2795 delete[] screenshot;
2796 delete[] row_pointers;
2800 unlink(ConvertFileName(file_name));