]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
Various SDL input and Game::* cleanups
[lugaru.git] / Source / OpenGL_Windows.cpp
1 /*
2 Copyright (C) 2003, 2010 - Wolfire Games
3
4 This file is part of Lugaru.
5
6 Lugaru is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 */
21
22
23 #ifdef WIN32
24 #define UINT8 WIN32API_UINT8
25 #define UINT16 WIN32API_UINT16
26 #define boolean WIN32API_boolean
27 #include <windows.h>
28 #undef UINT8
29 #undef UINT16
30 #undef boolean
31 #endif
32
33
34
35 #include "Game.h"
36 extern "C" {
37         #include "zlib.h"
38         #include "png.h"
39    #ifdef WIN32
40                 #define INT32 INT32_jpeg
41                 #include "jpeglib.h"
42                 #undef INT32
43         #else
44                 #include "jpeglib.h"
45         #endif
46 }
47
48 static bool load_image(const char * fname, TGAImageRec & tex);
49 static bool load_png(const char * fname, TGAImageRec & tex);
50 static bool load_jpg(const char * fname, TGAImageRec & tex);
51 static bool save_image(const char * fname);
52 static bool save_png(const char * fname);
53
54
55 #include "openal_wrapper.h"
56
57 // ADDED GWC
58 #ifdef _MSC_VER
59 #pragma comment(lib, "opengl32.lib")
60 #pragma comment(lib, "glu32.lib")
61 #pragma comment(lib, "glaux.lib")
62 #endif
63
64 extern float multiplier;
65 extern float sps;
66 extern float realmultiplier;
67 extern int slomo;
68 extern bool cellophane;
69 // MODIFIED GWC
70 //extern int terraindetail;
71 //extern int texdetail;
72 extern float terraindetail;
73 extern float texdetail;
74
75 extern bool osx;
76 extern int numplayers;
77 extern bool freeze;
78 extern Person player[maxplayers];
79 extern bool stillloading;
80 extern int mainmenu;
81 /*extern*/ bool gameFocused;
82
83 extern float slomospeed;
84 extern float slomofreq;
85
86
87
88 #include <math.h>
89 #include <stdio.h>
90 #include <string.h>
91 #include <fstream>
92 #include <iostream>
93 #include "gamegl.h"
94 #include "MacCompatibility.h"
95 #include "Settings.h"
96
97 #ifdef WIN32
98 #include <shellapi.h>
99 #include "win-res/resource.h"
100 #endif
101
102 using namespace std;
103
104
105
106 SDL_Rect **resolutions = NULL;
107 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
108 static SDL_Rect rect_800_600  = { 0, 0, 800,  600 };
109 static SDL_Rect rect_640_480  = { 0, 0, 640,  480 };
110 static SDL_Rect *hardcoded_resolutions[] = {
111     &rect_1024_768,
112     &rect_800_600,
113     &rect_640_480,
114     NULL
115 };
116
117
118
119 unsigned int resolutionDepths[8][2] = {0};
120
121 int closestResolution(int width, int height);
122 int resolutionID(int width, int height);
123
124 void ReportError (char * strError);
125
126 void DrawGL(Game & game);
127
128 void CreateGLWindow (void);
129 Boolean SetUp (Game & game);
130 void DoUpdate (Game & game);
131
132 void DoEvent (void);
133 void CleanUp (void);
134
135
136 // statics/globals (internal only) ------------------------------------------
137 #ifndef WIN32
138 typedef struct tagPOINT { 
139   int x;
140   int y;
141 } POINT, *PPOINT; 
142 #endif
143
144
145
146 #ifdef _MSC_VER
147 #pragma warning(push)
148 #pragma warning(disable: 4273)
149 #endif
150
151 #define GL_FUNC(ret,fn,params,call,rt) \
152     extern "C" { \
153         static ret (GLAPIENTRY *p##fn) params = NULL; \
154         ret GLAPIENTRY fn params { rt p##fn call; } \
155     }
156 #include "glstubs.h"
157 #undef GL_FUNC
158
159 #ifdef _MSC_VER
160 #pragma warning(pop)
161 #endif
162
163 static bool lookup_glsym(const char *funcname, void **func)
164 {
165     *func = SDL_GL_GetProcAddress(funcname);
166     if (*func == NULL)
167     {
168         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
169         return false;
170     }
171     return true;
172 }
173
174 static bool lookup_all_glsyms(void)
175 {
176     bool retval = true;
177     #define GL_FUNC(ret,fn,params,call,rt) \
178         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
179     #include "glstubs.h"
180     #undef GL_FUNC
181     return retval;
182 }
183
184 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
185 {
186     // no-op.
187 }
188
189
190
191 void sdlGetCursorPos(POINT *pt)
192 {
193     SDL_GetMouseState(&(pt->x), &(pt->y));
194 }
195 #define GetCursorPos(x) sdlGetCursorPos(x)
196 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
197 #define ScreenToClient(x, pt)
198 #define ClientToScreen(x, pt)
199 #ifdef MessageBox
200 #undef MessageBox
201 #endif
202 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
203
204
205 Point delta;
206
207 static bool g_button, fullscreen = true;
208
209
210 // Menu defs
211 enum 
212 {
213         kFileQuit = 1
214 };
215
216 enum 
217 {
218         kForegroundSleep = 10,
219         kBackgroundSleep = 10000
220 };
221
222
223 int kContextWidth;
224 int kContextHeight;
225
226 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
227
228 GLuint gFontList;
229 char gcstrMode [256] = "";
230
231 UInt32 gSleepTime = kForegroundSleep;
232 Boolean gDone = false, gfFrontProcess = true;
233
234 Game * pgame = 0;
235
236 #ifndef __MINGW32__
237 static int _argc = 0;
238 static char **_argv = NULL;
239 #endif
240
241 bool cmdline(const char *cmd)
242 {
243     for (int i = 1; i < _argc; i++)
244     {
245         char *arg = _argv[i];
246         while (*arg == '-')
247             arg++;
248         if (strcasecmp(arg, cmd) == 0)
249             return true;
250     }
251
252     return false;
253 }
254
255
256 // --------------------------------------------------------------------------
257
258 void ReportError (char * strError)
259 {
260 #ifdef _MSC_VER  // !!! FIXME.  --ryan.
261         throw std::exception( strError);
262 #endif
263
264         /*      char errMsgCStr [256];
265         Str255 strErr;
266
267         sprintf (errMsgCStr, "%s", strError); 
268
269         // out as debug string
270         CToPStr (strErr, errMsgCStr);
271         DebugStr (strErr);
272         */
273 }
274
275 //-----------------------------------------------------------------------------------------------------------------------
276
277 // OpenGL Drawing
278
279 void DrawGL (Game & game)
280 {
281         if ( stereomode == stereoNone ) {
282                 game.DrawGLScene(stereoCenter);
283         } else {
284                 game.DrawGLScene(stereoLeft);
285                 game.DrawGLScene(stereoRight);
286         }
287 }
288
289 static inline int clamp_sdl_mouse_button(Uint8 button)
290 {
291     if (button == 2)   // right mouse button is button 3 in SDL.
292         button = 3;
293     else if (button == 3)
294         button = 2;
295
296     if ((button >= 1) && (button <= 3))
297         return button - 1;
298     return -1;
299 }
300
301 static void sdlEventProc(const SDL_Event &e, Game &game)
302 {
303     int val;
304     SDLMod mod;
305
306     switch(e.type)
307         {
308         case SDL_MOUSEMOTION:
309             game.deltah += e.motion.xrel;
310             game.deltav += e.motion.yrel;
311             return;
312
313         case SDL_KEYDOWN:
314             if ((e.key.keysym.sym == SDLK_g) &&
315                                 (e.key.keysym.mod & KMOD_CTRL) &&
316                                 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
317                                 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
318                         } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
319                                 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
320             }
321             return;
322
323         case SDL_KEYUP:
324             return;
325     }
326 }
327
328
329 // --------------------------------------------------------------------------
330
331 static Point gMidPoint;
332
333 Boolean SetUp (Game & game)
334 {
335         char string[10];
336
337         LOGFUNC;
338
339         randSeed = UpTime().lo;
340
341         osx = 0;
342         cellophane=0;
343         texdetail=4;
344         terraindetail=2;
345         slomospeed=0.25;
346         slomofreq=8012;
347         numplayers=1;
348         
349         DefaultSettings(game);
350
351     if (!SDL_WasInit(SDL_INIT_VIDEO))
352         if (SDL_Init(SDL_INIT_VIDEO) == -1)
353         {
354             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
355             return false;
356         }
357         if(!LoadSettings(game)) {
358                 fprintf(stderr, "Failed to load config, creating default\n");
359                 SaveSettings(game);
360         }
361         if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
362                 kBitsPerPixel=16;
363         }
364
365         if (SDL_GL_LoadLibrary(NULL) == -1)
366         {
367                 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
368                 SDL_Quit();
369                 return false;
370         }
371
372         SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
373         if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
374                 res = hardcoded_resolutions;
375
376         // reverse list (it was sorted biggest to smallest by SDL)...
377         int count;
378         for (count = 0; res[count]; count++)
379         {
380                 if ((res[count]->w < 640) || (res[count]->h < 480))
381                         break;   // sane lower limit.
382         }
383
384         static SDL_Rect *resolutions_block = NULL;
385         resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
386         resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
387         if ((resolutions_block == NULL) || (resolutions == NULL))
388         {
389                 SDL_Quit();
390                 fprintf(stderr, "Out of memory!\n");
391                 return false;
392         }
393
394         resolutions[count--] = NULL;
395         for (int i = 0; count >= 0; i++, count--)
396         {
397                 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
398                 resolutions[count] = &resolutions_block[count];
399         }
400
401         if (cmdline("showresolutions"))
402         {
403                 printf("Resolutions we think are okay:\n");
404                 for (int i = 0; resolutions[i]; i++)
405                         printf("  %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
406         }
407
408     Uint32 sdlflags = SDL_OPENGL;
409     if (!cmdline("windowed"))
410         sdlflags |= SDL_FULLSCREEN;
411
412     SDL_WM_SetCaption("Lugaru", "Lugaru");
413
414     SDL_ShowCursor(0);
415
416     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
417     SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
418     
419     if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
420     {
421         fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
422         fprintf(stderr, "forcing 640x480...\n");
423         kContextWidth = 640;
424         kContextHeight = 480;
425         if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
426         {
427             fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
428             fprintf(stderr, "forcing 640x480 windowed mode...\n");
429             sdlflags &= ~SDL_FULLSCREEN;
430             if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
431             {
432                 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
433                 return false;
434             }
435         }
436     }
437
438     int dblbuf = 0;
439     if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
440     {
441         fprintf(stderr, "Failed to get double buffered GL context!\n");
442         SDL_Quit();
443         return false;
444     }
445
446     if (!lookup_all_glsyms())
447     {
448         SDL_Quit();
449         return false;
450     }
451
452     if (!cmdline("nomousegrab"))
453         SDL_WM_GrabInput(SDL_GRAB_ON);
454
455
456         glClear( GL_COLOR_BUFFER_BIT );
457         swap_gl_buffers();
458
459         // clear all states
460         glDisable( GL_ALPHA_TEST);
461         glDisable( GL_BLEND);
462         glDisable( GL_DEPTH_TEST);
463         //      glDisable( GL_DITHER);
464         glDisable( GL_FOG);
465         glDisable( GL_LIGHTING);
466         glDisable( GL_LOGIC_OP);
467         glDisable( GL_TEXTURE_1D);
468         glDisable( GL_TEXTURE_2D);
469         glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
470         glPixelTransferi( GL_RED_SCALE, 1);
471         glPixelTransferi( GL_RED_BIAS, 0);
472         glPixelTransferi( GL_GREEN_SCALE, 1);
473         glPixelTransferi( GL_GREEN_BIAS, 0);
474         glPixelTransferi( GL_BLUE_SCALE, 1);
475         glPixelTransferi( GL_BLUE_BIAS, 0);
476         glPixelTransferi( GL_ALPHA_SCALE, 1);
477         glPixelTransferi( GL_ALPHA_BIAS, 0);
478
479         // set initial rendering states
480         glShadeModel( GL_SMOOTH);
481         glClearDepth( 1.0f);
482         glDepthFunc( GL_LEQUAL);
483         glDepthMask( GL_TRUE);
484         //      glDepthRange( FRONT_CLIP, BACK_CLIP);
485         glEnable( GL_DEPTH_TEST);
486         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
487         glCullFace( GL_FRONT);
488         glEnable( GL_CULL_FACE);
489         glEnable( GL_LIGHTING);
490 //      glEnable( GL_LIGHT_MODEL_AMBIENT);
491         glEnable( GL_DITHER);
492         glEnable( GL_COLOR_MATERIAL);
493         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
494         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
495         glAlphaFunc( GL_GREATER, 0.5f);
496
497         GLint width = kContextWidth;
498         GLint height = kContextHeight;
499         gMidPoint.h = width / 2;
500         gMidPoint.v = height / 2;
501         screenwidth=width;
502         screenheight=height;
503
504         game.newdetail=detail;
505         game.newscreenwidth=screenwidth;
506         game.newscreenheight=screenheight;
507
508         if ( CanInitStereo(stereomode) ) {
509                 InitStereo(stereomode);
510         } else {
511                 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
512                 stereomode = stereoNone;
513         }
514
515         game.InitGame();
516
517         return true;
518 }
519
520
521 static void DoMouse(Game & game)
522 {
523
524         if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
525         {
526                 game.deltah *= usermousesensitivity;
527                 game.deltav *= usermousesensitivity;
528                 game.mousecoordh += game.deltah;
529                 game.mousecoordv += game.deltav;
530         if (game.mousecoordh < 0)
531             game.mousecoordh = 0;
532         else if (game.mousecoordh >= kContextWidth)
533             game.mousecoordh = kContextWidth - 1;
534         if (game.mousecoordv < 0)
535             game.mousecoordv = 0;
536         else if (game.mousecoordv >= kContextHeight)
537             game.mousecoordv = kContextHeight - 1;
538         }
539
540 }
541
542 void DoFrameRate (int update)
543 {       
544         static long frames = 0;
545
546         static AbsoluteTime time = {0,0};
547         static AbsoluteTime frametime = {0,0};
548         AbsoluteTime currTime = UpTime ();
549         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
550
551         if (0 > deltaTime)      // if negative microseconds
552                 deltaTime /= -1000000.0;
553         else                            // else milliseconds
554                 deltaTime /= 1000.0;
555
556         multiplier=deltaTime;
557         if(multiplier<.001) multiplier=.001;
558         if(multiplier>10) multiplier=10;
559         if(update) frametime = currTime;        // reset for next time interval
560
561         deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
562
563         if (0 > deltaTime)      // if negative microseconds
564                 deltaTime /= -1000000.0;
565         else                            // else milliseconds
566                 deltaTime /= 1000.0;
567         frames++;
568         if (0.001 <= deltaTime) // has update interval passed
569         {
570                 if(update){
571                         time = currTime;        // reset for next time interval
572                         frames = 0;
573                 }
574         }
575 }
576
577
578 void DoUpdate (Game & game)
579 {
580         static float sps=200;
581         static int count;
582         static float oldmult;
583
584         DoFrameRate(1);
585         if(multiplier>.6)multiplier=.6;
586
587         game.fps=1/multiplier;
588
589         count = multiplier*sps;
590         if(count<2)count=2;
591         //if(count>10)count=10;
592
593         realmultiplier=multiplier;
594         multiplier*=gamespeed;
595         if(difficulty==1)multiplier*=.9;
596         if(difficulty==0)multiplier*=.8;
597
598         if(game.loading==4)multiplier*=.00001;
599         //multiplier*.9;
600         if(slomo&&!mainmenu)multiplier*=slomospeed;
601         //if(freeze)multiplier*=0.00001;
602         oldmult=multiplier;
603         multiplier/=(float)count;
604
605         DoMouse(game);
606
607         game.TickOnce();
608
609         for(int i=0;i<count;i++)
610         {
611                 game.Tick();
612         }
613         multiplier=oldmult;
614
615         game.TickOnceAfter();
616 /* - Debug code to test how many channels were active on average per frame
617         static long frames = 0;
618
619         static AbsoluteTime start = {0,0};
620         AbsoluteTime currTime = UpTime ();
621         static int num_channels = 0;
622         
623         num_channels += OPENAL_GetChannelsPlaying();
624         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
625
626         if (0 > deltaTime)      // if negative microseconds
627                 deltaTime /= -1000000.0;
628         else                            // else milliseconds
629                 deltaTime /= 1000.0;
630
631         ++frames;
632
633         if (deltaTime >= 1)
634         {
635                 start = currTime;
636                 float avg_channels = (float)num_channels / (float)frames;
637
638                 ofstream opstream("log.txt",ios::app); 
639                 opstream << "Average frame count: ";
640                 opstream << frames;
641                 opstream << " frames - ";
642                 opstream << avg_channels;
643                 opstream << " per frame.\n";
644                 opstream.close();
645
646                 frames = 0;
647                 num_channels = 0;
648         }
649 */
650         DrawGL (game);
651 }
652
653 // --------------------------------------------------------------------------
654
655
656 void CleanUp (void)
657 {
658         LOGFUNC;
659
660 //      game.Dispose();
661
662
663
664
665     SDL_Quit();
666     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
667     #include "glstubs.h"
668     #undef GL_FUNC
669     // cheat here...static destructors are calling glDeleteTexture() after
670     //  the context is destroyed and libGL unloaded by SDL_Quit().
671     pglDeleteTextures = glDeleteTextures_doNothing;
672
673 }
674
675 // --------------------------------------------------------------------------
676
677 static bool IsFocused()
678 {
679     return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
680 }
681
682
683 static void launch_web_browser(const char *url)
684 {
685 #ifdef WIN32
686     ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
687
688 #elif (defined(__APPLE__) && defined(__MACH__))
689     const char *fmt = "open '%s'";
690     const size_t len = strlen(fmt) + strlen(url) + 16;
691     char *buf = new char[len];
692     snprintf(buf, len, fmt, url);
693     system(buf);
694     delete[] buf;
695
696 #elif PLATFORM_LINUX
697     const char *fmt = "PATH=$PATH:. xdg-open '%s'";
698     const size_t len = strlen(fmt) + strlen(url) + 16;
699     char *buf = new char[len];
700     snprintf(buf, len, fmt, url);
701     system(buf);
702     delete[] buf;
703 #endif
704 }
705
706
707 #ifndef WIN32
708 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
709 static char *findBinaryInPath(const char *bin, char *envr)
710 {
711     size_t alloc_size = 0;
712     char *exe = NULL;
713     char *start = envr;
714     char *ptr;
715
716     do
717     {
718         size_t size;
719         ptr = strchr(start, ':');  /* find next $PATH separator. */
720         if (ptr)
721             *ptr = '\0';
722
723         size = strlen(start) + strlen(bin) + 2;
724         if (size > alloc_size)
725         {
726             char *x = (char *) realloc(exe, size);
727             if (x == NULL)
728             {
729                 if (exe != NULL)
730                     free(exe);
731                 return(NULL);
732             } /* if */
733
734             alloc_size = size;
735             exe = x;
736         } /* if */
737
738         /* build full binary path... */
739         strcpy(exe, start);
740         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
741             strcat(exe, "/");
742         strcat(exe, bin);
743
744         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
745         {
746             strcpy(exe, start);  /* i'm lazy. piss off. */
747             return(exe);
748         } /* if */
749
750         start = ptr + 1;  /* start points to beginning of next element. */
751     } while (ptr != NULL);
752
753     if (exe != NULL)
754         free(exe);
755
756     return(NULL);  /* doesn't exist in path. */
757 } /* findBinaryInPath */
758
759
760 char *calcBaseDir(const char *argv0)
761 {
762     /* If there isn't a path on argv0, then look through the $PATH for it. */
763     char *retval;
764     char *envr;
765
766     const char *ptr = strrchr((char *)argv0, '/');
767     if (strchr(argv0, '/'))
768     {
769         retval = strdup(argv0);
770         if (retval)
771             *((char *) strrchr(retval, '/')) = '\0';
772         return(retval);
773     }
774
775     envr = getenv("PATH");
776     if (!envr) return NULL;
777     envr = strdup(envr);
778     if (!envr) return NULL;
779     retval = findBinaryInPath(argv0, envr);
780     free(envr);
781     return(retval);
782 }
783
784 static inline void chdirToAppPath(const char *argv0)
785 {
786     char *dir = calcBaseDir(argv0);
787     if (dir)
788     {
789         #if (defined(__APPLE__) && defined(__MACH__))
790         // Chop off /Contents/MacOS if it's at the end of the string, so we
791         //  land in the base of the app bundle.
792         const size_t len = strlen(dir);
793         const char *bundledirs = "/Contents/MacOS";
794         const size_t bundledirslen = strlen(bundledirs);
795         if (len > bundledirslen)
796         {
797             char *ptr = (dir + len) - bundledirslen;
798             if (strcasecmp(ptr, bundledirs) == 0)
799                 *ptr = '\0';
800         }
801         #endif
802         chdir(dir);
803         free(dir);
804     }
805 }
806 #endif
807
808
809 int main(int argc, char **argv)
810 {
811 #ifndef __MINGW32__
812     _argc = argc;
813     _argv = argv;
814 #endif
815
816     // !!! FIXME: we could use a Win32 API for this.  --ryan.
817 #ifndef WIN32
818     chdirToAppPath(argv[0]);
819 #endif
820
821         LOGFUNC;
822
823         //memset( &g_theKeys, 0, sizeof( KeyMap));
824
825     //initSDLKeyTable();
826
827         try
828         {
829                 bool regnow = false;
830                 {
831                         Game game;
832                         pgame = &game;
833
834                         //ofstream os("error.txt");
835                         //os.close();
836                         //ofstream os("log.txt");
837                         //os.close();
838
839                         if (!SetUp (game))
840                 return 42;
841
842                         while (!gDone&&!game.quit&&(!game.tryquit))
843                         {
844                                 if (IsFocused())
845                                 {
846                                         gameFocused = true;
847
848                                         // check windows messages
849                         
850                                         game.deltah = 0;
851                                         game.deltav = 0;
852                                         SDL_Event e;
853                                         if(!game.isWaiting()) {
854                                                 // message pump
855                                                 while( SDL_PollEvent( &e ) )
856                                                 {
857                                                         if( e.type == SDL_QUIT )
858                                                         {
859                                                                 gDone=true;
860                                                                 break;
861                                                         }
862                                                         sdlEventProc(e, game);
863                                                 }
864                                         }
865
866                                         // game
867                                         DoUpdate(game);
868                                 }
869                                 else
870                                 {
871                                         if (gameFocused)
872                                         {
873                                                 // allow game chance to pause
874                                                 gameFocused = false;
875                                                 DoUpdate(game);
876                                         }
877
878                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
879                                         SDL_ActiveEvent evt;
880                                         SDL_WaitEvent((SDL_Event*)&evt);
881                                         if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
882                                                 gameFocused = true;
883                                         else if (evt.type == SDL_QUIT)
884                                                 gDone = true;
885                                 }
886                         }
887
888                         regnow = game.registernow;
889                 }
890                 pgame = 0;
891
892                 CleanUp ();
893
894                 return 0;
895         }
896         catch (const std::exception& error)
897         {
898                 CleanUp();
899
900                 std::string e = "Caught exception: ";
901                 e += error.what();
902
903                 LOG(e);
904
905                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
906         }
907
908         CleanUp();
909
910         return -1;
911 }
912
913
914
915         // --------------------------------------------------------------------------
916
917         extern int channels[100];
918         extern OPENAL_SAMPLE * samp[100];
919         extern OPENAL_STREAM * strm[20];
920
921         extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
922         {
923                 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
924                 if (currSample && currSample == samp[chan])
925                 {
926                         if (OPENAL_GetPaused(channels[chan]))
927                         {
928                                 OPENAL_StopSound(channels[chan]);
929                                 channels[chan] = OPENAL_FREE;
930                         }
931                         else if (OPENAL_IsPlaying(channels[chan]))
932                         {
933                                 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
934                                 if (loop_mode & OPENAL_LOOP_OFF)
935                                 {
936                                         channels[chan] = OPENAL_FREE;
937                                 }
938                         }
939                 }
940                 else
941                 {
942                         channels[chan] = OPENAL_FREE;
943                 }
944
945                 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
946                 if (channels[chan] < 0)
947                 {
948                         channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
949                 }
950         }
951
952         extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
953         {
954                 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
955                 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
956                 {
957                                 OPENAL_StopSound(channels[chan]);
958                                 OPENAL_Stream_Stop(sptr);
959                 }
960                 else
961                 {
962                         OPENAL_Stream_Stop(sptr);
963                         channels[chan] = OPENAL_FREE;
964                 }
965
966                 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
967                 if (channels[chan] < 0)
968                 {
969                         channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
970                 }
971         }
972
973
974         bool LoadImage(const char * fname, TGAImageRec & tex)
975         {
976                 if ( tex.data == NULL )
977                         return false;
978                 else
979                         return load_image(fname, tex);
980         }
981
982         void ScreenShot(const char * fname)
983         {
984         save_image(fname);
985         }
986
987
988
989 static bool load_image(const char *file_name, TGAImageRec &tex)
990 {
991     const char *ptr = strrchr((char *)file_name, '.');
992     if (ptr)
993     {
994         if (strcasecmp(ptr+1, "png") == 0)
995             return load_png(file_name, tex);
996         else if (strcasecmp(ptr+1, "jpg") == 0)
997             return load_jpg(file_name, tex);
998     }
999
1000     STUBBED("Unsupported image type");
1001     return false;
1002 }
1003
1004
1005 struct my_error_mgr {
1006   struct jpeg_error_mgr pub;    /* "public" fields */
1007   jmp_buf setjmp_buffer;        /* for return to caller */
1008 };
1009 typedef struct my_error_mgr * my_error_ptr;
1010
1011
1012 static void my_error_exit(j_common_ptr cinfo)
1013 {
1014         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1015         longjmp(err->setjmp_buffer, 1);
1016 }
1017
1018 /* stolen from public domain example.c code in libjpg distribution. */
1019 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1020 {
1021     struct jpeg_decompress_struct cinfo;
1022     struct my_error_mgr jerr;
1023     JSAMPROW buffer[1];         /* Output row buffer */
1024     int row_stride;             /* physical row width in output buffer */
1025     FILE *infile = fopen(file_name, "rb");
1026
1027     if (infile == NULL)
1028         return false;
1029
1030     cinfo.err = jpeg_std_error(&jerr.pub);
1031     jerr.pub.error_exit = my_error_exit;
1032     if (setjmp(jerr.setjmp_buffer)) {
1033         jpeg_destroy_decompress(&cinfo);
1034         fclose(infile);
1035         return false;
1036     }
1037
1038     jpeg_create_decompress(&cinfo);
1039     jpeg_stdio_src(&cinfo, infile);
1040     (void) jpeg_read_header(&cinfo, TRUE);
1041
1042     cinfo.out_color_space = JCS_RGB;
1043     cinfo.quantize_colors = 0;
1044     (void) jpeg_calc_output_dimensions(&cinfo);
1045     (void) jpeg_start_decompress(&cinfo);
1046
1047     row_stride = cinfo.output_width * cinfo.output_components;
1048     tex.sizeX = cinfo.output_width;
1049     tex.sizeY = cinfo.output_height;
1050     tex.bpp = 24;
1051
1052     while (cinfo.output_scanline < cinfo.output_height) {
1053         buffer[0] = (JSAMPROW)(char *)tex.data +
1054                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1055         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1056     }
1057
1058     (void) jpeg_finish_decompress(&cinfo);
1059     jpeg_destroy_decompress(&cinfo);
1060     fclose(infile);
1061
1062     return true;
1063 }
1064
1065
1066 /* stolen from public domain example.c code in libpng distribution. */
1067 static bool load_png(const char *file_name, TGAImageRec &tex)
1068 {
1069     bool hasalpha = false;
1070     png_structp png_ptr = NULL;
1071     png_infop info_ptr = NULL;
1072     png_uint_32 width, height;
1073     int bit_depth, color_type, interlace_type;
1074     png_byte **rows = NULL;
1075     bool retval = false;
1076     png_byte **row_pointers = NULL;
1077     FILE *fp = fopen(file_name, "rb");
1078
1079     if (fp == NULL)
1080         return(NULL);
1081
1082     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1083     if (png_ptr == NULL)
1084         goto png_done;
1085
1086     info_ptr = png_create_info_struct(png_ptr);
1087     if (info_ptr == NULL)
1088         goto png_done;
1089
1090     if (setjmp(png_jmpbuf(png_ptr)))
1091         goto png_done;
1092
1093     png_init_io(png_ptr, fp);
1094     png_read_png(png_ptr, info_ptr,
1095                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1096                  NULL);
1097     png_get_IHDR(png_ptr, info_ptr, &width, &height,
1098                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
1099
1100     if (bit_depth != 8)  // transform SHOULD handle this...
1101         goto png_done;
1102
1103     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
1104         goto png_done;
1105
1106     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
1107         goto png_done;
1108
1109     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1110     row_pointers = png_get_rows(png_ptr, info_ptr);
1111     if (!row_pointers)
1112         goto png_done;
1113
1114     if (!hasalpha)
1115     {
1116         png_byte *dst = tex.data;
1117         for (int i = height-1; i >= 0; i--)
1118         {
1119             png_byte *src = row_pointers[i];
1120             for (int j = 0; j < width; j++)
1121             {
1122                 dst[0] = src[0];
1123                 dst[1] = src[1];
1124                 dst[2] = src[2];
1125                 dst[3] = 0xFF;
1126                 src += 3;
1127                 dst += 4;
1128             }
1129         }
1130     }
1131
1132     else
1133     {
1134         png_byte *dst = tex.data;
1135         int pitch = width * 4;
1136         for (int i = height-1; i >= 0; i--, dst += pitch)
1137             memcpy(dst, row_pointers[i], pitch);
1138     }
1139
1140     tex.sizeX = width;
1141     tex.sizeY = height;
1142     tex.bpp = 32;
1143     retval = true;
1144
1145 png_done:
1146     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1147     if (fp)
1148         fclose(fp);
1149     return (retval);
1150 }
1151
1152
1153 static bool save_image(const char *file_name)
1154 {
1155     const char *ptr = strrchr((char *)file_name, '.');
1156     if (ptr)
1157     {
1158         if (strcasecmp(ptr+1, "png") == 0)
1159             return save_png(file_name);
1160     }
1161
1162     STUBBED("Unsupported image type");
1163     return false;
1164 }
1165
1166
1167 static bool save_png(const char *file_name)
1168 {
1169     FILE *fp = NULL;
1170     png_structp png_ptr = NULL;
1171     png_infop info_ptr = NULL;
1172     bool retval = false;
1173
1174     fp = fopen(file_name, "wb");
1175     if (fp == NULL)
1176         return false;
1177
1178     png_bytep *row_pointers = new png_bytep[kContextHeight];
1179     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1180     if ((!screenshot) || (!row_pointers))
1181         goto save_png_done;
1182
1183     glGetError();
1184     glReadPixels(0, 0, kContextWidth, kContextHeight,
1185                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1186     if (glGetError() != GL_NO_ERROR)
1187         goto save_png_done;
1188
1189     for (int i = 0; i < kContextHeight; i++)
1190         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1191
1192     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1193     if (png_ptr == NULL)
1194         goto save_png_done;
1195
1196     info_ptr = png_create_info_struct(png_ptr);
1197     if (info_ptr == NULL)
1198         goto save_png_done;
1199
1200     if (setjmp(png_jmpbuf(png_ptr)))
1201         goto save_png_done;
1202
1203     png_init_io(png_ptr, fp);
1204
1205     if (setjmp(png_jmpbuf(png_ptr)))
1206         goto save_png_done;
1207
1208     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1209                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1210                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1211
1212     png_write_info(png_ptr, info_ptr);
1213
1214     if (setjmp(png_jmpbuf(png_ptr)))
1215         goto save_png_done;
1216
1217         png_write_image(png_ptr, row_pointers);
1218
1219         if (setjmp(png_jmpbuf(png_ptr)))
1220         goto save_png_done;
1221
1222     png_write_end(png_ptr, NULL);
1223     retval = true;
1224
1225 save_png_done:
1226     png_destroy_write_struct(&png_ptr, &info_ptr);
1227     delete[] screenshot;
1228     delete[] row_pointers;
1229     if (fp)
1230         fclose(fp);
1231     if (!retval)
1232         unlink(ConvertFileName(file_name));
1233     return retval;
1234 }
1235
1236
1237