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