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