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