]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
a64f5e4408f3bda69737bacc04f7f2834fdfb4b9
[lugaru.git] / Source / OpenGL_Windows.cpp
1
2 #ifdef WIN32
3 #include <vld.h>
4 #endif
5
6 #include "Game.h"
7
8 #ifndef USE_DEVIL
9 #  ifdef WIN32
10 #    define USE_DEVIL
11 #  endif
12 #endif
13
14 #if USE_DEVIL
15     #include "IL/il.h"
16     #include "IL/ilu.h"
17     #include "IL/ilut.h"
18 #else
19     // just use libpng and libjpg directly; it's lighter-weight and easier
20     //  to manage the dependencies on Linux...
21     extern "C" {
22         #include "png.h"
23         #include "jpeglib.h"
24     }
25     static bool load_image(const char * fname, TGAImageRec & tex);
26     static bool load_png(const char * fname, TGAImageRec & tex);
27     static bool load_jpg(const char * fname, TGAImageRec & tex);
28     static bool save_image(const char * fname);
29     static bool save_png(const char * fname);
30 #endif
31
32 // ADDED GWC
33 #ifdef _MSC_VER
34 #pragma comment(lib, "opengl32.lib")
35 #pragma comment(lib, "glu32.lib")
36 #pragma comment(lib, "glaux.lib")
37 #endif
38
39 extern bool buttons[3];
40 extern float multiplier;
41 extern float screenwidth,screenheight;
42 extern float sps;
43 extern float realmultiplier;
44 extern int slomo;
45 extern bool ismotionblur;
46 extern float usermousesensitivity;
47 extern int detail;
48 extern bool floatjump;
49 extern bool cellophane;
50 // MODIFIED GWC
51 //extern int terraindetail;
52 //extern int texdetail;
53 extern float terraindetail;
54 extern float texdetail;
55 extern int bloodtoggle;
56 extern bool osx;
57 extern bool autoslomo;
58 extern bool foliage;
59 extern bool musictoggle;
60 extern bool trilinear;
61 extern float gamespeed;
62 extern int difficulty;
63 extern bool damageeffects;
64 extern int numplayers;
65 extern bool decals;
66 extern bool invertmouse;
67 extern bool texttoggle;
68 extern bool ambientsound;
69 extern bool mousejump;
70 extern bool freeze;
71 extern Person player[maxplayers];
72 extern bool vblsync;
73 extern bool stillloading;
74 extern bool showpoints;
75 extern bool alwaysblur;
76 extern bool immediate;
77 extern bool velocityblur;
78 extern bool debugmode;
79 extern int mainmenu;
80 /*extern*/ bool gameFocused;
81 extern int kBitsPerPixel;
82 extern float slomospeed;
83 extern float slomofreq;
84 extern float oldgamespeed;
85 extern float volume;
86
87 #include <math.h>
88 #include <stdio.h>
89 #include <string.h>
90 #include <fstream>
91 #include <iostream>
92 #include "gamegl.h"
93 #include "MacCompatibility.h"
94
95 #ifdef WIN32
96 #include <shellapi.h>
97 #endif
98
99 #include "fmod.h"
100
101 #include "res/resource.h"
102
103 using namespace std;
104
105
106 unsigned int resolutionDepths[8][2] = {0};
107
108 bool selectDetail(int & width, int & height, int & bpp, int & detail);
109 int closestResolution(int width, int height);
110 int resolutionID(int width, int height);
111
112 void ReportError (char * strError);
113
114 void SetupDSpFullScreen();
115 void ShutdownDSp();
116
117 void DrawGL(Game & game);
118
119 void CreateGLWindow (void);
120 Boolean SetUp (Game & game);
121 void DoKey (SInt8 theKey, SInt8 theCode);
122 void DoUpdate (Game & game);
123
124 void DoEvent (void);
125 void CleanUp (void);
126
127
128 // statics/globals (internal only) ------------------------------------------
129 #ifndef WIN32
130 typedef struct tagPOINT { 
131   int x;
132   int y;
133 } POINT, *PPOINT; 
134 #endif
135
136 #if USE_SDL
137 #define GL_FUNC(ret,fn,params,call,rt) \
138     extern "C" { \
139         static ret GLAPIENTRY (*p##fn) params = NULL; \
140         ret GLAPIENTRY fn params { rt p##fn call; } \
141     }
142 #include "glstubs.h"
143 #undef GL_FUNC
144
145 static bool lookup_glsym(const char *funcname, void **func)
146 {
147     *func = SDL_GL_GetProcAddress(funcname);
148     if (*func == NULL)
149     {
150         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
151         return false;
152     }
153     return true;
154 }
155
156 static bool lookup_all_glsyms(void)
157 {
158     bool retval = true;
159     #define GL_FUNC(ret,fn,params,call,rt) \
160         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
161     #include "glstubs.h"
162     #undef GL_FUNC
163     return retval;
164 }
165
166 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
167 {
168     // no-op.
169 }
170
171
172
173 void sdlGetCursorPos(POINT *pt)
174 {
175     int x, y;
176     SDL_GetMouseState(&x, &y);
177     pt->x = x;
178     pt->y = y;
179 }
180 #define GetCursorPos(x) sdlGetCursorPos(x)
181 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
182 #define ScreenToClient(x, pt)
183 #define ClientToScreen(x, pt)
184 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
185 #endif
186
187 Point delta;
188
189 #ifdef WIN32
190 static const char g_wndClassName[]={ "LUGARUWINDOWCLASS" };
191 static HINSTANCE g_appInstance;
192 static HWND g_windowHandle;
193 static HGLRC hRC;
194 #endif
195
196 static bool g_button, fullscreen = true;
197
198
199 // Menu defs
200 enum 
201 {
202         kFileQuit = 1
203 };
204
205 enum 
206 {
207         kForegroundSleep = 10,
208         kBackgroundSleep = 10000
209 };
210
211
212 int kContextWidth;
213 int kContextHeight;
214
215 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
216
217 GLuint gFontList;
218 char gcstrMode [256] = "";
219
220 UInt32 gSleepTime = kForegroundSleep;
221 Boolean gDone = false, gfFrontProcess = true;
222
223 Game * pgame = 0;
224
225
226 static int _argc = 0;
227 static char **_argv = NULL;
228
229 bool cmdline(const char *cmd)
230 {
231     for (int i = 1; i < _argc; i++)
232     {
233         char *arg = _argv[i];
234         while (*arg == '-')
235             arg++;
236         if (stricmp(arg, cmd) == 0)
237             return true;
238     }
239
240     return false;
241 }
242
243
244 // --------------------------------------------------------------------------
245
246 void ReportError (char * strError)
247 {
248 #ifdef WIN32  // !!! FIXME.  --ryan.
249         throw std::exception( strError);
250 #endif
251
252         /*      char errMsgCStr [256];
253         Str255 strErr;
254
255         sprintf (errMsgCStr, "%s", strError); 
256
257         // out as debug string
258         CToPStr (strErr, errMsgCStr);
259         DebugStr (strErr);
260         */
261 }
262
263 void SetupDSpFullScreen ()
264 {
265 #ifdef WIN32
266         LOGFUNC;
267
268         if (fullscreen)
269         {
270                 DEVMODE dmScreenSettings;
271                 memset( &dmScreenSettings, 0, sizeof( dmScreenSettings));
272                 dmScreenSettings.dmSize = sizeof( dmScreenSettings);
273                 dmScreenSettings.dmPelsWidth    = kContextWidth;
274                 dmScreenSettings.dmPelsHeight   = kContextHeight;
275                 dmScreenSettings.dmBitsPerPel   = kBitsPerPixel;
276                 dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
277
278                 // set video mode
279                 if (ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
280                 {
281                         ReportError( "Could not set display mode");
282                         return;
283                 }
284         }
285
286         ShowCursor(FALSE);
287 #endif
288 }
289
290
291 void ShutdownDSp ()
292 {
293 #ifdef WIN32
294         LOGFUNC;
295
296         if (fullscreen)
297         {
298                 ChangeDisplaySettings( NULL, 0);
299         }
300
301         ShowCursor(TRUE);
302 #endif
303 }
304
305
306 //-----------------------------------------------------------------------------------------------------------------------
307
308 // OpenGL Drawing
309
310 void DrawGL (Game & game)
311 {
312 #ifdef WIN32
313         if (hDC == 0)
314                 return;
315 #endif
316
317         game.DrawGLScene();
318 }
319
320
321 static KeyMap g_theKeys;
322
323 void SetKey( int key)
324 {
325     g_theKeys[ key >> 3] |= (1 << (key & 7));
326 }
327
328 void ClearKey( int key)
329 {
330     g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
331 }
332
333 void GetKeys(  unsigned char theKeys[16])
334 {
335     memcpy( theKeys, &g_theKeys, 16);
336 }
337
338 Boolean Button()
339 {
340     return g_button;
341 }
342
343 #if !USE_SDL
344 static void initSDLKeyTable(void) {}
345 #else
346 #define MAX_SDLKEYS SDLK_LAST
347 static unsigned short KeyTable[MAX_SDLKEYS];
348
349 static void initSDLKeyTable(void)
350 {
351     memset(KeyTable, 0xFF, sizeof (KeyTable));
352     KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
353     KeyTable[SDLK_TAB] = MAC_TAB_KEY;
354     KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
355     KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
356     KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
357     KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
358     KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
359     KeyTable[SDLK_END] = MAC_END_KEY;
360     KeyTable[SDLK_HOME] = MAC_HOME_KEY;
361     KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
362     KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
363     KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
364     KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
365     KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
366     KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
367     KeyTable[SDLK_0] = MAC_0_KEY;
368     KeyTable[SDLK_1] = MAC_1_KEY;
369     KeyTable[SDLK_2] = MAC_2_KEY;
370     KeyTable[SDLK_3] = MAC_3_KEY;
371     KeyTable[SDLK_4] = MAC_4_KEY;
372     KeyTable[SDLK_5] = MAC_5_KEY;
373     KeyTable[SDLK_6] = MAC_6_KEY;
374     KeyTable[SDLK_7] = MAC_7_KEY;
375     KeyTable[SDLK_8] = MAC_8_KEY;
376     KeyTable[SDLK_9] = MAC_9_KEY;
377     KeyTable[SDLK_a] = MAC_A_KEY;
378     KeyTable[SDLK_b] = MAC_B_KEY;
379     KeyTable[SDLK_c] = MAC_C_KEY;
380     KeyTable[SDLK_d] = MAC_D_KEY;
381     KeyTable[SDLK_e] = MAC_E_KEY;
382     KeyTable[SDLK_f] = MAC_F_KEY;
383     KeyTable[SDLK_g] = MAC_G_KEY;
384     KeyTable[SDLK_h] = MAC_H_KEY;
385     KeyTable[SDLK_i] = MAC_I_KEY;
386     KeyTable[SDLK_j] = MAC_J_KEY;
387     KeyTable[SDLK_k] = MAC_K_KEY;
388     KeyTable[SDLK_l] = MAC_L_KEY;
389     KeyTable[SDLK_m] = MAC_M_KEY;
390     KeyTable[SDLK_n] = MAC_N_KEY;
391     KeyTable[SDLK_o] = MAC_O_KEY;
392     KeyTable[SDLK_p] = MAC_P_KEY;
393     KeyTable[SDLK_q] = MAC_Q_KEY;
394     KeyTable[SDLK_r] = MAC_R_KEY;
395     KeyTable[SDLK_s] = MAC_S_KEY;
396     KeyTable[SDLK_t] = MAC_T_KEY;
397     KeyTable[SDLK_u] = MAC_U_KEY;
398     KeyTable[SDLK_v] = MAC_V_KEY;
399     KeyTable[SDLK_w] = MAC_W_KEY;
400     KeyTable[SDLK_x] = MAC_X_KEY;
401     KeyTable[SDLK_y] = MAC_Y_KEY;
402     KeyTable[SDLK_z] = MAC_Z_KEY;
403     KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
404     KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
405     KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
406     KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
407     KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
408     KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
409     KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
410     KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
411     KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
412     KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
413     KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
414     KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
415     KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
416     KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
417     KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
418     KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
419     KeyTable[SDLK_F1] = MAC_F1_KEY;
420     KeyTable[SDLK_F2] = MAC_F2_KEY;
421     KeyTable[SDLK_F3] = MAC_F3_KEY;
422     KeyTable[SDLK_F4] = MAC_F4_KEY;
423     KeyTable[SDLK_F5] = MAC_F5_KEY;
424     KeyTable[SDLK_F6] = MAC_F6_KEY;
425     KeyTable[SDLK_F7] = MAC_F7_KEY;
426     KeyTable[SDLK_F8] = MAC_F8_KEY;
427     KeyTable[SDLK_F9] = MAC_F9_KEY;
428     KeyTable[SDLK_F10] = MAC_F10_KEY;
429     KeyTable[SDLK_F11] = MAC_F11_KEY;
430     KeyTable[SDLK_F12] = MAC_F12_KEY;
431     KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
432     KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
433     KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
434     KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
435     KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
436     KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
437     KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
438     KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
439     KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
440     KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
441     KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
442 }
443
444 static inline int clamp_sdl_mouse_button(Uint8 button)
445 {
446     if (button == 2)   // right mouse button is button 3 in SDL.
447         button = 3;
448     else if (button == 3)
449         button = 2;
450
451     if ((button >= 1) && (button <= 3))
452         return button - 1;
453     return -1;
454 }
455
456 static void sdlEventProc(const SDL_Event &e, Game &game)
457 {
458     int val;
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                     SDL_GrabMode mode = SDL_GRAB_ON;
498                     if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
499                     {
500                         mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
501                         mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
502                     }
503                     SDL_WM_GrabInput(mode);
504                 }
505             }
506
507             else if (e.key.keysym.sym == SDLK_RETURN)
508             {
509                 if (e.key.keysym.mod & KMOD_ALT)
510                     SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
511             }
512
513             if (e.key.keysym.sym < SDLK_LAST)
514             {
515                 if (KeyTable[e.key.keysym.sym] != 0xffff)
516                     SetKey(KeyTable[e.key.keysym.sym]);
517             }
518
519             mod = SDL_GetModState();
520             if (mod & KMOD_CTRL)
521                 SetKey(MAC_CONTROL_KEY);
522             if (mod & KMOD_ALT)
523                 SetKey(MAC_OPTION_KEY);
524             if (mod & KMOD_SHIFT)
525                 SetKey(MAC_SHIFT_KEY);
526             if (mod & KMOD_CAPS)
527                 SetKey(MAC_CAPS_LOCK_KEY);
528
529             return;
530
531         case SDL_KEYUP:
532             if (e.key.keysym.sym < SDLK_LAST)
533             {
534                 if (KeyTable[e.key.keysym.sym] != 0xffff)
535                     ClearKey(KeyTable[e.key.keysym.sym]);
536             }
537
538             mod = SDL_GetModState();
539             if ((mod & KMOD_CTRL) == 0)
540                 ClearKey(MAC_CONTROL_KEY);
541             if ((mod & KMOD_ALT) == 0)
542                 ClearKey(MAC_OPTION_KEY);
543             if ((mod & KMOD_SHIFT) == 0)
544                 ClearKey(MAC_SHIFT_KEY);
545             if ((mod & KMOD_CAPS) == 0)
546                 ClearKey(MAC_CAPS_LOCK_KEY);
547             return;
548     }
549 }
550 #endif
551
552 // --------------------------------------------------------------------------
553
554 static Point gMidPoint;
555
556 Boolean SetUp (Game & game)
557 {
558         char string[10];
559
560         LOGFUNC;
561
562         randSeed = UpTime().lo;
563
564         osx = 0;
565         ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
566         detail=1;
567         ismotionblur=0;
568         usermousesensitivity=1;
569         kContextWidth=640;
570         kContextHeight=480;
571         kBitsPerPixel = 32;
572         floatjump=0;
573         cellophane=0;
574         texdetail=4;
575         autoslomo=1;
576         decals=1;
577         invertmouse=0;
578         bloodtoggle=0;
579         terraindetail=2;
580         foliage=1;
581         musictoggle=1;
582         trilinear=1;
583         gamespeed=1;
584         difficulty=1;
585         damageeffects=0;
586         texttoggle=1;
587         alwaysblur=0;
588         showpoints=0;
589         immediate=0;
590         velocityblur=0;
591
592         slomospeed=0.25;
593         slomofreq=8012;
594
595         volume = 0.8f;
596
597         game.crouchkey=MAC_SHIFT_KEY;
598         game.jumpkey=MAC_SPACE_KEY;
599         game.leftkey=MAC_A_KEY;
600         game.forwardkey=MAC_W_KEY;
601         game.backkey=MAC_S_KEY;
602         game.rightkey=MAC_D_KEY;
603         game.drawkey=MAC_E_KEY;
604         game.throwkey=MAC_Q_KEY;
605         game.attackkey=MAC_MOUSEBUTTON1;
606         game.chatkey=MAC_T_KEY;
607         numplayers=1;
608         ambientsound=1;
609         vblsync=0;
610         debugmode=0;
611
612         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
613
614         if(!ipstream) {
615                 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
616                 opstream << "Screenwidth:\n";
617                 opstream << kContextWidth;
618                 opstream << "\nScreenheight:\n";
619                 opstream << kContextHeight;
620                 opstream << "\nMouse sensitivity:\n";
621                 opstream << usermousesensitivity;
622                 opstream << "\nBlur(0,1):\n";
623                 opstream << ismotionblur;
624                 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
625                 opstream << detail;
626                 opstream << "\nFloating jump:\n";
627                 opstream << floatjump;
628                 opstream << "\nMouse jump:\n";
629                 opstream << mousejump;
630                 opstream << "\nAmbient sound:\n";
631                 opstream << ambientsound;
632                 opstream << "\nBlood (0,1,2):\n";
633                 opstream << bloodtoggle;
634                 opstream << "\nAuto slomo:\n";
635                 opstream << autoslomo;
636                 opstream << "\nFoliage:\n";
637                 opstream << foliage;
638                 opstream << "\nMusic:\n";
639                 opstream << musictoggle;
640                 opstream << "\nTrilinear:\n";
641                 opstream << trilinear;
642                 opstream << "\nDecals(shadows,blood puddles,etc):\n";
643                 opstream << decals;
644                 opstream << "\nInvert mouse:\n";
645                 opstream << invertmouse;
646                 opstream << "\nGamespeed:\n";
647                 opstream << gamespeed;
648                 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
649                 opstream << difficulty;
650                 opstream << "\nDamage effects(blackout, doublevision):\n";
651                 opstream << damageeffects;
652                 opstream << "\nText:\n";
653                 opstream << texttoggle;
654                 opstream << "\nDebug:\n";
655                 opstream << debugmode;
656                 opstream << "\nVBL Sync:\n";
657                 opstream << vblsync;
658                 opstream << "\nShow Points:\n";
659                 opstream << showpoints;
660                 opstream << "\nAlways Blur:\n";
661                 opstream << alwaysblur;
662                 opstream << "\nImmediate mode (turn on on G5):\n";
663                 opstream << immediate;
664                 opstream << "\nVelocity blur:\n";
665                 opstream << velocityblur;
666                 opstream << "\nVolume:\n";
667                 opstream << volume;
668                 opstream << "\nForward key:\n";
669                 opstream << KeyToChar(game.forwardkey);
670                 opstream << "\nBack key:\n";
671                 opstream << KeyToChar(game.backkey);
672                 opstream << "\nLeft key:\n";
673                 opstream << KeyToChar(game.leftkey);
674                 opstream << "\nRight key:\n";
675                 opstream << KeyToChar(game.rightkey);
676                 opstream << "\nJump key:\n";
677                 opstream << KeyToChar(game.jumpkey);
678                 opstream << "\nCrouch key:\n";
679                 opstream << KeyToChar(game.crouchkey);
680                 opstream << "\nDraw key:\n";
681                 opstream << KeyToChar(game.drawkey);
682                 opstream << "\nThrow key:\n";
683                 opstream << KeyToChar(game.throwkey);
684                 opstream << "\nAttack key:\n";
685                 opstream << KeyToChar(game.attackkey);
686                 opstream << "\nChat key:\n";
687                 opstream << KeyToChar(game.chatkey);
688                 opstream.close();
689         }
690         if(ipstream){
691                 int i;
692                 ipstream.ignore(256,'\n');
693                 ipstream >> kContextWidth;
694                 ipstream.ignore(256,'\n');
695                 ipstream.ignore(256,'\n');
696                 ipstream >> kContextHeight;
697                 ipstream.ignore(256,'\n');
698                 ipstream.ignore(256,'\n');
699                 ipstream >> usermousesensitivity;
700                 ipstream.ignore(256,'\n');
701                 ipstream.ignore(256,'\n');
702                 ipstream >> i;
703                 ismotionblur = (i != 0);
704                 ipstream.ignore(256,'\n');
705                 ipstream.ignore(256,'\n');
706                 ipstream >> detail;
707                 if(detail!=0)kBitsPerPixel=32;
708                 else kBitsPerPixel=16;
709                 ipstream.ignore(256,'\n');
710                 ipstream.ignore(256,'\n');
711                 ipstream >> i;
712                 floatjump = (i != 0);
713                 ipstream.ignore(256,'\n');
714                 ipstream.ignore(256,'\n');
715                 ipstream >> i;
716                 mousejump = (i != 0);
717                 ipstream.ignore(256,'\n');
718                 ipstream.ignore(256,'\n');
719                 ipstream >> i;
720                 ambientsound = (i != 0);
721                 ipstream.ignore(256,'\n');
722                 ipstream.ignore(256,'\n');
723                 ipstream >> bloodtoggle;
724                 ipstream.ignore(256,'\n');
725                 ipstream.ignore(256,'\n');
726                 ipstream >> i;
727                 autoslomo = (i != 0);
728                 ipstream.ignore(256,'\n');
729                 ipstream.ignore(256,'\n');
730                 ipstream >> i;
731                 foliage = (i != 0);
732                 ipstream.ignore(256,'\n');
733                 ipstream.ignore(256,'\n');
734                 ipstream >> i;
735                 musictoggle = (i != 0);
736                 ipstream.ignore(256,'\n');
737                 ipstream.ignore(256,'\n');
738                 ipstream >> i;
739                 trilinear = (i != 0);
740                 ipstream.ignore(256,'\n');
741                 ipstream.ignore(256,'\n');
742                 ipstream >> i;
743                 decals = (i != 0);
744                 ipstream.ignore(256,'\n');
745                 ipstream.ignore(256,'\n');
746                 ipstream >> i;
747                 invertmouse = (i != 0);
748                 ipstream.ignore(256,'\n');
749                 ipstream.ignore(256,'\n');
750                 ipstream >> gamespeed;
751                 oldgamespeed=gamespeed;
752                 if(oldgamespeed==0){
753                         gamespeed=1;
754                         oldgamespeed=1;
755                 }
756                 ipstream.ignore(256,'\n');
757                 ipstream.ignore(256,'\n');
758                 ipstream >> difficulty;
759                 ipstream.ignore(256,'\n');
760                 ipstream.ignore(256,'\n');
761                 ipstream >> i;
762                 damageeffects = (i != 0);
763                 ipstream.ignore(256,'\n');
764                 ipstream.ignore(256,'\n');
765                 ipstream >> i;
766                 texttoggle = (i != 0);
767                 ipstream.ignore(256,'\n');
768                 ipstream.ignore(256,'\n');
769                 ipstream >> i;
770                 debugmode = (i != 0);
771                 ipstream.ignore(256,'\n');
772                 ipstream.ignore(256,'\n');
773                 ipstream >> i;
774                 vblsync = (i != 0);
775                 ipstream.ignore(256,'\n');
776                 ipstream.ignore(256,'\n');
777                 ipstream >> i;
778                 showpoints = (i != 0);
779                 ipstream.ignore(256,'\n');
780                 ipstream.ignore(256,'\n');
781                 ipstream >> i;
782                 alwaysblur = (i != 0);
783                 ipstream.ignore(256,'\n');
784                 ipstream.ignore(256,'\n');
785                 ipstream >> i;
786                 immediate = (i != 0);
787                 ipstream.ignore(256,'\n');
788                 ipstream.ignore(256,'\n');
789                 ipstream >> i;
790                 velocityblur = (i != 0);
791                 ipstream.ignore(256,'\n');
792                 ipstream.ignore(256,'\n'); 
793                 ipstream >> volume;
794                 ipstream.ignore(256,'\n');
795                 ipstream.ignore(256,'\n'); 
796                 ipstream >> string;
797                 game.forwardkey=CharToKey(string);
798                 ipstream.ignore(256,'\n');
799                 ipstream.ignore(256,'\n');
800                 ipstream >> string;
801                 game.backkey=CharToKey(string);
802                 ipstream.ignore(256,'\n');
803                 ipstream.ignore(256,'\n');
804                 ipstream >> string;
805                 game.leftkey=CharToKey(string);
806                 ipstream.ignore(256,'\n');
807                 ipstream.ignore(256,'\n');
808                 ipstream >> string;
809                 game.rightkey=CharToKey(string);
810                 ipstream.ignore(256,'\n');
811                 ipstream.ignore(256,'\n');
812                 ipstream >> string;
813                 game.jumpkey=CharToKey(string);
814                 ipstream.ignore(256,'\n');
815                 ipstream.ignore(256,'\n');
816                 ipstream >> string;
817                 game.crouchkey=CharToKey(string);
818                 ipstream.ignore(256,'\n');
819                 ipstream.ignore(256,'\n');
820                 ipstream >> string;
821                 game.drawkey=CharToKey(string);
822                 ipstream.ignore(256,'\n');
823                 ipstream.ignore(256,'\n');
824                 ipstream >> string;
825                 game.throwkey=CharToKey(string);
826                 ipstream.ignore(256,'\n');
827                 ipstream.ignore(256,'\n');
828                 ipstream >> string;
829                 game.attackkey=CharToKey(string);
830                 ipstream.ignore(256,'\n');
831                 ipstream.ignore(256,'\n');
832                 ipstream >> string;
833                 game.chatkey=CharToKey(string);
834                 ipstream.close();
835
836                 if(detail>2)detail=2;
837                 if(detail<0)detail=0;
838                 if(screenwidth>3000)screenwidth=640;
839                 if(screenwidth<0)screenwidth=640;
840                 if(screenheight>3000)screenheight=480;
841                 if(screenheight<0)screenheight=480;
842         }
843         if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
844                 kBitsPerPixel=16;
845         }
846
847
848         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
849
850         SetupDSpFullScreen();
851
852 #if USE_SDL
853     if (!SDL_WasInit(SDL_INIT_VIDEO))
854     {
855         if (SDL_Init(SDL_INIT_VIDEO) == -1)
856         {
857             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
858             return false;
859         }
860
861         if (SDL_GL_LoadLibrary(NULL) == -1)
862         {
863             fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
864             SDL_Quit();
865             return false;
866         }
867     }
868
869     Uint32 sdlflags = SDL_OPENGL;
870     if (!cmdline("windowed"))
871         sdlflags |= SDL_FULLSCREEN;
872
873     SDL_WM_SetCaption("Lugaru", "Lugaru");
874
875     SDL_ShowCursor(0);
876
877     if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
878     {
879         fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
880         return false;
881     }
882
883     if (!lookup_all_glsyms())
884     {
885         SDL_Quit();
886         return false;
887     }
888
889     if (!cmdline("nomousegrab"))
890         SDL_WM_GrabInput(SDL_GRAB_ON);
891
892 #elif (defined WIN32)
893         //------------------------------------------------------------------
894         // create window
895         int x = 0, y = 0;
896         RECT r = {0, 0, kContextWidth-1, kContextHeight-1};
897         DWORD dwStyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE;
898         DWORD dwExStyle = WS_EX_APPWINDOW;
899
900         if (fullscreen)
901         {
902                 dwStyle |= WS_POPUP;
903         }
904         else
905         {
906
907                 dwStyle |= WS_OVERLAPPEDWINDOW;
908                 dwExStyle |= WS_EX_WINDOWEDGE;
909         }
910
911         AdjustWindowRectEx(&r, dwStyle, FALSE, dwExStyle);
912
913         if (!fullscreen)
914         {
915                 x = (GetSystemMetrics(SM_CXSCREEN) >> 1) - ((r.right - r.left + 1) >> 1);
916                 y = (GetSystemMetrics(SM_CYSCREEN) >> 1) - ((r.bottom - r.top + 1) >> 1);
917         }
918
919         g_windowHandle=CreateWindowEx(
920                 dwExStyle,
921                 g_wndClassName, "Lugaru", dwStyle,
922                 x, y,
923 //              kContextWidth, kContextHeight,
924                 r.right - r.left + 1, r.bottom - r.top + 1,
925                 NULL,NULL,g_appInstance,NULL );
926         if (!g_windowHandle)
927         {
928                 ReportError("Could not create window");
929                 return false;
930         }
931
932         //------------------------------------------------------------------
933         // setup OpenGL
934
935         static PIXELFORMATDESCRIPTOR pfd =
936         {
937                 sizeof(PIXELFORMATDESCRIPTOR),                          // Size Of This Pixel Format Descriptor
938                         1,                                                                                      // Version Number
939                         PFD_DRAW_TO_WINDOW |                                            // Format Must Support Window
940                         PFD_SUPPORT_OPENGL |                                            // Format Must Support OpenGL
941                         PFD_DOUBLEBUFFER,                                                       // Must Support Double Buffering
942                         PFD_TYPE_RGBA,                                                          // Request An RGBA Format
943                         kBitsPerPixel,                                                          // Select Our Color Depth
944                         0, 0, 0, 0, 0, 0,                                                       // Color Bits Ignored
945                         0,                                                                                      // No Alpha Buffer
946                         0,                                                                                      // Shift Bit Ignored
947                         0,                                                                                      // No Accumulation Buffer
948                         0, 0, 0, 0,                                                                     // Accumulation Bits Ignored
949                         16,                                                                                     // 16Bit Z-Buffer (Depth Buffer)  
950                         0,                                                                                      // No Stencil Buffer
951                         0,                                                                                      // No Auxiliary Buffer
952                         PFD_MAIN_PLANE,                                                         // Main Drawing Layer
953                         0,                                                                                      // Reserved
954                         0, 0, 0                                                                         // Layer Masks Ignored
955         };
956
957         if (!(hDC = GetDC( g_windowHandle)))
958                 ReportError( "Could not get device context");
959
960         GLuint PixelFormat;
961         if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))
962         {
963                 ReportError( "Could not find appropriate pixel format");
964                 return false;
965         }
966
967         if (!DescribePixelFormat(hDC, PixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd))
968         {
969                 ReportError( "Could not retrieve pixel format");
970                 return false;
971         }
972
973         if (!SetPixelFormat( hDC, PixelFormat, &pfd))
974         {
975                 ReportError( "Could not set pixel format");
976                 return false;
977         }
978
979         if (!(hRC = wglCreateContext(hDC)))
980         {
981                 ReportError( "Could not create rendering context");
982                 return false;
983         }
984
985         if (!wglMakeCurrent(hDC, hRC))
986         {
987                 ReportError( "Could not activate rendering context");
988                 return false;
989         }
990
991         if (fullscreen)
992         {
993                 // Place the window above all topmost windows
994                 SetWindowPos( g_windowHandle, HWND_TOPMOST, 0,0,0,0,
995                         SWP_NOMOVE | SWP_NOSIZE );
996         }
997
998         SetForegroundWindow(g_windowHandle);
999         SetFocus(g_windowHandle);
1000 #endif
1001
1002         glClear( GL_COLOR_BUFFER_BIT );
1003         swap_gl_buffers();
1004
1005         // clear all states
1006         glDisable( GL_ALPHA_TEST);
1007         glDisable( GL_BLEND);
1008         glDisable( GL_DEPTH_TEST);
1009         //      glDisable( GL_DITHER);
1010         glDisable( GL_FOG);
1011         glDisable( GL_LIGHTING);
1012         glDisable( GL_LOGIC_OP);
1013         glDisable( GL_STENCIL_TEST);
1014         glDisable( GL_TEXTURE_1D);
1015         glDisable( GL_TEXTURE_2D);
1016         glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
1017         glPixelTransferi( GL_RED_SCALE, 1);
1018         glPixelTransferi( GL_RED_BIAS, 0);
1019         glPixelTransferi( GL_GREEN_SCALE, 1);
1020         glPixelTransferi( GL_GREEN_BIAS, 0);
1021         glPixelTransferi( GL_BLUE_SCALE, 1);
1022         glPixelTransferi( GL_BLUE_BIAS, 0);
1023         glPixelTransferi( GL_ALPHA_SCALE, 1);
1024         glPixelTransferi( GL_ALPHA_BIAS, 0);
1025
1026         // set initial rendering states
1027         glShadeModel( GL_SMOOTH);
1028         glClearDepth( 1.0f);
1029         glDepthFunc( GL_LEQUAL);
1030         glDepthMask( GL_TRUE);
1031         //      glDepthRange( FRONT_CLIP, BACK_CLIP);
1032         glEnable( GL_DEPTH_TEST);
1033         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
1034         glCullFace( GL_FRONT);
1035         glEnable( GL_CULL_FACE);
1036         glEnable( GL_LIGHTING);
1037 //      glEnable( GL_LIGHT_MODEL_AMBIENT);
1038         glEnable( GL_DITHER);
1039         glEnable( GL_COLOR_MATERIAL);
1040         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1041         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1042         glAlphaFunc( GL_GREATER, 0.5f);
1043
1044 #if USE_DEVIL
1045         if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION ||
1046                 iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION ||
1047                 ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION)
1048         {
1049                 ReportError("DevIL version is different...exiting!\n");
1050                 return false;
1051         }
1052
1053         ilInit();
1054         iluInit();
1055         ilutInit();
1056
1057         ilutRenderer(ILUT_OPENGL);
1058
1059         ilEnable(IL_ORIGIN_SET);
1060         ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
1061 #endif
1062
1063         GLint width = kContextWidth;
1064         GLint height = kContextHeight;
1065         gMidPoint.h = width / 2;
1066         gMidPoint.v = height / 2;
1067         screenwidth=width;
1068         screenheight=height;
1069
1070         game.newdetail=detail;
1071         game.newscreenwidth=screenwidth;
1072         game.newscreenheight=screenheight;
1073
1074         game.InitGame();
1075
1076         return true;
1077 }
1078
1079
1080 static void DoMouse(Game & game)
1081 {
1082 #if USE_SDL
1083         if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1084         {
1085                 game.deltah *= usermousesensitivity;
1086                 game.deltav *= usermousesensitivity;
1087                 game.mousecoordh += game.deltah;
1088                 game.mousecoordv += game.deltav;
1089         if (game.mousecoordh < 0)
1090             game.mousecoordh = 0;
1091         else if (game.mousecoordh >= kContextWidth)
1092             game.mousecoordh = kContextWidth - 1;
1093         if (game.mousecoordv < 0)
1094             game.mousecoordv = 0;
1095         else if (game.mousecoordv >= kContextHeight)
1096             game.mousecoordv = kContextHeight - 1;
1097         }
1098 #else
1099         static Point lastMouse = {-1,-1};
1100         Point globalMouse;
1101
1102         POINT pos;
1103         GetCursorPos(&pos);
1104         ScreenToClient(g_windowHandle, &pos);
1105         globalMouse.h = pos.x;
1106         globalMouse.v = pos.y;
1107
1108         if (lastMouse.h == globalMouse.h && lastMouse.v == globalMouse.v)
1109         {
1110                 game.deltah=0;
1111                 game.deltav=0;
1112         }
1113         else
1114         {
1115                 static Point virtualMouse = {0,0};
1116                 delta = globalMouse;
1117
1118                 delta.h -= lastMouse.h;
1119                 delta.v -= lastMouse.v;
1120                 lastMouse.h = pos.x;
1121                 lastMouse.v = pos.y;
1122
1123                 if(mainmenu||(abs(delta.h)<10*realmultiplier*1000&&abs(delta.v)<10*realmultiplier*1000)){
1124                         game.deltah=delta.h*usermousesensitivity;
1125                         game.deltav=delta.v*usermousesensitivity;
1126                         game.mousecoordh=globalMouse.h;
1127                         game.mousecoordv=globalMouse.v;
1128                 }
1129
1130                 if(!mainmenu)
1131                 {
1132                         if(lastMouse.h>gMidPoint.h+100||lastMouse.h<gMidPoint.h-100||lastMouse.v>gMidPoint.v+100||lastMouse.v<gMidPoint.v-100){
1133                                 pos.x = gMidPoint.h;
1134                                 pos.y = gMidPoint.v;
1135                                 ClientToScreen(g_windowHandle, &pos);
1136                                 //SetCursorPos( gMidPoint.h,gMidPoint.v);
1137                                 SetCursorPos(pos.x, pos.y);
1138                                 lastMouse = gMidPoint;
1139                         }
1140                 }
1141         }
1142 #endif
1143 }
1144
1145
1146
1147 // --------------------------------------------------------------------------
1148
1149 void DoKey (SInt8 theKey, SInt8 theCode)
1150 {
1151         // do nothing
1152 }
1153
1154 // --------------------------------------------------------------------------
1155
1156
1157
1158 void DoFrameRate (int update)
1159 {       
1160         static long frames = 0;
1161
1162         static AbsoluteTime time = {0,0};
1163         static AbsoluteTime frametime = {0,0};
1164         AbsoluteTime currTime = UpTime ();
1165         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1166
1167         if (0 > deltaTime)      // if negative microseconds
1168                 deltaTime /= -1000000.0;
1169         else                            // else milliseconds
1170                 deltaTime /= 1000.0;
1171
1172         multiplier=deltaTime;
1173         if(multiplier<.001)multiplier=.001;
1174         if(multiplier>10)multiplier=10;
1175         if(update)frametime = currTime; // reset for next time interval
1176
1177         deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1178
1179         if (0 > deltaTime)      // if negative microseconds
1180                 deltaTime /= -1000000.0;
1181         else                            // else milliseconds
1182                 deltaTime /= 1000.0;
1183         frames++;
1184         if (0.001 <= deltaTime) // has update interval passed
1185         {
1186                 if(update){
1187                         time = currTime;        // reset for next time interval
1188                         frames = 0;
1189                 }
1190         }
1191 }
1192
1193
1194 void DoUpdate (Game & game)
1195 {
1196         static float sps=200;
1197         static int count;
1198         static float oldmult;
1199
1200         DoFrameRate(1);
1201         if(multiplier>.6)multiplier=.6;
1202
1203         game.fps=1/multiplier;
1204
1205         count = multiplier*sps;
1206         if(count<2)count=2;
1207         //if(count>10)count=10;
1208
1209         realmultiplier=multiplier;
1210         multiplier*=gamespeed;
1211         if(difficulty==1)multiplier*=.9;
1212         if(difficulty==0)multiplier*=.8;
1213
1214         if(game.loading==4)multiplier*=.00001;
1215         //multiplier*.9;
1216         if(slomo&&!mainmenu)multiplier*=slomospeed;
1217         //if(freeze)multiplier*=0.00001;
1218         oldmult=multiplier;
1219         multiplier/=(float)count;
1220
1221         DoMouse(game);
1222
1223         game.TickOnce();
1224
1225         for(int i=0;i<count;i++)
1226         {
1227                 game.Tick();
1228         }
1229         multiplier=oldmult;
1230
1231         game.TickOnceAfter();
1232 /* - Debug code to test how many channels were active on average per frame
1233         static long frames = 0;
1234
1235         static AbsoluteTime start = {0,0};
1236         AbsoluteTime currTime = UpTime ();
1237         static int num_channels = 0;
1238         
1239         num_channels += FSOUND_GetChannelsPlaying();
1240         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1241
1242         if (0 > deltaTime)      // if negative microseconds
1243                 deltaTime /= -1000000.0;
1244         else                            // else milliseconds
1245                 deltaTime /= 1000.0;
1246
1247         ++frames;
1248
1249         if (deltaTime >= 1)
1250         {
1251                 start = currTime;
1252                 float avg_channels = (float)num_channels / (float)frames;
1253
1254                 ofstream opstream("log.txt",ios::app); 
1255                 opstream << "Average frame count: ";
1256                 opstream << frames;
1257                 opstream << " frames - ";
1258                 opstream << avg_channels;
1259                 opstream << " per frame.\n";
1260                 opstream.close();
1261
1262                 frames = 0;
1263                 num_channels = 0;
1264         }
1265 */
1266         DrawGL (game);
1267 }
1268
1269 // --------------------------------------------------------------------------
1270
1271
1272 void CleanUp (void)
1273 {
1274         LOGFUNC;
1275
1276 //      game.Dispose();
1277
1278 #if USE_DEVIL
1279         ilShutDown();
1280 #endif
1281
1282 #if USE_SDL
1283     SDL_Quit();
1284     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1285     #include "glstubs.h"
1286     #undef GL_FUNC
1287     // cheat here...static destructors are calling glDeleteTexture() after
1288     //  the context is destroyed and libGL unloaded by SDL_Quit().
1289     pglDeleteTextures = glDeleteTextures_doNothing;
1290
1291 #elif (defined WIN32)
1292         if (hRC)
1293         {
1294                 wglMakeCurrent( NULL, NULL);
1295                 wglDeleteContext( hRC);
1296                 hRC = NULL;
1297         }
1298
1299         if (hDC)
1300         {
1301                 ReleaseDC( g_windowHandle, hDC);
1302                 hDC = NULL;
1303         }
1304
1305         if (g_windowHandle)
1306         {
1307                 ShowWindow( g_windowHandle, SW_HIDE );
1308                 DestroyWindow( g_windowHandle);
1309                 g_windowHandle = NULL;
1310         }
1311
1312         ShutdownDSp ();
1313         ClipCursor(NULL);
1314 #endif
1315 }
1316
1317 // --------------------------------------------------------------------------
1318
1319 static bool g_focused = true;
1320
1321
1322 static bool IsFocused()
1323 {
1324 #ifdef WIN32
1325         if (!g_focused)
1326                 return false;
1327
1328         if (GetActiveWindow() != g_windowHandle)
1329                 return false;
1330
1331         if (IsIconic( g_windowHandle))
1332                 return false;
1333 #endif
1334
1335         return true;
1336 }
1337
1338
1339 static void launch_web_browser(const char *url)
1340 {
1341 #ifdef WIN32
1342     ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1343
1344 #elif (defined(__APPLE__) && defined(__MACH__))
1345     const char *fmt = "open '%s'";
1346     const size_t len = strlen(fmt) + strlen(url) + 16;
1347     char *buf = new char[len];
1348     snprintf(buf, len, fmt, url);
1349     system(buf);
1350     delete[] buf;
1351
1352 #elif PLATFORM_LINUX
1353     const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1354     const size_t len = strlen(fmt) + strlen(url) + 16;
1355     char *buf = new char[len];
1356     snprintf(buf, len, fmt, url);
1357     system(buf);
1358     delete[] buf;
1359 #endif
1360 }
1361
1362
1363 #ifndef WIN32
1364 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1365 static char *findBinaryInPath(const char *bin, char *envr)
1366 {
1367     size_t alloc_size = 0;
1368     char *exe = NULL;
1369     char *start = envr;
1370     char *ptr;
1371
1372     do
1373     {
1374         size_t size;
1375         ptr = strchr(start, ':');  /* find next $PATH separator. */
1376         if (ptr)
1377             *ptr = '\0';
1378
1379         size = strlen(start) + strlen(bin) + 2;
1380         if (size > alloc_size)
1381         {
1382             char *x = (char *) realloc(exe, size);
1383             if (x == NULL)
1384             {
1385                 if (exe != NULL)
1386                     free(exe);
1387                 return(NULL);
1388             } /* if */
1389
1390             alloc_size = size;
1391             exe = x;
1392         } /* if */
1393
1394         /* build full binary path... */
1395         strcpy(exe, start);
1396         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1397             strcat(exe, "/");
1398         strcat(exe, bin);
1399
1400         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
1401         {
1402             strcpy(exe, start);  /* i'm lazy. piss off. */
1403             return(exe);
1404         } /* if */
1405
1406         start = ptr + 1;  /* start points to beginning of next element. */
1407     } while (ptr != NULL);
1408
1409     if (exe != NULL)
1410         free(exe);
1411
1412     return(NULL);  /* doesn't exist in path. */
1413 } /* findBinaryInPath */
1414
1415
1416 char *calcBaseDir(const char *argv0)
1417 {
1418     /* If there isn't a path on argv0, then look through the $PATH for it. */
1419     char *retval;
1420     char *envr;
1421
1422     char *ptr = strrchr(argv0, '/');
1423     if (strchr(argv0, '/'))
1424     {
1425         retval = strdup(argv0);
1426         if (retval)
1427             *(strrchr(retval, '/')) = '\0';
1428         return(retval);
1429     }
1430
1431     envr = getenv("PATH");
1432     if (!envr) return NULL;
1433     envr = strdup(envr);
1434     if (!envr) return NULL;
1435     retval = findBinaryInPath(argv0, envr);
1436     free(envr);
1437     return(retval);
1438 }
1439
1440 static inline void chdirToAppPath(const char *argv0)
1441 {
1442     char *dir = calcBaseDir(argv0);
1443     if (dir)
1444     {
1445         #if (defined(__APPLE__) && defined(__MACH__))
1446         // Chop off /Contents/MacOS if it's at the end of the string, so we
1447         //  land in the base of the app bundle.
1448         const size_t len = strlen(dir);
1449         const char *bundledirs = "/Contents/MacOS";
1450         const size_t bundledirslen = strlen(bundledirs);
1451         if (len > bundledirslen)
1452         {
1453             char *ptr = (dir + len) - bundledirslen;
1454             if (strcasecmp(ptr, bundledirs) == 0)
1455                 *ptr = '\0';
1456         }
1457         #endif
1458         chdir(dir);
1459         free(dir);
1460     }
1461 }
1462 #endif
1463
1464
1465 int main(int argc, char **argv)
1466 {
1467     _argc = argc;
1468     _argv = argv;
1469 #ifndef WIN32
1470     chdirToAppPath(argv[0]);
1471 #endif
1472
1473         LOGFUNC;
1474
1475 #ifndef WIN32  // this is in WinMain, too.
1476         logger.start(true);
1477         memset( &g_theKeys, 0, sizeof( KeyMap));
1478 #endif
1479
1480     initSDLKeyTable();
1481
1482         try
1483         {
1484                 bool regnow = false;
1485                 {
1486                         Game game;
1487                         pgame = &game;
1488
1489                         //ofstream os("error.txt");
1490                         //os.close();
1491                         //ofstream os("log.txt");
1492                         //os.close();
1493
1494                         if (!SetUp (game))
1495                 return 42;
1496
1497                         while (!gDone&&!game.quit&&(!game.tryquit||!game.registered))
1498                         {
1499                                 if (IsFocused())
1500                                 {
1501                                         gameFocused = true;
1502
1503                                         // check windows messages
1504                                         #if USE_SDL
1505                                         game.deltah = 0;
1506                                         game.deltav = 0;
1507                                         SDL_Event e;
1508                                         // message pump
1509                                         while( SDL_PollEvent( &e ) )
1510                                         {
1511                                                 if( e.type == SDL_QUIT )
1512                                                 {
1513                                                         gDone=true;
1514                                                         break;
1515                                                 }
1516                                                 sdlEventProc(e, game);
1517                                         }
1518
1519                                         #elif (defined WIN32)
1520                                         MSG msg;
1521                                         // message pump
1522                                         while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE | PM_NOYIELD ) )
1523                                         {
1524                                                 if( msg.message == WM_QUIT )
1525                                                 {
1526                                                         gDone=true;
1527                                                         break;
1528                                                 }
1529                                                 else
1530                                                 {
1531                                                         TranslateMessage( &msg );
1532                                                         DispatchMessage( &msg );
1533                                                 }
1534                                         }
1535                                         #endif
1536
1537                                         // game
1538                                         DoUpdate(game);
1539                                 }
1540                                 else
1541                                 {
1542                                         if (gameFocused)
1543                                         {
1544                                                 // allow game chance to pause
1545                                                 gameFocused = false;
1546                                                 DoUpdate(game);
1547                                         }
1548
1549                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1550                     #ifdef WIN32
1551                                         MSG msg;
1552                                         BOOL bRet;
1553                                         //if (GetMessage( &msg, g_windowHandle, 0, 0 ))
1554                                         /*if (GetMessage( &msg, NULL, 0, 0 ))
1555                                         {
1556                                                 TranslateMessage(&msg);
1557                                                 DispatchMessage(&msg);
1558                                         }*/
1559                                         if ( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
1560                                         { 
1561                                                 if (bRet <= 0)
1562                                                 {
1563                                                         // handle the error and possibly exit
1564                                                         gDone=true;
1565                                                 }
1566                                                 else
1567                                                 {
1568                                                         TranslateMessage(&msg); 
1569                                                         DispatchMessage(&msg); 
1570                                                 }
1571                                         }
1572                     #else
1573                     STUBBED("give up CPU but sniff the event queue");
1574                     #endif
1575                                 }
1576                         }
1577
1578                         regnow = game.registernow;
1579                 }
1580                 pgame = 0;
1581
1582                 CleanUp ();
1583 //              if(game.registernow){
1584                 if(regnow)
1585                 {
1586             #if (defined(__APPLE__) && defined(__MACH__))
1587             launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1588             #elif PLATFORM_LINUX
1589             launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1590             #else
1591             launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1592             #endif
1593                 }
1594
1595         #if PLATFORM_LINUX  // (this may not be necessary any more.)
1596         _exit(0);  // !!! FIXME: hack...crashes on exit!
1597         #endif
1598                 return 0;
1599         }
1600         catch (const std::exception& error)
1601         {
1602                 CleanUp();
1603
1604                 std::string e = "Caught exception: ";
1605                 e += error.what();
1606
1607                 LOG(e, Logger::LOG_ERR);
1608
1609                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1610         }
1611
1612         CleanUp();
1613
1614         return -1;
1615 }
1616
1617
1618
1619         // --------------------------------------------------------------------------
1620
1621 #ifdef WIN32
1622 #define MAX_WINKEYS 256
1623         static unsigned short KeyTable[MAX_WINKEYS]=
1624         {
1625                 0xffff,  // (0)
1626                         MAC_MOUSEBUTTON1,  // VK_LBUTTON        (1)
1627                         MAC_MOUSEBUTTON2,  // VK_RBUTTON        (2)
1628                         0xffff,  // VK_CANCEL   (3)
1629                         0xffff,  // VK_MBUTTON  (4)
1630                         0xffff,  // (5)
1631                         0xffff,  // (6)
1632                         0xffff,  // (7)
1633                         MAC_DELETE_KEY,  // VK_BACK     (8)
1634                         MAC_TAB_KEY,  // VK_TAB (9)
1635                         0xffff,  // (10)
1636                         0xffff,  // (11)
1637                         0xffff,  // VK_CLEAR    (12)
1638                         MAC_RETURN_KEY,  // VK_RETURN   (13)
1639                         0xffff,  // (14)
1640                         0xffff,  // (15)
1641                         MAC_SHIFT_KEY,  // VK_SHIFT     (16)
1642                         MAC_CONTROL_KEY,  // VK_CONTROL (17)
1643                         MAC_OPTION_KEY,  // VK_MENU     (18)
1644                         0xffff,  // VK_PAUSE    (19)
1645                         MAC_CAPS_LOCK_KEY,  // #define VK_CAPITAL       (20)
1646                         0xffff,  // (21)
1647                         0xffff,  // (22)
1648                         0xffff,  // (23)
1649                         0xffff,  // (24)
1650                         0xffff,  // (25)
1651                         0xffff,  // (26)
1652                         MAC_ESCAPE_KEY,  // VK_ESCAPE   (27)
1653                         0xffff,  // (28)
1654                         0xffff,  // (29)
1655                         0xffff,  // (30)
1656                         0xffff,  // (31)
1657                         MAC_SPACE_KEY,  // VK_SPACE     (32)
1658                         MAC_PAGE_UP_KEY,  // VK_PRIOR   (33)
1659                         MAC_PAGE_DOWN_KEY,  // VK_NEXT  (34)
1660                         MAC_END_KEY,  // VK_END (35)
1661                         MAC_HOME_KEY,  // VK_HOME       (36)
1662                         MAC_ARROW_LEFT_KEY,  // VK_LEFT (37)
1663                         MAC_ARROW_UP_KEY,  // VK_UP     (38)
1664                         MAC_ARROW_RIGHT_KEY,  // VK_RIGHT       (39)
1665                         MAC_ARROW_DOWN_KEY,  // VK_DOWN (40)
1666                         0xffff,  // VK_SELECT   (41)
1667                         0xffff,  // VK_PRINT    (42)
1668                         0xffff,  // VK_EXECUTE  (43)
1669                         0xffff,  // VK_SNAPSHOT (44)
1670                         MAC_INSERT_KEY,  // VK_INSERT   (45)
1671                         MAC_DEL_KEY,  // VK_DELETE      (46)
1672                         0xffff,  // VK_HELP     (47)
1673                         MAC_0_KEY,  // VK_0     (48)
1674                         MAC_1_KEY,  // VK_1     (49)
1675                         MAC_2_KEY,  // VK_2     (50)
1676                         MAC_3_KEY,  // VK_3     (51)
1677                         MAC_4_KEY,  // VK_4     (52)
1678                         MAC_5_KEY,  // VK_5     (53)
1679                         MAC_6_KEY,  // VK_6     (54)
1680                         MAC_7_KEY,  // VK_7     (55)
1681                         MAC_8_KEY,  // VK_8     (56)
1682                         MAC_9_KEY,  // VK_9     (57)
1683                         0xffff,  // (58)
1684                         0xffff,  // (59)
1685                         0xffff,  // (60)
1686                         0xffff,  // (61)
1687                         0xffff,  // (62)
1688                         0xffff,  // (63)
1689                         0xffff,  // (64)
1690                         MAC_A_KEY,  // VK_A     (65)
1691                         MAC_B_KEY,  // VK_B     (66)
1692                         MAC_C_KEY,  // VK_C     (67)
1693                         MAC_D_KEY,  // VK_D     (68)
1694                         MAC_E_KEY,  // VK_E     (69)
1695                         MAC_F_KEY,  // VK_F     (70)
1696                         MAC_G_KEY,  // VK_G     (71)
1697                         MAC_H_KEY,  // VK_H     (72)
1698                         MAC_I_KEY,  // VK_I     (73)
1699                         MAC_J_KEY,  // VK_J     (74)
1700                         MAC_K_KEY,  // VK_K     (75)
1701                         MAC_L_KEY,  // VK_L     (76)
1702                         MAC_M_KEY,  // VK_M     (77)
1703                         MAC_N_KEY,  // VK_N     (78)
1704                         MAC_O_KEY,  // VK_O     (79)
1705                         MAC_P_KEY,  // VK_P     (80)
1706                         MAC_Q_KEY,  // VK_Q     (81)
1707                         MAC_R_KEY,  // VK_R     (82)
1708                         MAC_S_KEY,  // VK_S     (83)
1709                         MAC_T_KEY,  // VK_T     (84)
1710                         MAC_U_KEY,  // VK_U     (85)
1711                         MAC_V_KEY,  // VK_V     (86)
1712                         MAC_W_KEY,  // VK_W     (87)
1713                         MAC_X_KEY,  // VK_X     (88)
1714                         MAC_Y_KEY,  // VK_Y     (89)
1715                         MAC_Z_KEY,  // VK_Z     (90)
1716                         0xffff,  // (91)
1717                         0xffff,  // (92)
1718                         0xffff,  // (93)
1719                         0xffff,  // (94)
1720                         0xffff,  // (95)
1721                         MAC_NUMPAD_0_KEY,  // VK_NUMPAD0        (96)
1722                         MAC_NUMPAD_1_KEY,  // VK_NUMPAD1        (97)
1723                         MAC_NUMPAD_2_KEY,  // VK_NUMPAD2        (98)
1724                         MAC_NUMPAD_3_KEY,  // VK_NUMPAD3        (99)
1725                         MAC_NUMPAD_4_KEY,  // VK_NUMPAD4        (100)
1726                         MAC_NUMPAD_5_KEY,  // VK_NUMPAD5        (101)
1727                         MAC_NUMPAD_6_KEY,  // VK_NUMPAD6        (102)
1728                         MAC_NUMPAD_7_KEY,  // VK_NUMPAD7        (103)
1729                         MAC_NUMPAD_8_KEY,  // VK_NUMPAD8        (104)
1730                         MAC_NUMPAD_9_KEY,  // VK_NUMPAD9        (105)
1731                         MAC_NUMPAD_ASTERISK_KEY,  // VK_MULTIPLY        (106)
1732                         MAC_NUMPAD_PLUS_KEY,  // VK_ADD (107)
1733                         MAC_NUMPAD_ENTER_KEY,  // VK_SEPARATOR  (108)
1734                         MAC_NUMPAD_MINUS_KEY,  // VK_SUBTRACT   (109)
1735                         MAC_NUMPAD_PERIOD_KEY,  // VK_DECIMAL   (110)
1736                         MAC_NUMPAD_SLASH_KEY,  // VK_DIVIDE     (111)
1737                         MAC_F1_KEY,  // VK_F1   (112)
1738                         MAC_F2_KEY,  // VK_F2   (113)
1739                         MAC_F3_KEY,  // VK_F3   (114)
1740                         MAC_F4_KEY,  // VK_F4   (115)
1741                         MAC_F5_KEY,  // VK_F5   (116)
1742                         MAC_F6_KEY,  // VK_F6   (117)
1743                         MAC_F7_KEY,  // VK_F7   (118)
1744                         MAC_F8_KEY,  // VK_F8   (119)
1745                         MAC_F9_KEY,  // VK_F9   (120)
1746                         MAC_F10_KEY,  // VK_F10 (121)
1747                         MAC_F11_KEY,  // VK_F11 (122)
1748                         MAC_F12_KEY,  // VK_F12 (123)
1749                         0xffff,  // (124)
1750                         0xffff,  // (125)
1751                         0xffff,  // (126)
1752                         0xffff,  // (127)
1753                         0xffff,  // (128)
1754                         0xffff,  // (129)
1755                         0xffff,  // (130)
1756                         0xffff,  // (131)
1757                         0xffff,  // (132)
1758                         0xffff,  // (133)
1759                         0xffff,  // (134)
1760                         0xffff,  // (135)
1761                         0xffff,  // (136)
1762                         0xffff,  // (137)
1763                         0xffff,  // (138)
1764                         0xffff,  // (139)
1765                         0xffff,  // (130)
1766                         0xffff,  // (141)
1767                         0xffff,  // (142)
1768                         0xffff,  // (143)
1769                         0xffff,  // VK_NUMLOCK  (144)
1770                         0xffff,  // VK_SCROLL   (145)
1771                         0xffff,  // (146)
1772                         0xffff,  // (147)
1773                         0xffff,  // (148)
1774                         0xffff,  // (149)
1775                         0xffff,  // (150)
1776                         0xffff,  // (151)
1777                         0xffff,  // (152)
1778                         0xffff,  // (153)
1779                         0xffff,  // (154)
1780                         0xffff,  // (155)
1781                         0xffff,  // (156)
1782                         0xffff,  // (157)
1783                         0xffff,  // (158)
1784                         0xffff,  // (159)
1785                         MAC_SHIFT_KEY,  // VK_LSHIFT    (160)
1786                         MAC_SHIFT_KEY,  // VK_RSHIFT    (161)
1787                         MAC_CONTROL_KEY,  // VK_LCONTROL        (162)
1788                         MAC_CONTROL_KEY,  // VK_RCONTROL        (163)
1789                         MAC_OPTION_KEY,  // VK_LMENU    (164)
1790                         MAC_OPTION_KEY,  // VK_RMENU    (165)
1791                         0xffff,  // (166)
1792                         0xffff,  // (167)
1793                         0xffff,  // (168)
1794                         0xffff,  // (169)
1795                         0xffff,  // (170)
1796                         0xffff,  // (171)
1797                         0xffff,  // (172)
1798                         0xffff,  // (173)
1799                         0xffff,  // (174)
1800                         0xffff,  // (175)
1801                         0xffff,  // (176)
1802                         0xffff,  // (177)
1803                         0xffff,  // (178)
1804                         0xffff,  // (179)
1805                         0xffff,  // (180)
1806                         0xffff,  // (181)
1807                         0xffff,  // (182)
1808                         0xffff,  // (183)
1809                         0xffff,  // (184)
1810                         0xffff,  // (185)
1811                         MAC_SEMICOLON_KEY,  // (186)
1812                         MAC_PLUS_KEY,  // (187)
1813                         MAC_COMMA_KEY,  // (188)
1814                         MAC_MINUS_KEY,  // (189)
1815                         MAC_PERIOD_KEY,  // (190)
1816                         MAC_SLASH_KEY,  // (191)
1817                         MAC_TILDE_KEY,  // (192)
1818                         0xffff,  // (193)
1819                         0xffff,  // (194)
1820                         0xffff,  // (195)
1821                         0xffff,  // (196)
1822                         0xffff,  // (197)
1823                         0xffff,  // (198)
1824                         0xffff,  // (199)
1825                         0xffff,  // (200)
1826                         0xffff,  // (201)
1827                         0xffff,  // (202)
1828                         0xffff,  // (203)
1829                         0xffff,  // (204)
1830                         0xffff,  // (205)
1831                         0xffff,  // (206)
1832                         0xffff,  // (207)
1833                         0xffff,  // (208)
1834                         0xffff,  // (209)
1835                         0xffff,  // (210)
1836                         0xffff,  // (211)
1837                         0xffff,  // (212)
1838                         0xffff,  // (213)
1839                         0xffff,  // (214)
1840                         0xffff,  // (215)
1841                         0xffff,  // (216)
1842                         0xffff,  // (217)
1843                         0xffff,  // (218)
1844                         MAC_LEFTBRACKET_KEY,  // (219)
1845                         MAC_BACKSLASH_KEY,  // (220)
1846                         MAC_RIGHTBRACKET_KEY,  // (221)
1847                         MAC_APOSTROPHE_KEY,  // (222)
1848                         0xffff,  // (223)
1849                         0xffff,  // (224)
1850                         0xffff,  // (225)
1851                         0xffff,  // (226)
1852                         0xffff,  // (227)
1853                         0xffff,  // (228)
1854                         0xffff,  // (229)
1855                         0xffff,  // (230)
1856                         0xffff,  // (231)
1857                         0xffff,  // (232)
1858                         0xffff,  // (233)
1859                         0xffff,  // (234)
1860                         0xffff,  // (235)
1861                         0xffff,  // (236)
1862                         0xffff,  // (237)
1863                         0xffff,  // (238)
1864                         0xffff,  // (239)
1865                         0xffff,  // (240)
1866                         0xffff,  // (241)
1867                         0xffff,  // (242)
1868                         0xffff,  // (243)
1869                         0xffff,  // (244)
1870                         0xffff,  // (245)
1871                         0xffff,  // (246)
1872                         0xffff,  // (247)
1873                         0xffff,  // (248)
1874                         0xffff,  // (249)
1875                         0xffff,  // (250)
1876                         0xffff,  // (251)
1877                         0xffff,  // (252)
1878                         0xffff,  // (253)
1879                         0xffff,  // (254)
1880                         0xffff,  // (255)
1881         };
1882
1883         void ClipMouseToWindow(HWND window)
1884         {
1885                 RECT wRect;
1886
1887                 GetClientRect(window, &wRect);
1888
1889                 ClientToScreen(window, (LPPOINT)&wRect.left);
1890                 ClientToScreen(window, (LPPOINT)&wRect.right);
1891
1892                 ClipCursor(&wRect);
1893
1894                 return;
1895         }
1896
1897         LRESULT FAR PASCAL AppWndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
1898         {
1899                 /* this is where we receive all messages concerning this window
1900                 * we can either process a message or pass it on to the default
1901                 * message handler of windows */
1902
1903                 static PAINTSTRUCT ps;
1904
1905                 switch(msg)
1906                 {
1907                 case WM_ACTIVATE:       // Watch For Window Activate Message
1908                         {
1909                                 // Check Minimization State
1910                                 BOOL iconified = HIWORD(wParam) ? TRUE : FALSE;
1911
1912                                 if (LOWORD(wParam) == WA_INACTIVE)
1913                                 {
1914                                         ClipCursor(NULL);
1915
1916                                         if (fullscreen)
1917                                         {
1918                                                 if( !iconified )
1919                                                 {
1920                                                         // Minimize window
1921                                                         CloseWindow( hWnd );
1922
1923                                                         // The window is now iconified
1924                                                         iconified = GL_TRUE;
1925                                                 }
1926                                         }
1927
1928                                         ShutdownDSp();
1929
1930                                         g_focused=false;                                // Program Is Active
1931                                 }
1932                                 else
1933                                 {
1934                                         SetupDSpFullScreen();
1935
1936                                         if( iconified )
1937                                         {
1938                                                 // Minimize window
1939                                                 OpenIcon( hWnd );
1940
1941                                                 // The window is now iconified
1942                                                 iconified = GL_FALSE;
1943
1944                                                 // Activate window
1945                                                 ShowWindow( hWnd, SW_SHOW );
1946                                                 SetForegroundWindow( hWnd );
1947                                                 SetFocus( hWnd );
1948                                         }
1949
1950                                         ClipMouseToWindow(hWnd);
1951                                         g_focused=true;                 // Program Is No Longer Active
1952                                 }
1953
1954                                 return 0;                                               // Return To The Message Loop
1955                         }
1956
1957                 case WM_KEYDOWN:
1958                 case WM_SYSKEYDOWN:
1959                         {
1960                                 // check for Alt-F4 (exit hotkey)
1961                                 if (wParam == VK_F4)
1962                                 {
1963                                         if (GetKeyState( VK_MENU) & 0x8080)
1964                                         {
1965                                                 gDone = true;
1966                                                 break;
1967                                         }
1968                                 }
1969                                 if (wParam < MAX_WINKEYS)
1970                                 {
1971                                         if (KeyTable[wParam] != 0xffff)
1972                                                 SetKey( KeyTable[wParam]);
1973                                 }
1974                                 return (0);
1975                         }
1976
1977                 case WM_KEYUP:
1978                 case WM_SYSKEYUP:
1979                         {
1980                                 if (wParam < MAX_WINKEYS)
1981                                         if (KeyTable[wParam] != 0xffff)
1982                                                 ClearKey( KeyTable[wParam]);
1983                                 return (0);
1984                         }
1985
1986                 case WM_CHAR:
1987                 case WM_DEADCHAR:
1988                 case WM_SYSCHAR:
1989                 case WM_SYSDEADCHAR:
1990                         return (0);
1991
1992                 case WM_NCLBUTTONDOWN:
1993                 case WM_LBUTTONDOWN:
1994                         {
1995                                 g_button = true;
1996                                 buttons[ 0] = true;
1997                         }
1998                         return (0);
1999
2000                 case WM_NCRBUTTONDOWN:
2001                 case WM_RBUTTONDOWN:
2002                         {
2003                                 buttons[ 1] = true;
2004                         }
2005                         return (0);
2006
2007                 case WM_NCMBUTTONDOWN:
2008                 case WM_MBUTTONDOWN:
2009                         {
2010                                 buttons[ 2] = true;
2011                         }
2012                         return (0);
2013
2014                 case WM_NCLBUTTONUP:
2015                 case WM_LBUTTONUP:
2016                         {
2017                                 g_button = false;
2018                                 buttons[ 0] = false;
2019                         }
2020                         return (0);
2021
2022                 case WM_NCRBUTTONUP:
2023                 case WM_RBUTTONUP:
2024                         {
2025                                 buttons[ 1] = false;
2026                         }
2027                         return (0);
2028
2029                 case WM_NCMBUTTONUP:
2030                 case WM_MBUTTONUP:
2031                         {
2032                                 buttons[ 2] = false;
2033                         }
2034                         return (0);
2035
2036                 case WM_NCLBUTTONDBLCLK:
2037                 case WM_NCRBUTTONDBLCLK:
2038                 case WM_NCMBUTTONDBLCLK:
2039                 case WM_LBUTTONDBLCLK:
2040                         return (0);
2041                 case WM_RBUTTONDBLCLK:
2042                 case WM_MBUTTONDBLCLK:
2043                         return (0);
2044
2045                 case WM_NCMOUSEMOVE:
2046                 case WM_MOUSEMOVE:
2047                         /*                      ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseX = (signed short)(lParam & 0xffff);
2048                         ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseY = (signed short)(lParam >> 16);
2049                         if (g_lastWindow->m_mouseCallbacksEnabled) g_lastWindow->MouseMoveCallback();
2050                         *///                    goto winmessage;
2051                         return (0);
2052
2053                 case WM_SYSCOMMAND:                                             // Intercept System Commands
2054                         {
2055                                 switch (wParam)                                         // Check System Calls
2056                                 {
2057                                 case SC_SCREENSAVE:                             // Screensaver Trying To Start?
2058                                 case SC_MONITORPOWER:                   // Monitor Trying To Enter Powersave?
2059                                         return 0;                                       // Prevent From Happening
2060
2061                                         // User trying to access application menu using ALT?
2062                                 case SC_KEYMENU:
2063                                         return 0;
2064                                 }
2065                         }
2066                         break;
2067
2068                 case WM_MOVE:
2069 //                      {
2070 //                              ReleaseCapture();
2071 //                              ClipMouseToWindow(hWnd);
2072 //                      }
2073                         break;
2074
2075                 case WM_SIZE:
2076                         break;
2077
2078                 case WM_CLOSE:
2079                         {
2080                                 //gDone =  true;
2081                                 //game.tryquit=1;
2082                         }
2083                         //return (0);
2084
2085                 case WM_DESTROY:
2086                         {
2087                                 //ClipCursor(NULL);
2088                                 PostQuitMessage(0);  /* Terminate Application */
2089                         }
2090                         return (0);
2091
2092                 case WM_ERASEBKGND:
2093                         break;
2094
2095                 case WM_PAINT:
2096 //                      BeginPaint( g_windowHandle,&ps);
2097 //                      EndPaint( g_windowHandle,&ps);
2098                         break;
2099
2100                 default:
2101                         break;
2102                 }
2103
2104                 /* We processed the message and there
2105                 * is no processing by Windows necessary */
2106
2107                 /* We didn't process the message so let Windows do it */
2108                 return DefWindowProc(hWnd,msg,wParam,lParam);
2109         }
2110
2111
2112         static BOOL RegisterWindowClasses(HINSTANCE hFirstInstance)
2113         {
2114                 WNDCLASSEX wc;
2115                 memset( &wc, 0, sizeof( wc));
2116
2117                 /* Register the window class. */
2118                 wc.cbSize = sizeof(wc);
2119 #undef style
2120                 wc.style = (CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_OWNDC);  /* Combination of Class Styles */
2121                 wc.lpfnWndProc = AppWndProc;       /* Adress of Window Procedure */
2122                 wc.cbClsExtra = 0;                 /* Extra Bytes allocated for this Class */
2123                 wc.cbWndExtra = 0;                 /* Extra Bytes allocated for each Window */
2124                 wc.hInstance = hFirstInstance;     /* Handle of program instance */
2125                 wc.hIcon = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2126                 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2127                 wc.hbrBackground = NULL;
2128                 wc.lpszMenuName  = NULL;
2129                 wc.lpszClassName = g_wndClassName; /* Name of the Window Class */
2130                 wc.hIconSm = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2131
2132                 if (!RegisterClassEx(&wc)) return FALSE;  /* Register Class failed */
2133
2134                 return TRUE;
2135         }
2136 #endif
2137
2138         int resolutionID(int width, int height)
2139         {
2140                 int whichres;
2141                 whichres=-1;
2142                 if(width==640 && height==480)whichres=0;
2143                 if(width==800 && height==600)whichres=1;
2144                 if(width==1024 && height==768)whichres=2;
2145                 if(width==1280 && height==1024)whichres=3;
2146                 if(width==1600 && height==1200)whichres=4;
2147                 if(width==840 && height==524)whichres=5;
2148                 if(width==1024 && height==640)whichres=6;
2149                 if(width==1344 && height==840)whichres=7;
2150                 if(width==1920 && height==1200)whichres=8;
2151
2152                 return whichres;
2153         }
2154
2155         int closestResolution(int width, int height)
2156         {
2157                 int whichres;
2158                 whichres=-1;
2159                 if(width>=640 && height>=480)whichres=0;
2160                 if(width>=800 && height>=600)whichres=1;
2161                 if(width>=1024 && height>=768)whichres=2;
2162                 if(width>=1280 && height>=1024)whichres=3;
2163                 if(width>=1600 && height>=1200)whichres=4;
2164                 if(width==840 && height==524)whichres=5;
2165                 if(width==1024 && height==640)whichres=6;
2166                 if(width==1344 && height==840)whichres=7;
2167                 if(width>=1920 && height>=1200)whichres=8;
2168
2169                 return whichres;
2170         }
2171
2172         bool selectDetail(int & width, int & height, int & bpp, int & detail)
2173         {
2174                 bool res = true;
2175                 int whichres = closestResolution(width, height);
2176
2177                 while (true)
2178                 {
2179                         if(whichres<=0 || whichres>8){
2180                                 whichres = 0;
2181                                 width=640;
2182                                 height=480;
2183                         }
2184                         if(whichres==1){
2185                                 width=800;
2186                                 height=600;
2187                         }
2188                         if(whichres==2){
2189                                 width=1024;
2190                                 height=768;
2191                         }
2192                         if(whichres==3){
2193                                 width=1280;
2194                                 height=1024;
2195                         }
2196                         if(whichres==4){
2197                                 width=1600;
2198                                 height=1200;
2199                         }
2200                         if(whichres==5){
2201                                 width=840;
2202                                 height=524;
2203                         }
2204                         if(whichres==6){
2205                                 width=1024;
2206                                 height=640;
2207                         }
2208                         if(whichres==7){
2209                                 width=1344;
2210                                 height=840;
2211                         }
2212                         if(whichres==8){
2213                                 width=1920;
2214                                 height=1200;
2215                         }
2216
2217             // currently with SDL, we just use whatever the native bitdepth
2218             //  of the display is and don't care.
2219             #if USE_SDL
2220             break;
2221             #endif
2222
2223                         if ((detail != 0) && (resolutionDepths[whichres][1] != 0))
2224                         {
2225                                 break;
2226                         }
2227                         else if ((detail == 0) && (resolutionDepths[whichres][0] != 0))
2228                         {
2229                                 break;
2230                         }
2231                         else if ((detail != 0) && (resolutionDepths[whichres][0] != 0))
2232                         {
2233                                 res = false;
2234                                 detail = 0;
2235                                 break;
2236                         }
2237                         else
2238
2239             if (0 == whichres)
2240                         {
2241                                 break;
2242                         }
2243
2244                         --whichres;
2245                 }
2246
2247                 bpp = resolutionDepths[whichres][(detail != 0)];
2248
2249                 return res;
2250         }
2251
2252     #ifdef WIN32
2253         int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
2254         {
2255                 int argc = 0;
2256                 LPWSTR * cl = CommandLineToArgvW(GetCommandLineW(), &argc);
2257                 if (argc > 1)
2258                 {
2259                         if (0 == _wcsicmp(cl[1], L"-windowed"))
2260                         {
2261                                 fullscreen = false;
2262                         }
2263                 }
2264
2265                 logger.start(true);
2266
2267                 memset( &g_theKeys, 0, sizeof( KeyMap));
2268
2269                 unsigned int i = 0;
2270                 DEVMODE mode;
2271                 memset(&mode, 0, sizeof(mode));
2272                 mode.dmSize = sizeof(mode);
2273                 while (EnumDisplaySettings(NULL, i++, &mode))
2274                 {
2275                         if (mode.dmBitsPerPel < 16)
2276                         {
2277                                 continue;
2278                         }
2279
2280                         int res = resolutionID(mode.dmPelsWidth, mode.dmPelsHeight);
2281
2282                         if (res > -1 && res < 8)
2283                         {
2284                                 if (DISP_CHANGE_SUCCESSFUL != ChangeDisplaySettings(&mode, CDS_TEST))
2285                                 {
2286                                         continue;
2287                                 }
2288
2289                                 switch(mode.dmBitsPerPel)
2290                                 {
2291                                 case 32:
2292                                 case 24:
2293                                         resolutionDepths[res][1] = mode.dmBitsPerPel;
2294                                         break;
2295                                 case 16:
2296                                         resolutionDepths[res][0] = mode.dmBitsPerPel;
2297                                         break;
2298                                 }
2299                         }
2300                 }
2301
2302                 /* if there is no Instance of our program in memory then register the window class */
2303                 if (hPrevInstance == NULL && !RegisterWindowClasses(hInstance))
2304                         return FALSE;  /* registration failed! */
2305
2306                 g_appInstance=hInstance;
2307
2308                 main(0, NULL);
2309
2310                 UnregisterClass( g_wndClassName, hInstance);
2311
2312                 return TRUE;
2313
2314         }
2315     #endif
2316
2317         extern int channels[100];
2318         extern FSOUND_SAMPLE * samp[100];
2319         extern FSOUND_STREAM * strm[20];
2320
2321         extern "C" void PlaySoundEx(int chan, FSOUND_SAMPLE *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2322         {
2323                 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2324                 if (currSample && currSample == samp[chan])
2325                 {
2326                         if (FSOUND_GetPaused(channels[chan]))
2327                         {
2328                                 FSOUND_StopSound(channels[chan]);
2329                                 channels[chan] = FSOUND_FREE;
2330                         }
2331                         else if (FSOUND_IsPlaying(channels[chan]))
2332                         {
2333                                 int loop_mode = FSOUND_GetLoopMode(channels[chan]);
2334                                 if (loop_mode & FSOUND_LOOP_OFF)
2335                                 {
2336                                         channels[chan] = FSOUND_FREE;
2337                                 }
2338                         }
2339                 }
2340                 else
2341                 {
2342                         channels[chan] = FSOUND_FREE;
2343                 }
2344
2345                 channels[chan] = FSOUND_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
2346                 if (channels[chan] < 0)
2347                 {
2348                         channels[chan] = FSOUND_PlaySoundEx(FSOUND_FREE, sptr, dsp, startpaused);
2349                 }
2350         }
2351
2352         extern "C" void PlayStreamEx(int chan, FSOUND_STREAM *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2353         {
2354                 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2355                 if (currSample && currSample == FSOUND_Stream_GetSample(sptr))
2356                 {
2357                                 FSOUND_StopSound(channels[chan]);
2358                                 FSOUND_Stream_Stop(sptr);
2359                 }
2360                 else
2361                 {
2362                         FSOUND_Stream_Stop(sptr);
2363                         channels[chan] = FSOUND_FREE;
2364                 }
2365
2366                 channels[chan] = FSOUND_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
2367                 if (channels[chan] < 0)
2368                 {
2369                         channels[chan] = FSOUND_Stream_PlayEx(FSOUND_FREE, sptr, dsp, startpaused);
2370                 }
2371         }
2372
2373         bool LoadImage(const char * fname, TGAImageRec & tex)
2374         {
2375                 bool res = true;
2376
2377                 if ( tex.data == NULL )
2378                 {
2379                         return false;
2380                 }
2381
2382         #if USE_DEVIL
2383                 ILstring f = strdup(ConvertFileName(fname));
2384                 if (!f)
2385                 {
2386                         return false;
2387                 }
2388
2389                 ILuint iid=0;
2390                 ilGenImages(1, &iid);
2391                 ilBindImage(iid);
2392                 if (ilLoadImage(f))
2393                 {
2394                         //iluFlipImage();
2395                         tex.sizeX = ilGetInteger(IL_IMAGE_WIDTH);
2396                         tex.sizeY = ilGetInteger(IL_IMAGE_HEIGHT);
2397                         tex.bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
2398                         ILuint Bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL),
2399                                 imageSize = tex.sizeX * tex.sizeY * Bpp;
2400                         ILubyte *Data = ilGetData();
2401                         memcpy(tex.data, Data, imageSize);
2402
2403                         // Truvision Targa files are stored as BGR colors
2404                         // We want RGB so Blue and Red bytes are switched
2405                         if (IL_TGA == ilGetInteger(IL_IMAGE_FORMAT))
2406                         {
2407                                 // Loop Through The Image Data
2408                                 for (GLuint i = 0; i < int(imageSize); i += Bpp)
2409                                 {
2410                                         // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
2411                                         GLbyte temp;                                            // Temporary Variable
2412                                         temp = tex.data[i];                                     // Temporarily Store The Value At Image Data 'i'
2413                                         tex.data[i] = tex.data[i + 2];          // Set The 1st Byte To The Value Of The 3rd Byte
2414                                         tex.data[i + 2] = temp;                         // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
2415                                 }
2416                         }
2417                 }
2418                 else
2419                 {
2420                         res = false;
2421                 }
2422                 ilDeleteImages(1, &iid);
2423 /*
2424                 if (tid)
2425                 {
2426                         GLuint texid = ilutGLLoadImage(f);
2427                         *tid = texid;
2428                 }
2429                 else if (mip)
2430                 {
2431                         ilutGLBuildMipmaps()
2432                 }
2433                 else
2434                 {
2435                         ilutGLTexImage(0);
2436                 }
2437 */
2438                 free(f);
2439         #else
2440         res = load_image(fname, tex);
2441         //if (!res) printf("failed to load %s\n", fname);
2442         #endif
2443
2444                 return res;
2445         }
2446
2447         void ScreenShot(const char * fname)
2448         {
2449         #if USE_DEVIL
2450                 ILstring f = strdup(fname);
2451                 if (!f)
2452                 {
2453                         return;
2454                 }
2455
2456                 ILuint iid;
2457                 ilGenImages(1, &iid);
2458                 ilBindImage(iid);
2459                 if (ilutGLScreen())
2460                 {
2461                         ilSaveImage(f);
2462                 }
2463                 ilDeleteImages(1, &iid);
2464
2465                 free(f);
2466         #else
2467         save_image(fname);
2468         #endif
2469         }
2470
2471
2472 #if !USE_DEVIL
2473 static bool load_image(const char *file_name, TGAImageRec &tex)
2474 {
2475     char *ptr = strrchr(file_name, '.');
2476     if (ptr)
2477     {
2478         if (stricmp(ptr+1, "png") == 0)
2479             return load_png(file_name, tex);
2480         else if (stricmp(ptr+1, "jpg") == 0)
2481             return load_jpg(file_name, tex);
2482     }
2483
2484     STUBBED("Unsupported image type");
2485     return false;
2486 }
2487
2488
2489 struct my_error_mgr {
2490   struct jpeg_error_mgr pub;    /* "public" fields */
2491   jmp_buf setjmp_buffer;        /* for return to caller */
2492 };
2493 typedef struct my_error_mgr * my_error_ptr;
2494
2495
2496 static void my_error_exit(j_common_ptr cinfo)
2497 {
2498         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
2499         longjmp(err->setjmp_buffer, 1);
2500 }
2501
2502 /* stolen from public domain example.c code in libjpg distribution. */
2503 static bool load_jpg(const char *file_name, TGAImageRec &tex)
2504 {
2505     struct jpeg_decompress_struct cinfo;
2506     struct my_error_mgr jerr;
2507     JSAMPROW buffer[1];         /* Output row buffer */
2508     int row_stride;             /* physical row width in output buffer */
2509     FILE *infile = fopen(file_name, "rb");
2510
2511     if (infile == NULL)
2512         return false;
2513
2514     cinfo.err = jpeg_std_error(&jerr.pub);
2515     jerr.pub.error_exit = my_error_exit;
2516     if (setjmp(jerr.setjmp_buffer)) {
2517         jpeg_destroy_decompress(&cinfo);
2518         fclose(infile);
2519         return false;
2520     }
2521
2522     jpeg_create_decompress(&cinfo);
2523     jpeg_stdio_src(&cinfo, infile);
2524     (void) jpeg_read_header(&cinfo, TRUE);
2525
2526     cinfo.out_color_space = JCS_RGB;
2527     cinfo.quantize_colors = 0;
2528     (void) jpeg_calc_output_dimensions(&cinfo);
2529     (void) jpeg_start_decompress(&cinfo);
2530
2531     row_stride = cinfo.output_width * cinfo.output_components;
2532     tex.sizeX = cinfo.output_width;
2533     tex.sizeY = cinfo.output_height;
2534     tex.bpp = 24;
2535
2536     while (cinfo.output_scanline < cinfo.output_height) {
2537         buffer[0] = (JSAMPROW)(char *)tex.data +
2538                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
2539         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
2540     }
2541
2542     (void) jpeg_finish_decompress(&cinfo);
2543     jpeg_destroy_decompress(&cinfo);
2544     fclose(infile);
2545
2546     return true;
2547 }
2548
2549
2550 /* stolen from public domain example.c code in libpng distribution. */
2551 static bool load_png(const char *file_name, TGAImageRec &tex)
2552 {
2553     bool hasalpha = false;
2554     png_structp png_ptr = NULL;
2555     png_infop info_ptr = NULL;
2556     png_uint_32 width, height;
2557     int bit_depth, color_type, interlace_type;
2558     png_byte **rows = NULL;
2559     bool retval = false;
2560     png_byte **row_pointers = NULL;
2561     FILE *fp = fopen(file_name, "rb");
2562
2563     if (fp == NULL)
2564         return(NULL);
2565
2566     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2567     if (png_ptr == NULL)
2568         goto png_done;
2569
2570     info_ptr = png_create_info_struct(png_ptr);
2571     if (info_ptr == NULL)
2572         goto png_done;
2573
2574     if (setjmp(png_jmpbuf(png_ptr)))
2575         goto png_done;
2576
2577     png_init_io(png_ptr, fp);
2578     png_read_png(png_ptr, info_ptr,
2579                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
2580                  png_voidp_NULL);
2581     png_get_IHDR(png_ptr, info_ptr, &width, &height,
2582                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
2583
2584     if (bit_depth != 8)  // transform SHOULD handle this...
2585         goto png_done;
2586
2587     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
2588         goto png_done;
2589
2590     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
2591         goto png_done;
2592
2593     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
2594     row_pointers = png_get_rows(png_ptr, info_ptr);
2595     if (!row_pointers)
2596         goto png_done;
2597
2598     if (!hasalpha)
2599     {
2600         png_byte *dst = tex.data;
2601         for (int i = height-1; i >= 0; i--)
2602         {
2603             png_byte *src = row_pointers[i];
2604             for (int j = 0; j < width; j++)
2605             {
2606                 dst[0] = src[0];
2607                 dst[1] = src[1];
2608                 dst[2] = src[2];
2609                 dst[3] = 0xFF;
2610                 src += 3;
2611                 dst += 4;
2612             }
2613         }
2614     }
2615
2616     else
2617     {
2618         png_byte *dst = tex.data;
2619         int pitch = width * 4;
2620         for (int i = height-1; i >= 0; i--, dst += pitch)
2621             memcpy(dst, row_pointers[i], pitch);
2622     }
2623
2624     tex.sizeX = width;
2625     tex.sizeY = height;
2626     tex.bpp = 32;
2627     retval = true;
2628
2629 png_done:
2630     png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
2631     if (fp)
2632         fclose(fp);
2633     return (retval);
2634 }
2635
2636
2637 static bool save_image(const char *file_name)
2638 {
2639     char *ptr = strrchr(file_name, '.');
2640     if (ptr)
2641     {
2642         if (stricmp(ptr+1, "png") == 0)
2643             return save_png(file_name);
2644     }
2645
2646     STUBBED("Unsupported image type");
2647     return false;
2648 }
2649
2650
2651 static bool save_png(const char *file_name)
2652 {
2653     FILE *fp = NULL;
2654     png_structp png_ptr = NULL;
2655     png_infop info_ptr = NULL;
2656     bool retval = false;
2657
2658     fp = fopen(file_name, "wb");
2659     if (fp == NULL)
2660         return false;
2661
2662     png_bytep *row_pointers = new png_bytep[kContextHeight];
2663     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
2664     if ((!screenshot) || (!row_pointers))
2665         goto save_png_done;
2666
2667     glGetError();
2668     glReadPixels(0, 0, kContextWidth, kContextHeight,
2669                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
2670     if (glGetError() != GL_NO_ERROR)
2671         goto save_png_done;
2672
2673     for (int i = 0; i < kContextHeight; i++)
2674         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
2675
2676     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2677     if (png_ptr == NULL)
2678         goto save_png_done;
2679
2680     info_ptr = png_create_info_struct(png_ptr);
2681     if (info_ptr == NULL)
2682         goto save_png_done;
2683
2684     if (setjmp(png_jmpbuf(png_ptr)))
2685         goto save_png_done;
2686
2687     png_init_io(png_ptr, fp);
2688
2689     if (setjmp(png_jmpbuf(png_ptr)))
2690         goto save_png_done;
2691
2692     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
2693                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
2694                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2695
2696     png_write_info(png_ptr, info_ptr);
2697
2698     if (setjmp(png_jmpbuf(png_ptr)))
2699         goto save_png_done;
2700
2701         png_write_image(png_ptr, row_pointers);
2702
2703         if (setjmp(png_jmpbuf(png_ptr)))
2704         goto save_png_done;
2705
2706     png_write_end(png_ptr, NULL);
2707     retval = true;
2708
2709 save_png_done:
2710     png_destroy_write_struct(&png_ptr, &info_ptr);
2711     delete[] screenshot;
2712     delete[] row_pointers;
2713     if (fp)
2714         fclose(fp);
2715     if (!retval)
2716         unlink(ConvertFileName(file_name));
2717     return retval;
2718 }
2719
2720 #endif
2721