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