]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
Merged FMod changes in
[lugaru.git] / Source / OpenGL_Windows.cpp
1 /*
2 Copyright (C) 2003, 2010 - Wolfire Games
3
4 This file is part of Lugaru.
5
6 Lugaru is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 */
21
22 #ifdef WIN32
23 #define UINT8 WIN32API_UINT8
24 #define UINT16 WIN32API_UINT16
25 #define boolean WIN32API_boolean
26 #include <windows.h>
27 #undef UINT8
28 #undef UINT16
29 #undef boolean
30 #endif
31
32 #define USE_DEVIL 0
33
34 #ifndef USE_DEVIL
35 #  ifdef WIN32
36 #    define USE_DEVIL
37 #  endif
38 #endif
39
40 #if USE_DEVIL
41     #include "IL/il.h"
42     #include "IL/ilu.h"
43     #include "IL/ilut.h"
44         #include "Game.h"
45 #else
46
47         #include "Game.h"
48         extern "C" {
49                 #include "zlib.h"
50                 #include "png.h"
51                 #include "jpeglib.h"
52         }
53
54     static bool load_image(const char * fname, TGAImageRec & tex);
55     static bool load_png(const char * fname, TGAImageRec & tex);
56     static bool load_jpg(const char * fname, TGAImageRec & tex);
57     static bool save_image(const char * fname);
58     static bool save_png(const char * fname);
59 #endif
60
61 #include "openal_wrapper.h"
62
63 // ADDED GWC
64 #ifdef _MSC_VER
65 #pragma comment(lib, "opengl32.lib")
66 #pragma comment(lib, "glu32.lib")
67 #pragma comment(lib, "glaux.lib")
68 #endif
69
70 extern bool buttons[3];
71 extern float multiplier;
72 extern float screenwidth,screenheight;
73 extern float sps;
74 extern float realmultiplier;
75 extern int slomo;
76 extern bool ismotionblur;
77 extern float usermousesensitivity;
78 extern int detail;
79 extern bool floatjump;
80 extern bool cellophane;
81 // MODIFIED GWC
82 //extern int terraindetail;
83 //extern int texdetail;
84 extern float terraindetail;
85 extern float texdetail;
86 extern int bloodtoggle;
87 extern bool osx;
88 extern bool autoslomo;
89 extern bool foliage;
90 extern bool musictoggle;
91 extern bool trilinear;
92 extern float gamespeed;
93 extern int difficulty;
94 extern bool damageeffects;
95 extern int numplayers;
96 extern bool decals;
97 extern bool invertmouse;
98 extern bool texttoggle;
99 extern bool ambientsound;
100 extern bool mousejump;
101 extern bool freeze;
102 extern Person player[maxplayers];
103 extern bool vblsync;
104 extern bool stillloading;
105 extern bool showpoints;
106 extern bool alwaysblur;
107 extern bool immediate;
108 extern bool velocityblur;
109 extern bool debugmode;
110 extern int mainmenu;
111 /*extern*/ bool gameFocused;
112 extern int kBitsPerPixel;
113 extern float slomospeed;
114 extern float slomofreq;
115 extern float oldgamespeed;
116 extern float volume;
117
118 #include <math.h>
119 #include <stdio.h>
120 #include <string.h>
121 #include <fstream>
122 #include <iostream>
123 #include "gamegl.h"
124 #include "MacCompatibility.h"
125
126 #ifdef WIN32
127 #include <shellapi.h>
128 #endif
129
130 #include "fmod.h"
131
132 #include "res/resource.h"
133
134 using namespace std;
135
136
137 #if USE_SDL
138 SDL_Rect **resolutions = NULL;
139 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
140 static SDL_Rect rect_800_600  = { 0, 0, 800,  600 };
141 static SDL_Rect rect_640_480  = { 0, 0, 640,  480 };
142 static SDL_Rect *hardcoded_resolutions[] = {
143     &rect_1024_768,
144     &rect_800_600,
145     &rect_640_480,
146     NULL
147 };
148 #endif
149
150
151 unsigned int resolutionDepths[8][2] = {0};
152
153 bool selectDetail(int & width, int & height, int & bpp, int & detail);
154 int closestResolution(int width, int height);
155 int resolutionID(int width, int height);
156
157 void ReportError (char * strError);
158
159 void SetupDSpFullScreen();
160 void ShutdownDSp();
161
162 void DrawGL(Game & game);
163
164 void CreateGLWindow (void);
165 Boolean SetUp (Game & game);
166 void DoKey (SInt8 theKey, SInt8 theCode);
167 void DoUpdate (Game & game);
168
169 void DoEvent (void);
170 void CleanUp (void);
171
172
173 // statics/globals (internal only) ------------------------------------------
174 #ifndef WIN32
175 typedef struct tagPOINT { 
176   int x;
177   int y;
178 } POINT, *PPOINT; 
179 #endif
180
181 #if USE_SDL
182
183 #ifdef _MSC_VER
184 #pragma warning(push)
185 #pragma warning(disable: 4273)
186 #endif
187
188 #define GL_FUNC(ret,fn,params,call,rt) \
189     extern "C" { \
190         static ret (GLAPIENTRY *p##fn) params = NULL; \
191         ret GLAPIENTRY fn params { rt p##fn call; } \
192     }
193 #include "glstubs.h"
194 #undef GL_FUNC
195
196 #ifdef _MSC_VER
197 #pragma warning(pop)
198 #endif
199
200 static bool lookup_glsym(const char *funcname, void **func)
201 {
202     *func = SDL_GL_GetProcAddress(funcname);
203     if (*func == NULL)
204     {
205         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
206         return false;
207     }
208     return true;
209 }
210
211 static bool lookup_all_glsyms(void)
212 {
213     bool retval = true;
214     #define GL_FUNC(ret,fn,params,call,rt) \
215         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
216     #include "glstubs.h"
217     #undef GL_FUNC
218     return retval;
219 }
220
221 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
222 {
223     // no-op.
224 }
225
226
227
228 void sdlGetCursorPos(POINT *pt)
229 {
230     int x, y;
231     SDL_GetMouseState(&x, &y);
232     pt->x = x;
233     pt->y = y;
234 }
235 #define GetCursorPos(x) sdlGetCursorPos(x)
236 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
237 #define ScreenToClient(x, pt)
238 #define ClientToScreen(x, pt)
239 #ifdef MessageBox
240 #undef MessageBox
241 #endif
242 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
243 #endif
244
245 Point delta;
246
247 static bool g_button, fullscreen = true;
248
249
250 // Menu defs
251 enum 
252 {
253         kFileQuit = 1
254 };
255
256 enum 
257 {
258         kForegroundSleep = 10,
259         kBackgroundSleep = 10000
260 };
261
262
263 int kContextWidth;
264 int kContextHeight;
265
266 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
267
268 GLuint gFontList;
269 char gcstrMode [256] = "";
270
271 UInt32 gSleepTime = kForegroundSleep;
272 Boolean gDone = false, gfFrontProcess = true;
273
274 Game * pgame = 0;
275
276 #ifndef __MINGW32__
277 static int _argc = 0;
278 static char **_argv = NULL;
279 #endif
280
281 bool cmdline(const char *cmd)
282 {
283     for (int i = 1; i < _argc; i++)
284     {
285         char *arg = _argv[i];
286         while (*arg == '-')
287             arg++;
288         if (strcasecmp(arg, cmd) == 0)
289             return true;
290     }
291
292     return false;
293 }
294
295
296 // --------------------------------------------------------------------------
297
298 void ReportError (char * strError)
299 {
300 #ifdef _MSC_VER  // !!! FIXME.  --ryan.
301         throw std::exception( strError);
302 #endif
303
304         /*      char errMsgCStr [256];
305         Str255 strErr;
306
307         sprintf (errMsgCStr, "%s", strError); 
308
309         // out as debug string
310         CToPStr (strErr, errMsgCStr);
311         DebugStr (strErr);
312         */
313 }
314
315 void SetupDSpFullScreen ()
316 {
317 }
318
319
320 void ShutdownDSp ()
321 {
322 }
323
324
325 //-----------------------------------------------------------------------------------------------------------------------
326
327 // OpenGL Drawing
328
329 void DrawGL (Game & game)
330 {
331         game.DrawGLScene();
332 }
333
334
335 static KeyMap g_theKeys;
336
337 void SetKey( int key)
338 {
339     g_theKeys[ key >> 3] |= (1 << (key & 7));
340 }
341
342 void ClearKey( int key)
343 {
344     g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
345 }
346
347 void GetKeys(  unsigned char theKeys[16])
348 {
349     memcpy( theKeys, &g_theKeys, 16);
350 }
351
352 Boolean Button()
353 {
354     return g_button;
355 }
356
357 #if !USE_SDL
358 static void initSDLKeyTable(void) {}
359 #else
360 #define MAX_SDLKEYS SDLK_LAST
361 static unsigned short KeyTable[MAX_SDLKEYS];
362
363 static void initSDLKeyTable(void)
364 {
365     memset(KeyTable, 0xFF, sizeof (KeyTable));
366     KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
367     KeyTable[SDLK_TAB] = MAC_TAB_KEY;
368     KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
369     KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
370     KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
371     KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
372     KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
373     KeyTable[SDLK_END] = MAC_END_KEY;
374     KeyTable[SDLK_HOME] = MAC_HOME_KEY;
375     KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
376     KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
377     KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
378     KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
379     KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
380     KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
381     KeyTable[SDLK_0] = MAC_0_KEY;
382     KeyTable[SDLK_1] = MAC_1_KEY;
383     KeyTable[SDLK_2] = MAC_2_KEY;
384     KeyTable[SDLK_3] = MAC_3_KEY;
385     KeyTable[SDLK_4] = MAC_4_KEY;
386     KeyTable[SDLK_5] = MAC_5_KEY;
387     KeyTable[SDLK_6] = MAC_6_KEY;
388     KeyTable[SDLK_7] = MAC_7_KEY;
389     KeyTable[SDLK_8] = MAC_8_KEY;
390     KeyTable[SDLK_9] = MAC_9_KEY;
391     KeyTable[SDLK_a] = MAC_A_KEY;
392     KeyTable[SDLK_b] = MAC_B_KEY;
393     KeyTable[SDLK_c] = MAC_C_KEY;
394     KeyTable[SDLK_d] = MAC_D_KEY;
395     KeyTable[SDLK_e] = MAC_E_KEY;
396     KeyTable[SDLK_f] = MAC_F_KEY;
397     KeyTable[SDLK_g] = MAC_G_KEY;
398     KeyTable[SDLK_h] = MAC_H_KEY;
399     KeyTable[SDLK_i] = MAC_I_KEY;
400     KeyTable[SDLK_j] = MAC_J_KEY;
401     KeyTable[SDLK_k] = MAC_K_KEY;
402     KeyTable[SDLK_l] = MAC_L_KEY;
403     KeyTable[SDLK_m] = MAC_M_KEY;
404     KeyTable[SDLK_n] = MAC_N_KEY;
405     KeyTable[SDLK_o] = MAC_O_KEY;
406     KeyTable[SDLK_p] = MAC_P_KEY;
407     KeyTable[SDLK_q] = MAC_Q_KEY;
408     KeyTable[SDLK_r] = MAC_R_KEY;
409     KeyTable[SDLK_s] = MAC_S_KEY;
410     KeyTable[SDLK_t] = MAC_T_KEY;
411     KeyTable[SDLK_u] = MAC_U_KEY;
412     KeyTable[SDLK_v] = MAC_V_KEY;
413     KeyTable[SDLK_w] = MAC_W_KEY;
414     KeyTable[SDLK_x] = MAC_X_KEY;
415     KeyTable[SDLK_y] = MAC_Y_KEY;
416     KeyTable[SDLK_z] = MAC_Z_KEY;
417     KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
418     KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
419     KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
420     KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
421     KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
422     KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
423     KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
424     KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
425     KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
426     KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
427     KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
428     KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
429     KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
430     KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
431     KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
432     KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
433     KeyTable[SDLK_F1] = MAC_F1_KEY;
434     KeyTable[SDLK_F2] = MAC_F2_KEY;
435     KeyTable[SDLK_F3] = MAC_F3_KEY;
436     KeyTable[SDLK_F4] = MAC_F4_KEY;
437     KeyTable[SDLK_F5] = MAC_F5_KEY;
438     KeyTable[SDLK_F6] = MAC_F6_KEY;
439     KeyTable[SDLK_F7] = MAC_F7_KEY;
440     KeyTable[SDLK_F8] = MAC_F8_KEY;
441     KeyTable[SDLK_F9] = MAC_F9_KEY;
442     KeyTable[SDLK_F10] = MAC_F10_KEY;
443     KeyTable[SDLK_F11] = MAC_F11_KEY;
444     KeyTable[SDLK_F12] = MAC_F12_KEY;
445     KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
446     KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
447     KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
448     KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
449     KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
450     KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
451     KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
452     KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
453     KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
454     KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
455     KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
456 }
457
458 static inline int clamp_sdl_mouse_button(Uint8 button)
459 {
460     if (button == 2)   // right mouse button is button 3 in SDL.
461         button = 3;
462     else if (button == 3)
463         button = 2;
464
465     if ((button >= 1) && (button <= 3))
466         return button - 1;
467     return -1;
468 }
469
470 static void sdlEventProc(const SDL_Event &e, Game &game)
471 {
472     int val;
473     bool skipkey = false;
474     SDLMod mod;
475
476     switch(e.type)
477         {
478         case SDL_MOUSEMOTION:
479             game.deltah += e.motion.xrel;
480             game.deltav += e.motion.yrel;
481             return;
482
483                 case SDL_MOUSEBUTTONDOWN:
484                         {
485                 val = clamp_sdl_mouse_button(e.button.button);
486                 if ((val >= 0) && (val <= 2))
487                 {
488                     if (val == 0)
489                                     g_button = true;
490                                 buttons[val] = true;
491                 }
492                         }
493                         return;
494
495                 case SDL_MOUSEBUTTONUP:
496                         {
497                 val = clamp_sdl_mouse_button(e.button.button);
498                 if ((val >= 0) && (val <= 2))
499                 {
500                     if (val == 0)
501                                     g_button = false;
502                                 buttons[val] = false;
503                 }
504                         }
505             return;
506
507         case SDL_KEYDOWN:
508             if (e.key.keysym.sym == SDLK_g)
509             {
510                 if (e.key.keysym.mod & KMOD_CTRL)
511                 {
512                     skipkey = true;
513                     SDL_GrabMode mode = SDL_GRAB_ON;
514                     if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
515                     {
516                         mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
517                         mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
518                     }
519                     SDL_WM_GrabInput(mode);
520                 }
521             }
522
523             else if (e.key.keysym.sym == SDLK_RETURN)
524             {
525                 if (e.key.keysym.mod & KMOD_ALT)
526                 {
527                     skipkey = true;
528                     SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
529                 }
530             }
531
532             if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
533             {
534                 if (KeyTable[e.key.keysym.sym] != 0xffff)
535                     SetKey(KeyTable[e.key.keysym.sym]);
536             }
537
538             mod = SDL_GetModState();
539             if (mod & KMOD_CTRL)
540                 SetKey(MAC_CONTROL_KEY);
541             if (mod & KMOD_ALT)
542                 SetKey(MAC_OPTION_KEY);
543             if (mod & KMOD_META)
544                 SetKey(MAC_COMMAND_KEY);
545             if (mod & KMOD_SHIFT)
546                 SetKey(MAC_SHIFT_KEY);
547             if (mod & KMOD_CAPS)
548                 SetKey(MAC_CAPS_LOCK_KEY);
549
550             return;
551
552         case SDL_KEYUP:
553             if (e.key.keysym.sym < SDLK_LAST)
554             {
555                 if (KeyTable[e.key.keysym.sym] != 0xffff)
556                     ClearKey(KeyTable[e.key.keysym.sym]);
557             }
558
559             mod = SDL_GetModState();
560             if ((mod & KMOD_CTRL) == 0)
561                 ClearKey(MAC_CONTROL_KEY);
562             if ((mod & KMOD_ALT) == 0)
563                 ClearKey(MAC_OPTION_KEY);
564             if ((mod & KMOD_META) == 0)
565                 ClearKey(MAC_COMMAND_KEY);
566             if ((mod & KMOD_SHIFT) == 0)
567                 ClearKey(MAC_SHIFT_KEY);
568             if ((mod & KMOD_CAPS) == 0)
569                 ClearKey(MAC_CAPS_LOCK_KEY);
570             return;
571     }
572 }
573 #endif
574
575 // --------------------------------------------------------------------------
576
577 static Point gMidPoint;
578
579 Boolean SetUp (Game & game)
580 {
581         char string[10];
582
583         LOGFUNC;
584
585         randSeed = UpTime().lo;
586
587         osx = 0;
588         ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
589         detail=1;
590         ismotionblur=0;
591         usermousesensitivity=1;
592         kContextWidth=640;
593         kContextHeight=480;
594         kBitsPerPixel = 32;
595         floatjump=0;
596         cellophane=0;
597         texdetail=4;
598         autoslomo=1;
599         decals=1;
600         invertmouse=0;
601         bloodtoggle=0;
602         terraindetail=2;
603         foliage=1;
604         musictoggle=1;
605         trilinear=1;
606         gamespeed=1;
607         difficulty=1;
608         damageeffects=0;
609         texttoggle=1;
610         alwaysblur=0;
611         showpoints=0;
612         immediate=0;
613         velocityblur=0;
614
615         slomospeed=0.25;
616         slomofreq=8012;
617
618         volume = 0.8f;
619
620         game.crouchkey=MAC_SHIFT_KEY;
621         game.jumpkey=MAC_SPACE_KEY;
622         game.leftkey=MAC_A_KEY;
623         game.forwardkey=MAC_W_KEY;
624         game.backkey=MAC_S_KEY;
625         game.rightkey=MAC_D_KEY;
626         game.drawkey=MAC_E_KEY;
627         game.throwkey=MAC_Q_KEY;
628         game.attackkey=MAC_MOUSEBUTTON1;
629         game.chatkey=MAC_T_KEY;
630         numplayers=1;
631         ambientsound=1;
632         vblsync=0;
633         debugmode=0;
634
635         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
636
637         if(!ipstream) {
638                 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
639                 opstream << "Screenwidth:\n";
640                 opstream << kContextWidth;
641                 opstream << "\nScreenheight:\n";
642                 opstream << kContextHeight;
643                 opstream << "\nMouse sensitivity:\n";
644                 opstream << usermousesensitivity;
645                 opstream << "\nBlur(0,1):\n";
646                 opstream << ismotionblur;
647                 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
648                 opstream << detail;
649                 opstream << "\nFloating jump:\n";
650                 opstream << floatjump;
651                 opstream << "\nMouse jump:\n";
652                 opstream << mousejump;
653                 opstream << "\nAmbient sound:\n";
654                 opstream << ambientsound;
655                 opstream << "\nBlood (0,1,2):\n";
656                 opstream << bloodtoggle;
657                 opstream << "\nAuto slomo:\n";
658                 opstream << autoslomo;
659                 opstream << "\nFoliage:\n";
660                 opstream << foliage;
661                 opstream << "\nMusic:\n";
662                 opstream << musictoggle;
663                 opstream << "\nTrilinear:\n";
664                 opstream << trilinear;
665                 opstream << "\nDecals(shadows,blood puddles,etc):\n";
666                 opstream << decals;
667                 opstream << "\nInvert mouse:\n";
668                 opstream << invertmouse;
669                 opstream << "\nGamespeed:\n";
670                 opstream << gamespeed;
671                 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
672                 opstream << difficulty;
673                 opstream << "\nDamage effects(blackout, doublevision):\n";
674                 opstream << damageeffects;
675                 opstream << "\nText:\n";
676                 opstream << texttoggle;
677                 opstream << "\nDebug:\n";
678                 opstream << debugmode;
679                 opstream << "\nVBL Sync:\n";
680                 opstream << vblsync;
681                 opstream << "\nShow Points:\n";
682                 opstream << showpoints;
683                 opstream << "\nAlways Blur:\n";
684                 opstream << alwaysblur;
685                 opstream << "\nImmediate mode (turn on on G5):\n";
686                 opstream << immediate;
687                 opstream << "\nVelocity blur:\n";
688                 opstream << velocityblur;
689                 opstream << "\nVolume:\n";
690                 opstream << volume;
691                 opstream << "\nForward key:\n";
692                 opstream << KeyToChar(game.forwardkey);
693                 opstream << "\nBack key:\n";
694                 opstream << KeyToChar(game.backkey);
695                 opstream << "\nLeft key:\n";
696                 opstream << KeyToChar(game.leftkey);
697                 opstream << "\nRight key:\n";
698                 opstream << KeyToChar(game.rightkey);
699                 opstream << "\nJump key:\n";
700                 opstream << KeyToChar(game.jumpkey);
701                 opstream << "\nCrouch key:\n";
702                 opstream << KeyToChar(game.crouchkey);
703                 opstream << "\nDraw key:\n";
704                 opstream << KeyToChar(game.drawkey);
705                 opstream << "\nThrow key:\n";
706                 opstream << KeyToChar(game.throwkey);
707                 opstream << "\nAttack key:\n";
708                 opstream << KeyToChar(game.attackkey);
709                 opstream << "\nChat key:\n";
710                 opstream << KeyToChar(game.chatkey);
711                 opstream.close();
712         }
713         if(ipstream){
714                 int i;
715                 ipstream.ignore(256,'\n');
716                 ipstream >> kContextWidth;
717                 ipstream.ignore(256,'\n');
718                 ipstream.ignore(256,'\n');
719                 ipstream >> kContextHeight;
720                 ipstream.ignore(256,'\n');
721                 ipstream.ignore(256,'\n');
722                 ipstream >> usermousesensitivity;
723                 ipstream.ignore(256,'\n');
724                 ipstream.ignore(256,'\n');
725                 ipstream >> i;
726                 ismotionblur = (i != 0);
727                 ipstream.ignore(256,'\n');
728                 ipstream.ignore(256,'\n');
729                 ipstream >> detail;
730                 if(detail!=0)kBitsPerPixel=32;
731                 else kBitsPerPixel=16;
732                 ipstream.ignore(256,'\n');
733                 ipstream.ignore(256,'\n');
734                 ipstream >> i;
735                 floatjump = (i != 0);
736                 ipstream.ignore(256,'\n');
737                 ipstream.ignore(256,'\n');
738                 ipstream >> i;
739                 mousejump = (i != 0);
740                 ipstream.ignore(256,'\n');
741                 ipstream.ignore(256,'\n');
742                 ipstream >> i;
743                 ambientsound = (i != 0);
744                 ipstream.ignore(256,'\n');
745                 ipstream.ignore(256,'\n');
746                 ipstream >> bloodtoggle;
747                 ipstream.ignore(256,'\n');
748                 ipstream.ignore(256,'\n');
749                 ipstream >> i;
750                 autoslomo = (i != 0);
751                 ipstream.ignore(256,'\n');
752                 ipstream.ignore(256,'\n');
753                 ipstream >> i;
754                 foliage = (i != 0);
755                 ipstream.ignore(256,'\n');
756                 ipstream.ignore(256,'\n');
757                 ipstream >> i;
758                 musictoggle = (i != 0);
759                 ipstream.ignore(256,'\n');
760                 ipstream.ignore(256,'\n');
761                 ipstream >> i;
762                 trilinear = (i != 0);
763                 ipstream.ignore(256,'\n');
764                 ipstream.ignore(256,'\n');
765                 ipstream >> i;
766                 decals = (i != 0);
767                 ipstream.ignore(256,'\n');
768                 ipstream.ignore(256,'\n');
769                 ipstream >> i;
770                 invertmouse = (i != 0);
771                 ipstream.ignore(256,'\n');
772                 ipstream.ignore(256,'\n');
773                 ipstream >> gamespeed;
774                 oldgamespeed=gamespeed;
775                 if(oldgamespeed==0){
776                         gamespeed=1;
777                         oldgamespeed=1;
778                 }
779                 ipstream.ignore(256,'\n');
780                 ipstream.ignore(256,'\n');
781                 ipstream >> difficulty;
782                 ipstream.ignore(256,'\n');
783                 ipstream.ignore(256,'\n');
784                 ipstream >> i;
785                 damageeffects = (i != 0);
786                 ipstream.ignore(256,'\n');
787                 ipstream.ignore(256,'\n');
788                 ipstream >> i;
789                 texttoggle = (i != 0);
790                 ipstream.ignore(256,'\n');
791                 ipstream.ignore(256,'\n');
792                 ipstream >> i;
793                 debugmode = (i != 0);
794                 ipstream.ignore(256,'\n');
795                 ipstream.ignore(256,'\n');
796                 ipstream >> i;
797                 vblsync = (i != 0);
798                 ipstream.ignore(256,'\n');
799                 ipstream.ignore(256,'\n');
800                 ipstream >> i;
801                 showpoints = (i != 0);
802                 ipstream.ignore(256,'\n');
803                 ipstream.ignore(256,'\n');
804                 ipstream >> i;
805                 alwaysblur = (i != 0);
806                 ipstream.ignore(256,'\n');
807                 ipstream.ignore(256,'\n');
808                 ipstream >> i;
809                 immediate = (i != 0);
810                 ipstream.ignore(256,'\n');
811                 ipstream.ignore(256,'\n');
812                 ipstream >> i;
813                 velocityblur = (i != 0);
814                 ipstream.ignore(256,'\n');
815                 ipstream.ignore(256,'\n'); 
816                 ipstream >> volume;
817                 ipstream.ignore(256,'\n');
818                 ipstream.ignore(256,'\n'); 
819                 ipstream >> string;
820                 game.forwardkey=CharToKey(string);
821                 ipstream.ignore(256,'\n');
822                 ipstream.ignore(256,'\n');
823                 ipstream >> string;
824                 game.backkey=CharToKey(string);
825                 ipstream.ignore(256,'\n');
826                 ipstream.ignore(256,'\n');
827                 ipstream >> string;
828                 game.leftkey=CharToKey(string);
829                 ipstream.ignore(256,'\n');
830                 ipstream.ignore(256,'\n');
831                 ipstream >> string;
832                 game.rightkey=CharToKey(string);
833                 ipstream.ignore(256,'\n');
834                 ipstream.ignore(256,'\n');
835                 ipstream >> string;
836                 game.jumpkey=CharToKey(string);
837                 ipstream.ignore(256,'\n');
838                 ipstream.ignore(256,'\n');
839                 ipstream >> string;
840                 game.crouchkey=CharToKey(string);
841                 ipstream.ignore(256,'\n');
842                 ipstream.ignore(256,'\n');
843                 ipstream >> string;
844                 game.drawkey=CharToKey(string);
845                 ipstream.ignore(256,'\n');
846                 ipstream.ignore(256,'\n');
847                 ipstream >> string;
848                 game.throwkey=CharToKey(string);
849                 ipstream.ignore(256,'\n');
850                 ipstream.ignore(256,'\n');
851                 ipstream >> string;
852                 game.attackkey=CharToKey(string);
853                 ipstream.ignore(256,'\n');
854                 ipstream.ignore(256,'\n');
855                 ipstream >> string;
856                 game.chatkey=CharToKey(string);
857                 ipstream.close();
858
859                 if(detail>2)detail=2;
860                 if(detail<0)detail=0;
861                 if(screenwidth<0)screenwidth=640;
862                 if(screenheight<0)screenheight=480;
863 #if !USE_SDL  // we'll take anything that works.
864                 if(screenwidth>3000)screenwidth=640;
865                 if(screenheight>3000)screenheight=480;
866 #endif
867         }
868         if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
869                 kBitsPerPixel=16;
870         }
871
872
873         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
874
875         SetupDSpFullScreen();
876
877 #if USE_SDL
878     if (!SDL_WasInit(SDL_INIT_VIDEO))
879     {
880         if (SDL_Init(SDL_INIT_VIDEO) == -1)
881         {
882             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
883             return false;
884         }
885
886         if (SDL_GL_LoadLibrary(NULL) == -1)
887         {
888             fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
889             SDL_Quit();
890             return false;
891         }
892
893         SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
894         if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
895             res = hardcoded_resolutions;
896
897         // reverse list (it was sorted biggest to smallest by SDL)...
898         int count;
899         for (count = 0; res[count]; count++)
900         {
901             if ((res[count]->w < 640) || (res[count]->h < 480))
902                 break;   // sane lower limit.
903         }
904
905         static SDL_Rect *resolutions_block = NULL;
906         resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
907         resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
908         if ((resolutions_block == NULL) || (resolutions == NULL))
909         {
910             SDL_Quit();
911             fprintf(stderr, "Out of memory!\n");
912             return false;
913         }
914
915         resolutions[count--] = NULL;
916         for (int i = 0; count >= 0; i++, count--)
917         {
918             memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
919             resolutions[count] = &resolutions_block[count];
920         }
921
922         if (cmdline("showresolutions"))
923         {
924             printf("Resolutions we think are okay:\n");
925             for (int i = 0; resolutions[i]; i++)
926                 printf("  %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
927         }
928     }
929
930     Uint32 sdlflags = SDL_OPENGL;
931     if (!cmdline("windowed"))
932         sdlflags |= SDL_FULLSCREEN;
933
934     SDL_WM_SetCaption("Lugaru", "Lugaru");
935
936     SDL_ShowCursor(0);
937
938     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
939
940     if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
941     {
942         fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
943         fprintf(stderr, "forcing 640x480...\n");
944         kContextWidth = 640;
945         kContextHeight = 480;
946         if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
947         {
948             fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
949             fprintf(stderr, "forcing 640x480 windowed mode...\n");
950             sdlflags &= ~SDL_FULLSCREEN;
951             if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
952             {
953                 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
954                 return false;
955             }
956         }
957     }
958
959     int dblbuf = 0;
960     if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
961     {
962         fprintf(stderr, "Failed to get double buffered GL context!\n");
963         SDL_Quit();
964         return false;
965     }
966
967     if (!lookup_all_glsyms())
968     {
969         SDL_Quit();
970         return false;
971     }
972
973     if (!cmdline("nomousegrab"))
974         SDL_WM_GrabInput(SDL_GRAB_ON);
975 #endif
976
977         glClear( GL_COLOR_BUFFER_BIT );
978         swap_gl_buffers();
979
980         // clear all states
981         glDisable( GL_ALPHA_TEST);
982         glDisable( GL_BLEND);
983         glDisable( GL_DEPTH_TEST);
984         //      glDisable( GL_DITHER);
985         glDisable( GL_FOG);
986         glDisable( GL_LIGHTING);
987         glDisable( GL_LOGIC_OP);
988         glDisable( GL_STENCIL_TEST);
989         glDisable( GL_TEXTURE_1D);
990         glDisable( GL_TEXTURE_2D);
991         glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
992         glPixelTransferi( GL_RED_SCALE, 1);
993         glPixelTransferi( GL_RED_BIAS, 0);
994         glPixelTransferi( GL_GREEN_SCALE, 1);
995         glPixelTransferi( GL_GREEN_BIAS, 0);
996         glPixelTransferi( GL_BLUE_SCALE, 1);
997         glPixelTransferi( GL_BLUE_BIAS, 0);
998         glPixelTransferi( GL_ALPHA_SCALE, 1);
999         glPixelTransferi( GL_ALPHA_BIAS, 0);
1000
1001         // set initial rendering states
1002         glShadeModel( GL_SMOOTH);
1003         glClearDepth( 1.0f);
1004         glDepthFunc( GL_LEQUAL);
1005         glDepthMask( GL_TRUE);
1006         //      glDepthRange( FRONT_CLIP, BACK_CLIP);
1007         glEnable( GL_DEPTH_TEST);
1008         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
1009         glCullFace( GL_FRONT);
1010         glEnable( GL_CULL_FACE);
1011         glEnable( GL_LIGHTING);
1012 //      glEnable( GL_LIGHT_MODEL_AMBIENT);
1013         glEnable( GL_DITHER);
1014         glEnable( GL_COLOR_MATERIAL);
1015         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1016         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1017         glAlphaFunc( GL_GREATER, 0.5f);
1018
1019 #if USE_DEVIL
1020         if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION ||
1021                 iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION ||
1022                 ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION)
1023         {
1024                 ReportError("DevIL version is different...exiting!\n");
1025                 return false;
1026         }
1027
1028         ilInit();
1029         iluInit();
1030         ilutInit();
1031
1032         ilutRenderer(ILUT_OPENGL);
1033
1034         ilEnable(IL_ORIGIN_SET);
1035         ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
1036 #endif
1037
1038         GLint width = kContextWidth;
1039         GLint height = kContextHeight;
1040         gMidPoint.h = width / 2;
1041         gMidPoint.v = height / 2;
1042         screenwidth=width;
1043         screenheight=height;
1044
1045         game.newdetail=detail;
1046         game.newscreenwidth=screenwidth;
1047         game.newscreenheight=screenheight;
1048
1049         game.InitGame();
1050
1051         return true;
1052 }
1053
1054
1055 static void DoMouse(Game & game)
1056 {
1057 #if USE_SDL
1058         if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1059         {
1060                 game.deltah *= usermousesensitivity;
1061                 game.deltav *= usermousesensitivity;
1062                 game.mousecoordh += game.deltah;
1063                 game.mousecoordv += game.deltav;
1064         if (game.mousecoordh < 0)
1065             game.mousecoordh = 0;
1066         else if (game.mousecoordh >= kContextWidth)
1067             game.mousecoordh = kContextWidth - 1;
1068         if (game.mousecoordv < 0)
1069             game.mousecoordv = 0;
1070         else if (game.mousecoordv >= kContextHeight)
1071             game.mousecoordv = kContextHeight - 1;
1072         }
1073 #endif
1074 }
1075
1076
1077
1078 // --------------------------------------------------------------------------
1079
1080 void DoKey (SInt8 theKey, SInt8 theCode)
1081 {
1082         // do nothing
1083 }
1084
1085 // --------------------------------------------------------------------------
1086
1087
1088
1089 void DoFrameRate (int update)
1090 {       
1091         static long frames = 0;
1092
1093         static AbsoluteTime time = {0,0};
1094         static AbsoluteTime frametime = {0,0};
1095         AbsoluteTime currTime = UpTime ();
1096         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1097
1098         if (0 > deltaTime)      // if negative microseconds
1099                 deltaTime /= -1000000.0;
1100         else                            // else milliseconds
1101                 deltaTime /= 1000.0;
1102
1103         multiplier=deltaTime;
1104         if(multiplier<.001)multiplier=.001;
1105         if(multiplier>10)multiplier=10;
1106         if(update)frametime = currTime; // reset for next time interval
1107
1108         deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1109
1110         if (0 > deltaTime)      // if negative microseconds
1111                 deltaTime /= -1000000.0;
1112         else                            // else milliseconds
1113                 deltaTime /= 1000.0;
1114         frames++;
1115         if (0.001 <= deltaTime) // has update interval passed
1116         {
1117                 if(update){
1118                         time = currTime;        // reset for next time interval
1119                         frames = 0;
1120                 }
1121         }
1122 }
1123
1124
1125 void DoUpdate (Game & game)
1126 {
1127         static float sps=200;
1128         static int count;
1129         static float oldmult;
1130
1131         DoFrameRate(1);
1132         if(multiplier>.6)multiplier=.6;
1133
1134         game.fps=1/multiplier;
1135
1136         count = multiplier*sps;
1137         if(count<2)count=2;
1138         //if(count>10)count=10;
1139
1140         realmultiplier=multiplier;
1141         multiplier*=gamespeed;
1142         if(difficulty==1)multiplier*=.9;
1143         if(difficulty==0)multiplier*=.8;
1144
1145         if(game.loading==4)multiplier*=.00001;
1146         //multiplier*.9;
1147         if(slomo&&!mainmenu)multiplier*=slomospeed;
1148         //if(freeze)multiplier*=0.00001;
1149         oldmult=multiplier;
1150         multiplier/=(float)count;
1151
1152         DoMouse(game);
1153
1154         game.TickOnce();
1155
1156         for(int i=0;i<count;i++)
1157         {
1158                 game.Tick();
1159         }
1160         multiplier=oldmult;
1161
1162         game.TickOnceAfter();
1163 /* - Debug code to test how many channels were active on average per frame
1164         static long frames = 0;
1165
1166         static AbsoluteTime start = {0,0};
1167         AbsoluteTime currTime = UpTime ();
1168         static int num_channels = 0;
1169         
1170         num_channels += OPENAL_GetChannelsPlaying();
1171         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1172
1173         if (0 > deltaTime)      // if negative microseconds
1174                 deltaTime /= -1000000.0;
1175         else                            // else milliseconds
1176                 deltaTime /= 1000.0;
1177
1178         ++frames;
1179
1180         if (deltaTime >= 1)
1181         {
1182                 start = currTime;
1183                 float avg_channels = (float)num_channels / (float)frames;
1184
1185                 ofstream opstream("log.txt",ios::app); 
1186                 opstream << "Average frame count: ";
1187                 opstream << frames;
1188                 opstream << " frames - ";
1189                 opstream << avg_channels;
1190                 opstream << " per frame.\n";
1191                 opstream.close();
1192
1193                 frames = 0;
1194                 num_channels = 0;
1195         }
1196 */
1197         DrawGL (game);
1198 }
1199
1200 // --------------------------------------------------------------------------
1201
1202
1203 void CleanUp (void)
1204 {
1205         LOGFUNC;
1206
1207 //      game.Dispose();
1208
1209 #if USE_DEVIL
1210         ilShutDown();
1211 #endif
1212
1213 #if USE_SDL
1214     SDL_Quit();
1215     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1216     #include "glstubs.h"
1217     #undef GL_FUNC
1218     // cheat here...static destructors are calling glDeleteTexture() after
1219     //  the context is destroyed and libGL unloaded by SDL_Quit().
1220     pglDeleteTextures = glDeleteTextures_doNothing;
1221 #endif
1222 }
1223
1224 // --------------------------------------------------------------------------
1225
1226 static bool g_focused = true;
1227
1228
1229 static bool IsFocused()
1230 {
1231     STUBBED("write me");
1232         return true;
1233 }
1234
1235
1236 static void launch_web_browser(const char *url)
1237 {
1238 #ifdef WIN32
1239     ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1240
1241 #elif (defined(__APPLE__) && defined(__MACH__))
1242     const char *fmt = "open '%s'";
1243     const size_t len = strlen(fmt) + strlen(url) + 16;
1244     char *buf = new char[len];
1245     snprintf(buf, len, fmt, url);
1246     system(buf);
1247     delete[] buf;
1248
1249 #elif PLATFORM_LINUX
1250     const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1251     const size_t len = strlen(fmt) + strlen(url) + 16;
1252     char *buf = new char[len];
1253     snprintf(buf, len, fmt, url);
1254     system(buf);
1255     delete[] buf;
1256 #endif
1257 }
1258
1259
1260 #ifndef WIN32
1261 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1262 static char *findBinaryInPath(const char *bin, char *envr)
1263 {
1264     size_t alloc_size = 0;
1265     char *exe = NULL;
1266     char *start = envr;
1267     char *ptr;
1268
1269     do
1270     {
1271         size_t size;
1272         ptr = strchr(start, ':');  /* find next $PATH separator. */
1273         if (ptr)
1274             *ptr = '\0';
1275
1276         size = strlen(start) + strlen(bin) + 2;
1277         if (size > alloc_size)
1278         {
1279             char *x = (char *) realloc(exe, size);
1280             if (x == NULL)
1281             {
1282                 if (exe != NULL)
1283                     free(exe);
1284                 return(NULL);
1285             } /* if */
1286
1287             alloc_size = size;
1288             exe = x;
1289         } /* if */
1290
1291         /* build full binary path... */
1292         strcpy(exe, start);
1293         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1294             strcat(exe, "/");
1295         strcat(exe, bin);
1296
1297         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
1298         {
1299             strcpy(exe, start);  /* i'm lazy. piss off. */
1300             return(exe);
1301         } /* if */
1302
1303         start = ptr + 1;  /* start points to beginning of next element. */
1304     } while (ptr != NULL);
1305
1306     if (exe != NULL)
1307         free(exe);
1308
1309     return(NULL);  /* doesn't exist in path. */
1310 } /* findBinaryInPath */
1311
1312
1313 char *calcBaseDir(const char *argv0)
1314 {
1315     /* If there isn't a path on argv0, then look through the $PATH for it. */
1316     char *retval;
1317     char *envr;
1318
1319     char *ptr = strrchr((char *)argv0, '/');
1320     if (strchr(argv0, '/'))
1321     {
1322         retval = strdup(argv0);
1323         if (retval)
1324             *(strrchr(retval, '/')) = '\0';
1325         return(retval);
1326     }
1327
1328     envr = getenv("PATH");
1329     if (!envr) return NULL;
1330     envr = strdup(envr);
1331     if (!envr) return NULL;
1332     retval = findBinaryInPath(argv0, envr);
1333     free(envr);
1334     return(retval);
1335 }
1336
1337 static inline void chdirToAppPath(const char *argv0)
1338 {
1339     char *dir = calcBaseDir(argv0);
1340     if (dir)
1341     {
1342         #if (defined(__APPLE__) && defined(__MACH__))
1343         // Chop off /Contents/MacOS if it's at the end of the string, so we
1344         //  land in the base of the app bundle.
1345         const size_t len = strlen(dir);
1346         const char *bundledirs = "/Contents/MacOS";
1347         const size_t bundledirslen = strlen(bundledirs);
1348         if (len > bundledirslen)
1349         {
1350             char *ptr = (dir + len) - bundledirslen;
1351             if (strcasecmp(ptr, bundledirs) == 0)
1352                 *ptr = '\0';
1353         }
1354         #endif
1355         chdir(dir);
1356         free(dir);
1357     }
1358 }
1359 #endif
1360
1361
1362 int main(int argc, char **argv)
1363 {
1364 #ifndef __MINGW32__
1365     _argc = argc;
1366     _argv = argv;
1367 #endif
1368
1369     // !!! FIXME: we could use a Win32 API for this.  --ryan.
1370 #ifndef WIN32
1371     chdirToAppPath(argv[0]);
1372 #endif
1373
1374         LOGFUNC;
1375
1376         memset( &g_theKeys, 0, sizeof( KeyMap));
1377
1378     initSDLKeyTable();
1379
1380         try
1381         {
1382                 bool regnow = false;
1383                 {
1384                         Game game;
1385                         pgame = &game;
1386
1387                         //ofstream os("error.txt");
1388                         //os.close();
1389                         //ofstream os("log.txt");
1390                         //os.close();
1391
1392                         if (!SetUp (game))
1393                 return 42;
1394
1395                         while (!gDone&&!game.quit&&(!game.tryquit||!game.registered))
1396                         {
1397                                 if (IsFocused())
1398                                 {
1399                                         gameFocused = true;
1400
1401                                         // check windows messages
1402                                         #if USE_SDL
1403                                         game.deltah = 0;
1404                                         game.deltav = 0;
1405                                         SDL_Event e;
1406                                         // message pump
1407                                         while( SDL_PollEvent( &e ) )
1408                                         {
1409                                                 if( e.type == SDL_QUIT )
1410                                                 {
1411                                                         gDone=true;
1412                                                         break;
1413                                                 }
1414                                                 sdlEventProc(e, game);
1415                                         }
1416                                         #endif
1417
1418                                         // game
1419                                         DoUpdate(game);
1420                                 }
1421                                 else
1422                                 {
1423                                         if (gameFocused)
1424                                         {
1425                                                 // allow game chance to pause
1426                                                 gameFocused = false;
1427                                                 DoUpdate(game);
1428                                         }
1429
1430                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1431                     STUBBED("give up CPU but sniff the event queue");
1432                                 }
1433                         }
1434
1435                         regnow = game.registernow;
1436                 }
1437                 pgame = 0;
1438
1439                 CleanUp ();
1440 //              if(game.registernow){
1441                 if(regnow)
1442                 {
1443             #if (defined(__APPLE__) && defined(__MACH__))
1444             launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1445             #elif PLATFORM_LINUX
1446             launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1447             #else
1448             launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1449             #endif
1450                 }
1451
1452         #if PLATFORM_LINUX  // (this may not be necessary any more.)
1453         _exit(0);  // !!! FIXME: hack...crashes on exit!
1454         #endif
1455                 return 0;
1456         }
1457         catch (const std::exception& error)
1458         {
1459                 CleanUp();
1460
1461                 std::string e = "Caught exception: ";
1462                 e += error.what();
1463
1464                 LOG(e);
1465
1466                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1467         }
1468
1469         CleanUp();
1470
1471         return -1;
1472 }
1473
1474
1475
1476         // --------------------------------------------------------------------------
1477
1478 #if !USE_SDL
1479         int resolutionID(int width, int height)
1480         {
1481                 int whichres;
1482                 whichres=-1;
1483                 if(width==640 && height==480)whichres=0;
1484                 if(width==800 && height==600)whichres=1;
1485                 if(width==1024 && height==768)whichres=2;
1486                 if(width==1280 && height==1024)whichres=3;
1487                 if(width==1600 && height==1200)whichres=4;
1488                 if(width==840 && height==524)whichres=5;
1489                 if(width==1024 && height==640)whichres=6;
1490                 if(width==1344 && height==840)whichres=7;
1491                 if(width==1920 && height==1200)whichres=8;
1492
1493                 return whichres;
1494         }
1495
1496         int closestResolution(int width, int height)
1497         {
1498                 int whichres;
1499                 whichres=-1;
1500                 if(width>=640 && height>=480)whichres=0;
1501                 if(width>=800 && height>=600)whichres=1;
1502                 if(width>=1024 && height>=768)whichres=2;
1503                 if(width>=1280 && height>=1024)whichres=3;
1504                 if(width>=1600 && height>=1200)whichres=4;
1505                 if(width==840 && height==524)whichres=5;
1506                 if(width==1024 && height==640)whichres=6;
1507                 if(width==1344 && height==840)whichres=7;
1508                 if(width>=1920 && height>=1200)whichres=8;
1509
1510                 return whichres;
1511         }
1512 #endif
1513
1514         bool selectDetail(int & width, int & height, int & bpp, int & detail)
1515         {
1516                 bool res = true;
1517
1518                 // currently with SDL, we just use whatever is requested
1519                 //  and don't care.  --ryan.
1520                 #if !USE_SDL
1521                 int whichres = closestResolution(width, height);
1522
1523                 while (true)
1524                 {
1525                         if(whichres<=0 || whichres>8){
1526                                 whichres = 0;
1527                                 width=640;
1528                                 height=480;
1529                         }
1530                         if(whichres==1){
1531                                 width=800;
1532                                 height=600;
1533                         }
1534                         if(whichres==2){
1535                                 width=1024;
1536                                 height=768;
1537                         }
1538                         if(whichres==3){
1539                                 width=1280;
1540                                 height=1024;
1541                         }
1542                         if(whichres==4){
1543                                 width=1600;
1544                                 height=1200;
1545                         }
1546                         if(whichres==5){
1547                                 width=840;
1548                                 height=524;
1549                         }
1550                         if(whichres==6){
1551                                 width=1024;
1552                                 height=640;
1553                         }
1554                         if(whichres==7){
1555                                 width=1344;
1556                                 height=840;
1557                         }
1558                         if(whichres==8){
1559                                 width=1920;
1560                                 height=1200;
1561                         }
1562
1563                         if ((detail != 0) && (resolutionDepths[whichres][1] != 0))
1564                         {
1565                                 break;
1566                         }
1567                         else if ((detail == 0) && (resolutionDepths[whichres][0] != 0))
1568                         {
1569                                 break;
1570                         }
1571                         else if ((detail != 0) && (resolutionDepths[whichres][0] != 0))
1572                         {
1573                                 res = false;
1574                                 detail = 0;
1575                                 break;
1576                         }
1577                         else
1578
1579             if (0 == whichres)
1580                         {
1581                                 break;
1582                         }
1583
1584                         --whichres;
1585                 }
1586
1587                 bpp = resolutionDepths[whichres][(detail != 0)];
1588                 #endif
1589
1590                 return res;
1591         }
1592
1593         extern int channels[100];
1594         extern OPENAL_SAMPLE * samp[100];
1595         extern OPENAL_STREAM * strm[20];
1596
1597         extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1598         {
1599                 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1600                 if (currSample && currSample == samp[chan])
1601                 {
1602                         if (OPENAL_GetPaused(channels[chan]))
1603                         {
1604                                 OPENAL_StopSound(channels[chan]);
1605                                 channels[chan] = OPENAL_FREE;
1606                         }
1607                         else if (OPENAL_IsPlaying(channels[chan]))
1608                         {
1609                                 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
1610                                 if (loop_mode & OPENAL_LOOP_OFF)
1611                                 {
1612                                         channels[chan] = OPENAL_FREE;
1613                                 }
1614                         }
1615                 }
1616                 else
1617                 {
1618                         channels[chan] = OPENAL_FREE;
1619                 }
1620
1621                 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
1622                 if (channels[chan] < 0)
1623                 {
1624                         channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
1625                 }
1626         }
1627
1628         extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1629         {
1630                 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1631                 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
1632                 {
1633                                 OPENAL_StopSound(channels[chan]);
1634                                 OPENAL_Stream_Stop(sptr);
1635                 }
1636                 else
1637                 {
1638                         OPENAL_Stream_Stop(sptr);
1639                         channels[chan] = OPENAL_FREE;
1640                 }
1641
1642                 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
1643                 if (channels[chan] < 0)
1644                 {
1645                         channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
1646                 }
1647         }
1648
1649         bool LoadImage(const char * fname, TGAImageRec & tex)
1650         {
1651                 bool res = true;
1652
1653                 if ( tex.data == NULL )
1654                 {
1655                         return false;
1656                 }
1657
1658         #if USE_DEVIL
1659                 ILstring f = strdup(ConvertFileName(fname));
1660                 if (!f)
1661                 {
1662                         return false;
1663                 }
1664
1665                 ILuint iid=0;
1666                 ilGenImages(1, &iid);
1667                 ilBindImage(iid);
1668                 if (ilLoadImage(f))
1669                 {
1670                         //iluFlipImage();
1671                         tex.sizeX = ilGetInteger(IL_IMAGE_WIDTH);
1672                         tex.sizeY = ilGetInteger(IL_IMAGE_HEIGHT);
1673                         tex.bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
1674                         ILuint Bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL),
1675                                 imageSize = tex.sizeX * tex.sizeY * Bpp;
1676                         ILubyte *Data = ilGetData();
1677                         memcpy(tex.data, Data, imageSize);
1678
1679                         // Truvision Targa files are stored as BGR colors
1680                         // We want RGB so Blue and Red bytes are switched
1681                         if (IL_TGA == ilGetInteger(IL_IMAGE_FORMAT))
1682                         {
1683                                 // Loop Through The Image Data
1684                                 for (GLuint i = 0; i < int(imageSize); i += Bpp)
1685                                 {
1686                                         // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
1687                                         GLbyte temp;                                            // Temporary Variable
1688                                         temp = tex.data[i];                                     // Temporarily Store The Value At Image Data 'i'
1689                                         tex.data[i] = tex.data[i + 2];          // Set The 1st Byte To The Value Of The 3rd Byte
1690                                         tex.data[i + 2] = temp;                         // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
1691                                 }
1692                         }
1693                 }
1694                 else
1695                 {
1696                         res = false;
1697                 }
1698                 ilDeleteImages(1, &iid);
1699 /*
1700                 if (tid)
1701                 {
1702                         GLuint texid = ilutGLLoadImage(f);
1703                         *tid = texid;
1704                 }
1705                 else if (mip)
1706                 {
1707                         ilutGLBuildMipmaps()
1708                 }
1709                 else
1710                 {
1711                         ilutGLTexImage(0);
1712                 }
1713 */
1714                 free(f);
1715         #else
1716         res = load_image(fname, tex);
1717         //if (!res) printf("failed to load %s\n", fname);
1718         #endif
1719
1720                 return res;
1721         }
1722
1723         void ScreenShot(const char * fname)
1724         {
1725         #if USE_DEVIL
1726                 ILstring f = strdup(fname);
1727                 if (!f)
1728                 {
1729                         return;
1730                 }
1731
1732                 ILuint iid;
1733                 ilGenImages(1, &iid);
1734                 ilBindImage(iid);
1735                 if (ilutGLScreen())
1736                 {
1737                         ilSaveImage(f);
1738                 }
1739                 ilDeleteImages(1, &iid);
1740
1741                 free(f);
1742         #else
1743         save_image(fname);
1744         #endif
1745         }
1746
1747
1748 #if !USE_DEVIL
1749 static bool load_image(const char *file_name, TGAImageRec &tex)
1750 {
1751     char *ptr = strrchr((char *)file_name, '.');
1752     if (ptr)
1753     {
1754         if (strcasecmp(ptr+1, "png") == 0)
1755             return load_png(file_name, tex);
1756         else if (strcasecmp(ptr+1, "jpg") == 0)
1757             return load_jpg(file_name, tex);
1758     }
1759
1760     STUBBED("Unsupported image type");
1761     return false;
1762 }
1763
1764
1765 struct my_error_mgr {
1766   struct jpeg_error_mgr pub;    /* "public" fields */
1767   jmp_buf setjmp_buffer;        /* for return to caller */
1768 };
1769 typedef struct my_error_mgr * my_error_ptr;
1770
1771
1772 static void my_error_exit(j_common_ptr cinfo)
1773 {
1774         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1775         longjmp(err->setjmp_buffer, 1);
1776 }
1777
1778 /* stolen from public domain example.c code in libjpg distribution. */
1779 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1780 {
1781     struct jpeg_decompress_struct cinfo;
1782     struct my_error_mgr jerr;
1783     JSAMPROW buffer[1];         /* Output row buffer */
1784     int row_stride;             /* physical row width in output buffer */
1785     FILE *infile = fopen(file_name, "rb");
1786
1787     if (infile == NULL)
1788         return false;
1789
1790     cinfo.err = jpeg_std_error(&jerr.pub);
1791     jerr.pub.error_exit = my_error_exit;
1792     if (setjmp(jerr.setjmp_buffer)) {
1793         jpeg_destroy_decompress(&cinfo);
1794         fclose(infile);
1795         return false;
1796     }
1797
1798     jpeg_create_decompress(&cinfo);
1799     jpeg_stdio_src(&cinfo, infile);
1800     (void) jpeg_read_header(&cinfo, TRUE);
1801
1802     cinfo.out_color_space = JCS_RGB;
1803     cinfo.quantize_colors = 0;
1804     (void) jpeg_calc_output_dimensions(&cinfo);
1805     (void) jpeg_start_decompress(&cinfo);
1806
1807     row_stride = cinfo.output_width * cinfo.output_components;
1808     tex.sizeX = cinfo.output_width;
1809     tex.sizeY = cinfo.output_height;
1810     tex.bpp = 24;
1811
1812     while (cinfo.output_scanline < cinfo.output_height) {
1813         buffer[0] = (JSAMPROW)(char *)tex.data +
1814                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1815         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1816     }
1817
1818     (void) jpeg_finish_decompress(&cinfo);
1819     jpeg_destroy_decompress(&cinfo);
1820     fclose(infile);
1821
1822     return true;
1823 }
1824
1825
1826 /* stolen from public domain example.c code in libpng distribution. */
1827 static bool load_png(const char *file_name, TGAImageRec &tex)
1828 {
1829     bool hasalpha = false;
1830     png_structp png_ptr = NULL;
1831     png_infop info_ptr = NULL;
1832     png_uint_32 width, height;
1833     int bit_depth, color_type, interlace_type;
1834     png_byte **rows = NULL;
1835     bool retval = false;
1836     png_byte **row_pointers = NULL;
1837     FILE *fp = fopen(file_name, "rb");
1838
1839     if (fp == NULL)
1840         return(NULL);
1841
1842     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1843     if (png_ptr == NULL)
1844         goto png_done;
1845
1846     info_ptr = png_create_info_struct(png_ptr);
1847     if (info_ptr == NULL)
1848         goto png_done;
1849
1850     if (setjmp(png_jmpbuf(png_ptr)))
1851         goto png_done;
1852
1853     png_init_io(png_ptr, fp);
1854     png_read_png(png_ptr, info_ptr,
1855                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1856                  NULL);
1857     png_get_IHDR(png_ptr, info_ptr, &width, &height,
1858                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
1859
1860     if (bit_depth != 8)  // transform SHOULD handle this...
1861         goto png_done;
1862
1863     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
1864         goto png_done;
1865
1866     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
1867         goto png_done;
1868
1869     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1870     row_pointers = png_get_rows(png_ptr, info_ptr);
1871     if (!row_pointers)
1872         goto png_done;
1873
1874     if (!hasalpha)
1875     {
1876         png_byte *dst = tex.data;
1877         for (int i = height-1; i >= 0; i--)
1878         {
1879             png_byte *src = row_pointers[i];
1880             for (int j = 0; j < width; j++)
1881             {
1882                 dst[0] = src[0];
1883                 dst[1] = src[1];
1884                 dst[2] = src[2];
1885                 dst[3] = 0xFF;
1886                 src += 3;
1887                 dst += 4;
1888             }
1889         }
1890     }
1891
1892     else
1893     {
1894         png_byte *dst = tex.data;
1895         int pitch = width * 4;
1896         for (int i = height-1; i >= 0; i--, dst += pitch)
1897             memcpy(dst, row_pointers[i], pitch);
1898     }
1899
1900     tex.sizeX = width;
1901     tex.sizeY = height;
1902     tex.bpp = 32;
1903     retval = true;
1904
1905 png_done:
1906     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1907     if (fp)
1908         fclose(fp);
1909     return (retval);
1910 }
1911
1912
1913 static bool save_image(const char *file_name)
1914 {
1915     char *ptr = strrchr((char *)file_name, '.');
1916     if (ptr)
1917     {
1918         if (strcasecmp(ptr+1, "png") == 0)
1919             return save_png(file_name);
1920     }
1921
1922     STUBBED("Unsupported image type");
1923     return false;
1924 }
1925
1926
1927 static bool save_png(const char *file_name)
1928 {
1929     FILE *fp = NULL;
1930     png_structp png_ptr = NULL;
1931     png_infop info_ptr = NULL;
1932     bool retval = false;
1933
1934     fp = fopen(file_name, "wb");
1935     if (fp == NULL)
1936         return false;
1937
1938     png_bytep *row_pointers = new png_bytep[kContextHeight];
1939     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1940     if ((!screenshot) || (!row_pointers))
1941         goto save_png_done;
1942
1943     glGetError();
1944     glReadPixels(0, 0, kContextWidth, kContextHeight,
1945                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1946     if (glGetError() != GL_NO_ERROR)
1947         goto save_png_done;
1948
1949     for (int i = 0; i < kContextHeight; i++)
1950         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1951
1952     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1953     if (png_ptr == NULL)
1954         goto save_png_done;
1955
1956     info_ptr = png_create_info_struct(png_ptr);
1957     if (info_ptr == NULL)
1958         goto save_png_done;
1959
1960     if (setjmp(png_jmpbuf(png_ptr)))
1961         goto save_png_done;
1962
1963     png_init_io(png_ptr, fp);
1964
1965     if (setjmp(png_jmpbuf(png_ptr)))
1966         goto save_png_done;
1967
1968     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1969                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1970                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1971
1972     png_write_info(png_ptr, info_ptr);
1973
1974     if (setjmp(png_jmpbuf(png_ptr)))
1975         goto save_png_done;
1976
1977         png_write_image(png_ptr, row_pointers);
1978
1979         if (setjmp(png_jmpbuf(png_ptr)))
1980         goto save_png_done;
1981
1982     png_write_end(png_ptr, NULL);
1983     retval = true;
1984
1985 save_png_done:
1986     png_destroy_write_struct(&png_ptr, &info_ptr);
1987     delete[] screenshot;
1988     delete[] row_pointers;
1989     if (fp)
1990         fclose(fp);
1991     if (!retval)
1992         unlink(ConvertFileName(file_name));
1993     return retval;
1994 }
1995
1996 #endif
1997