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