]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
b25b0cba26dbf01ef8f5fc8d1c546105ee4bbe61
[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 bool save_image(const char * fname);
52 static bool save_png(const char * fname);
53
54
55 #include "openal_wrapper.h"
56
57 extern float multiplier;
58 extern float sps;
59 extern float realmultiplier;
60 extern int slomo;
61 extern bool cellophane;
62 extern float texdetail;
63
64 extern bool osx;
65 extern bool freeze;
66 extern bool stillloading;
67 extern int mainmenu;
68 /*extern*/ bool gameFocused;
69
70 extern float slomospeed;
71 extern float slomofreq;
72
73
74
75 #include <math.h>
76 #include <stdio.h>
77 #include <string.h>
78 #include <fstream>
79 #include <iostream>
80 #include "gamegl.h"
81 #include "MacCompatibility.h"
82 #include "Settings.h"
83
84 #ifdef WIN32
85 #include <shellapi.h>
86 #include "win-res/resource.h"
87 #endif
88
89 using namespace std;
90
91 SDL_Rect **resolutions = NULL;
92 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
93 static SDL_Rect rect_800_600  = { 0, 0, 800,  600 };
94 static SDL_Rect rect_640_480  = { 0, 0, 640,  480 };
95 static SDL_Rect *hardcoded_resolutions[] = {
96     &rect_1024_768,
97     &rect_800_600,
98     &rect_640_480,
99     NULL
100 };
101
102 void DrawGL(Game & game);
103
104 Boolean SetUp (Game & game);
105 void DoUpdate (Game & game);
106
107 void CleanUp (void);
108
109 // statics/globals (internal only) ------------------------------------------
110
111 #ifdef _MSC_VER
112 #pragma warning(push)
113 #pragma warning(disable: 4273)
114 #endif
115
116 #define GL_FUNC(ret,fn,params,call,rt) \
117     extern "C" { \
118         static ret (GLAPIENTRY *p##fn) params = NULL; \
119         ret GLAPIENTRY fn params { rt p##fn call; } \
120     }
121 #include "glstubs.h"
122 #undef GL_FUNC
123
124 #ifdef _MSC_VER
125 #pragma warning(pop)
126 #endif
127
128 static bool lookup_glsym(const char *funcname, void **func)
129 {
130     *func = SDL_GL_GetProcAddress(funcname);
131     if (*func == NULL)
132     {
133         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
134         return false;
135     }
136     return true;
137 }
138
139 static bool lookup_all_glsyms(void)
140 {
141     bool retval = true;
142     #define GL_FUNC(ret,fn,params,call,rt) \
143         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
144     #include "glstubs.h"
145     #undef GL_FUNC
146     return retval;
147 }
148
149 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
150 {
151     // no-op.
152 }
153
154 #ifdef MessageBox
155 #undef MessageBox
156 #endif
157 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
158
159 // Menu defs
160
161 int kContextWidth;
162 int kContextHeight;
163
164 Boolean gDone = false;
165
166 Game * pgame = 0;
167
168 #ifndef __MINGW32__
169 static int _argc = 0;
170 static char **_argv = NULL;
171 #endif
172
173 bool cmdline(const char *cmd)
174 {
175     for (int i = 1; i < _argc; i++)
176     {
177         char *arg = _argv[i];
178         while (*arg == '-')
179             arg++;
180         if (strcasecmp(arg, cmd) == 0)
181             return true;
182     }
183
184     return false;
185 }
186
187 //-----------------------------------------------------------------------------------------------------------------------
188
189 // OpenGL Drawing
190
191 void initGL(){
192         glClear( GL_COLOR_BUFFER_BIT );
193         swap_gl_buffers();
194
195         // clear all states
196         glDisable( GL_ALPHA_TEST);
197         glDisable( GL_BLEND);
198         glDisable( GL_DEPTH_TEST);
199         //      glDisable( GL_DITHER);
200         glDisable( GL_FOG);
201         glDisable( GL_LIGHTING);
202         glDisable( GL_LOGIC_OP);
203         glDisable( GL_TEXTURE_1D);
204         glDisable( GL_TEXTURE_2D);
205         glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
206         glPixelTransferi( GL_RED_SCALE, 1);
207         glPixelTransferi( GL_RED_BIAS, 0);
208         glPixelTransferi( GL_GREEN_SCALE, 1);
209         glPixelTransferi( GL_GREEN_BIAS, 0);
210         glPixelTransferi( GL_BLUE_SCALE, 1);
211         glPixelTransferi( GL_BLUE_BIAS, 0);
212         glPixelTransferi( GL_ALPHA_SCALE, 1);
213         glPixelTransferi( GL_ALPHA_BIAS, 0);
214
215         // set initial rendering states
216         glShadeModel( GL_SMOOTH);
217         glClearDepth( 1.0f);
218         glDepthFunc( GL_LEQUAL);
219         glDepthMask( GL_TRUE);
220         //      glDepthRange( FRONT_CLIP, BACK_CLIP);
221         glEnable( GL_DEPTH_TEST);
222         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
223         glCullFace( GL_FRONT);
224         glEnable( GL_CULL_FACE);
225         glEnable( GL_LIGHTING);
226 //      glEnable( GL_LIGHT_MODEL_AMBIENT);
227         glEnable( GL_DITHER);
228         glEnable( GL_COLOR_MATERIAL);
229         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
230         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
231         glAlphaFunc( GL_GREATER, 0.5f);
232
233         if ( CanInitStereo(stereomode) ) {
234                 InitStereo(stereomode);
235         } else {
236                 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
237                 stereomode = stereoNone;
238         }
239 }
240
241 static void toggleFullscreen(){
242     SDL_Surface* screen=SDL_GetVideoSurface();
243     Uint32 flags=screen->flags;
244     screen=SDL_SetVideoMode(0,0,0,flags^SDL_FULLSCREEN);
245     if(!screen)
246         screen=SDL_SetVideoMode(0,0,0,flags);
247     if(!screen)
248         exit(1);
249     //reload opengl state
250     initGL();
251     for(std::vector<TextureInfo>::iterator it=Game::textures.begin(); it!=Game::textures.end(); it++) {
252         it->load();
253     }
254     pgame->text.BuildFont();
255     pgame->LoadScreenTexture();
256 }
257
258 static void sdlEventProc(const SDL_Event &e, Game &game){
259     switch(e.type){
260         case SDL_MOUSEMOTION:
261             game.deltah += e.motion.xrel;
262             game.deltav += e.motion.yrel;
263             break;
264         case SDL_KEYDOWN:
265             if ((e.key.keysym.sym == SDLK_g) &&
266                                 (e.key.keysym.mod & KMOD_CTRL) &&
267                                 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
268                                 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
269                         } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
270                 toggleFullscreen();
271             }
272             break;
273         case SDL_ACTIVEEVENT:
274             if(e.active.state&SDL_APPINPUTFOCUS){
275                 if(e.active.gain){
276                     SDL_WM_GrabInput(SDL_GRAB_ON);
277                     gameFocused=true;
278                 }else{
279                     SDL_WM_GrabInput(SDL_GRAB_OFF);
280                     gameFocused=false;
281                 }
282             }
283             break;
284     }
285 }
286
287
288 // --------------------------------------------------------------------------
289
290 static Point gMidPoint;
291
292 Boolean SetUp (Game & game)
293 {
294         char string[10];
295
296         LOGFUNC;
297
298         osx = 0;
299         cellophane=0;
300         texdetail=4;
301         slomospeed=0.25;
302         slomofreq=8012;
303         numplayers=1;
304         
305         DefaultSettings(game);
306
307     if (!SDL_WasInit(SDL_INIT_VIDEO))
308         if (SDL_Init(SDL_INIT_VIDEO) == -1)
309         {
310             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
311             return false;
312         }
313         if(!LoadSettings(game)) {
314                 fprintf(stderr, "Failed to load config, creating default\n");
315                 SaveSettings(game);
316         }
317         if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
318                 kBitsPerPixel=16;
319         }
320
321         if (SDL_GL_LoadLibrary(NULL) == -1)
322         {
323                 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
324                 SDL_Quit();
325                 return false;
326         }
327
328         SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
329         if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
330                 res = hardcoded_resolutions;
331
332         // reverse list (it was sorted biggest to smallest by SDL)...
333         int count;
334         for (count = 0; res[count]; count++)
335         {
336                 if ((res[count]->w < 640) || (res[count]->h < 480))
337                         break;   // sane lower limit.
338         }
339
340         static SDL_Rect *resolutions_block = NULL;
341         resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
342         resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
343         if ((resolutions_block == NULL) || (resolutions == NULL))
344         {
345                 SDL_Quit();
346                 fprintf(stderr, "Out of memory!\n");
347                 return false;
348         }
349
350         resolutions[count--] = NULL;
351         for (int i = 0; count >= 0; i++, count--)
352         {
353                 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
354                 resolutions[count] = &resolutions_block[count];
355         }
356
357         if (cmdline("showresolutions"))
358         {
359                 printf("Resolutions we think are okay:\n");
360                 for (int i = 0; resolutions[i]; i++)
361                         printf("  %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
362         }
363
364     Uint32 sdlflags = SDL_OPENGL;
365     
366     if (!cmdline("windowed"))
367         sdlflags |= SDL_FULLSCREEN;
368
369     SDL_WM_SetCaption("Lugaru", "Lugaru");
370
371     SDL_ShowCursor(0);
372
373     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
374     SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
375 #if SDL_VERSION_ATLEAST(1, 2, 10)
376     SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, vblsync);
377 #endif
378     
379     if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
380     {
381         fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
382         fprintf(stderr, "forcing 640x480...\n");
383         kContextWidth = 640;
384         kContextHeight = 480;
385         if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
386         {
387             fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
388             fprintf(stderr, "forcing 640x480 windowed mode...\n");
389             sdlflags &= ~SDL_FULLSCREEN;
390             if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
391             {
392                 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
393                 return false;
394             }
395         }
396     }
397
398     int dblbuf = 0;
399     if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
400     {
401         fprintf(stderr, "Failed to get double buffered GL context!\n");
402         SDL_Quit();
403         return false;
404     }
405
406     if (!lookup_all_glsyms())
407     {
408         SDL_Quit();
409         return false;
410     }
411
412     if (!cmdline("nomousegrab"))
413         SDL_WM_GrabInput(SDL_GRAB_ON);
414
415
416     initGL();
417
418         GLint width = kContextWidth;
419         GLint height = kContextHeight;
420         gMidPoint.h = width / 2;
421         gMidPoint.v = height / 2;
422         screenwidth=width;
423         screenheight=height;
424
425         game.newdetail=detail;
426         game.newscreenwidth=screenwidth;
427         game.newscreenheight=screenheight;
428
429         game.InitGame();
430
431         return true;
432 }
433
434
435 static void DoMouse(Game & game)
436 {
437
438         if(mainmenu|| ( (abs(game.deltah)<10*realmultiplier*1000) && (abs(game.deltav)<10*realmultiplier*1000) ))
439         {
440                 game.deltah *= usermousesensitivity;
441                 game.deltav *= usermousesensitivity;
442                 game.mousecoordh += game.deltah;
443                 game.mousecoordv += game.deltav;
444         if (game.mousecoordh < 0)
445             game.mousecoordh = 0;
446         else if (game.mousecoordh >= kContextWidth)
447             game.mousecoordh = kContextWidth - 1;
448         if (game.mousecoordv < 0)
449             game.mousecoordv = 0;
450         else if (game.mousecoordv >= kContextHeight)
451             game.mousecoordv = kContextHeight - 1;
452         }
453
454 }
455
456 void DoFrameRate (int update)
457 {       
458         static long frames = 0;
459
460         static AbsoluteTime time = {0,0};
461         static AbsoluteTime frametime = {0,0};
462         AbsoluteTime currTime = UpTime ();
463         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
464
465         if (0 > deltaTime)      // if negative microseconds
466                 deltaTime /= -1000000.0;
467         else                            // else milliseconds
468                 deltaTime /= 1000.0;
469
470         multiplier=deltaTime;
471         if(multiplier<.001) multiplier=.001;
472         if(multiplier>10) multiplier=10;
473         if(update) frametime = currTime;        // reset for next time interval
474
475         deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
476
477         if (0 > deltaTime)      // if negative microseconds
478                 deltaTime /= -1000000.0;
479         else                            // else milliseconds
480                 deltaTime /= 1000.0;
481         frames++;
482         if (0.001 <= deltaTime) // has update interval passed
483         {
484                 if(update){
485                         time = currTime;        // reset for next time interval
486                         frames = 0;
487                 }
488         }
489 }
490
491
492 void DoUpdate (Game & game)
493 {
494         static float sps=200;
495         static int count;
496         static float oldmult;
497
498         DoFrameRate(1);
499         if(multiplier>.6)multiplier=.6;
500
501         game.fps=1/multiplier;
502
503         count = multiplier*sps;
504         if(count<2)count=2;
505
506         realmultiplier=multiplier;
507         multiplier*=gamespeed;
508         if(difficulty==1)multiplier*=.9;
509         if(difficulty==0)multiplier*=.8;
510
511         if(game.loading==4)multiplier*=.00001;
512         if(slomo&&!mainmenu)multiplier*=slomospeed;
513         oldmult=multiplier;
514         multiplier/=(float)count;
515
516         DoMouse(game);
517
518         game.TickOnce();
519
520         for(int i=0;i<count;i++)
521         {
522                 game.Tick();
523         }
524         multiplier=oldmult;
525
526         game.TickOnceAfter();
527 /* - Debug code to test how many channels were active on average per frame
528         static long frames = 0;
529
530         static AbsoluteTime start = {0,0};
531         AbsoluteTime currTime = UpTime ();
532         static int num_channels = 0;
533         
534         num_channels += OPENAL_GetChannelsPlaying();
535         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
536
537         if (0 > deltaTime)      // if negative microseconds
538                 deltaTime /= -1000000.0;
539         else                            // else milliseconds
540                 deltaTime /= 1000.0;
541
542         ++frames;
543
544         if (deltaTime >= 1)
545         {
546                 start = currTime;
547                 float avg_channels = (float)num_channels / (float)frames;
548
549                 ofstream opstream("log.txt",ios::app); 
550                 opstream << "Average frame count: ";
551                 opstream << frames;
552                 opstream << " frames - ";
553                 opstream << avg_channels;
554                 opstream << " per frame.\n";
555                 opstream.close();
556
557                 frames = 0;
558                 num_channels = 0;
559         }
560 */
561         game.DrawGL();
562 }
563
564 // --------------------------------------------------------------------------
565
566
567 void CleanUp (void)
568 {
569         LOGFUNC;
570
571     SDL_Quit();
572     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
573     #include "glstubs.h"
574     #undef GL_FUNC
575     // cheat here...static destructors are calling glDeleteTexture() after
576     //  the context is destroyed and libGL unloaded by SDL_Quit().
577     pglDeleteTextures = glDeleteTextures_doNothing;
578
579 }
580
581 // --------------------------------------------------------------------------
582
583 static bool IsFocused()
584 {
585     return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
586 }
587
588
589
590 #ifndef WIN32
591 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
592 static char *findBinaryInPath(const char *bin, char *envr)
593 {
594     size_t alloc_size = 0;
595     char *exe = NULL;
596     char *start = envr;
597     char *ptr;
598
599     do
600     {
601         size_t size;
602         ptr = strchr(start, ':');  /* find next $PATH separator. */
603         if (ptr)
604             *ptr = '\0';
605
606         size = strlen(start) + strlen(bin) + 2;
607         if (size > alloc_size)
608         {
609             char *x = (char *) realloc(exe, size);
610             if (x == NULL)
611             {
612                 if (exe != NULL)
613                     free(exe);
614                 return(NULL);
615             } /* if */
616
617             alloc_size = size;
618             exe = x;
619         } /* if */
620
621         /* build full binary path... */
622         strcpy(exe, start);
623         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
624             strcat(exe, "/");
625         strcat(exe, bin);
626
627         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
628         {
629             strcpy(exe, start);  /* i'm lazy. piss off. */
630             return(exe);
631         } /* if */
632
633         start = ptr + 1;  /* start points to beginning of next element. */
634     } while (ptr != NULL);
635
636     if (exe != NULL)
637         free(exe);
638
639     return(NULL);  /* doesn't exist in path. */
640 } /* findBinaryInPath */
641
642
643 char *calcBaseDir(const char *argv0)
644 {
645     /* If there isn't a path on argv0, then look through the $PATH for it. */
646     char *retval;
647     char *envr;
648
649     const char *ptr = strrchr((char *)argv0, '/');
650     if (strchr(argv0, '/'))
651     {
652         retval = strdup(argv0);
653         if (retval)
654             *((char *) strrchr(retval, '/')) = '\0';
655         return(retval);
656     }
657
658     envr = getenv("PATH");
659     if (!envr) return NULL;
660     envr = strdup(envr);
661     if (!envr) return NULL;
662     retval = findBinaryInPath(argv0, envr);
663     free(envr);
664     return(retval);
665 }
666
667 static inline void chdirToAppPath(const char *argv0)
668 {
669     char *dir = calcBaseDir(argv0);
670     if (dir)
671     {
672         #if (defined(__APPLE__) && defined(__MACH__))
673         // Chop off /Contents/MacOS if it's at the end of the string, so we
674         //  land in the base of the app bundle.
675         const size_t len = strlen(dir);
676         const char *bundledirs = "/Contents/MacOS";
677         const size_t bundledirslen = strlen(bundledirs);
678         if (len > bundledirslen)
679         {
680             char *ptr = (dir + len) - bundledirslen;
681             if (strcasecmp(ptr, bundledirs) == 0)
682                 *ptr = '\0';
683         }
684         #endif
685         chdir(dir);
686         free(dir);
687     }
688 }
689 #endif
690
691
692 int main(int argc, char **argv)
693 {
694 #ifndef __MINGW32__
695     _argc = argc;
696     _argv = argv;
697 #endif
698
699     // !!! FIXME: we could use a Win32 API for this.  --ryan.
700 #ifndef WIN32
701     chdirToAppPath(argv[0]);
702 #endif
703
704         LOGFUNC;
705
706         try
707         {
708                 {
709                         Game game;
710                         pgame = &game;
711
712                         //ofstream os("error.txt");
713                         //os.close();
714                         //ofstream os("log.txt");
715                         //os.close();
716
717                         if (!SetUp (game))
718                 return 42;
719
720                         while (!gDone&&!game.quit&&(!game.tryquit))
721                         {
722                                 //if (IsFocused()) {
723                                         //gameFocused = true;
724
725                                         // check windows messages
726                         
727                                         game.deltah = 0;
728                                         game.deltav = 0;
729                                         SDL_Event e;
730                                         if(!game.isWaiting()) {
731                                                 // message pump
732                                                 while( SDL_PollEvent( &e ) ){
733                             switch(e.type){
734                             case SDL_QUIT:
735                                 gDone=true;
736                                 break;
737                             default:
738                                 sdlEventProc(e, game);
739                                 break;
740                                                         }
741                                                 }
742                                         }
743
744                                         // game
745                                         DoUpdate(game);
746                                 /*
747                 }
748                 else
749                 {
750                                         if (gameFocused)
751                                         {
752                                                 // allow game chance to pause
753                                                 gameFocused = false;
754                                                 DoUpdate(game);
755                                         }
756
757                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
758                                         SDL_ActiveEvent evt;
759                                         SDL_WaitEvent((SDL_Event*)&evt);
760                                         if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
761                                                 gameFocused = true;
762                                         else if (evt.type == SDL_QUIT)
763                                                 gDone = true;
764                                 }
765                 */
766                         }
767
768                 }
769                 pgame = 0;
770
771                 CleanUp ();
772
773                 return 0;
774         }
775         catch (const std::exception& error)
776         {
777                 CleanUp();
778
779                 std::string e = "Caught exception: ";
780                 e += error.what();
781
782                 LOG(e);
783
784                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
785         }
786
787         CleanUp();
788
789         return -1;
790 }
791
792
793
794 // --------------------------------------------------------------------------
795
796
797 bool LoadImage(const char * fname, TGAImageRec & tex)
798 {
799         if ( tex.data == NULL )
800                 return false;
801         else
802                 return load_image(fname, tex);
803 }
804
805 void ScreenShot(const char * fname)
806 {
807         
808 }
809
810
811
812 static bool load_image(const char *file_name, TGAImageRec &tex)
813 {
814     const char *ptr = strrchr((char *)file_name, '.');
815     if (ptr)
816     {
817         if (strcasecmp(ptr+1, "png") == 0)
818             return load_png(file_name, tex);
819         else if (strcasecmp(ptr+1, "jpg") == 0)
820             return load_jpg(file_name, tex);
821     }
822
823     STUBBED("Unsupported image type");
824     return false;
825 }
826
827
828 struct my_error_mgr {
829   struct jpeg_error_mgr pub;    /* "public" fields */
830   jmp_buf setjmp_buffer;        /* for return to caller */
831 };
832 typedef struct my_error_mgr * my_error_ptr;
833
834
835 static void my_error_exit(j_common_ptr cinfo)
836 {
837         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
838         longjmp(err->setjmp_buffer, 1);
839 }
840
841 /* stolen from public domain example.c code in libjpg distribution. */
842 static bool load_jpg(const char *file_name, TGAImageRec &tex)
843 {
844     struct jpeg_decompress_struct cinfo;
845     struct my_error_mgr jerr;
846     JSAMPROW buffer[1];         /* Output row buffer */
847     int row_stride;             /* physical row width in output buffer */
848     FILE *infile = fopen(file_name, "rb");
849
850     if (infile == NULL)
851         return false;
852
853     cinfo.err = jpeg_std_error(&jerr.pub);
854     jerr.pub.error_exit = my_error_exit;
855     if (setjmp(jerr.setjmp_buffer)) {
856         jpeg_destroy_decompress(&cinfo);
857         fclose(infile);
858         return false;
859     }
860
861     jpeg_create_decompress(&cinfo);
862     jpeg_stdio_src(&cinfo, infile);
863     (void) jpeg_read_header(&cinfo, TRUE);
864
865     cinfo.out_color_space = JCS_RGB;
866     cinfo.quantize_colors = 0;
867     (void) jpeg_calc_output_dimensions(&cinfo);
868     (void) jpeg_start_decompress(&cinfo);
869
870     row_stride = cinfo.output_width * cinfo.output_components;
871     tex.sizeX = cinfo.output_width;
872     tex.sizeY = cinfo.output_height;
873     tex.bpp = 24;
874
875     while (cinfo.output_scanline < cinfo.output_height) {
876         buffer[0] = (JSAMPROW)(char *)tex.data +
877                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
878         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
879     }
880
881     (void) jpeg_finish_decompress(&cinfo);
882     jpeg_destroy_decompress(&cinfo);
883     fclose(infile);
884
885     return true;
886 }
887
888
889 /* stolen from public domain example.c code in libpng distribution. */
890 static bool load_png(const char *file_name, TGAImageRec &tex)
891 {
892     bool hasalpha = false;
893     png_structp png_ptr = NULL;
894     png_infop info_ptr = NULL;
895     png_uint_32 width, height;
896     int bit_depth, color_type, interlace_type;
897     png_byte **rows = NULL;
898     bool retval = false;
899     png_byte **row_pointers = NULL;
900     FILE *fp = fopen(file_name, "rb");
901
902     if (fp == NULL)
903         return(NULL);
904
905     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
906     if (png_ptr == NULL)
907         goto png_done;
908
909     info_ptr = png_create_info_struct(png_ptr);
910     if (info_ptr == NULL)
911         goto png_done;
912
913     if (setjmp(png_jmpbuf(png_ptr)))
914         goto png_done;
915
916     png_init_io(png_ptr, fp);
917     png_read_png(png_ptr, info_ptr,
918                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
919                  NULL);
920     png_get_IHDR(png_ptr, info_ptr, &width, &height,
921                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
922
923     if (bit_depth != 8)  // transform SHOULD handle this...
924         goto png_done;
925
926     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
927         goto png_done;
928
929     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
930         goto png_done;
931
932     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
933     row_pointers = png_get_rows(png_ptr, info_ptr);
934     if (!row_pointers)
935         goto png_done;
936
937     if (!hasalpha)
938     {
939         png_byte *dst = tex.data;
940         for (int i = height-1; i >= 0; i--)
941         {
942             png_byte *src = row_pointers[i];
943             for (int j = 0; j < width; j++)
944             {
945                 dst[0] = src[0];
946                 dst[1] = src[1];
947                 dst[2] = src[2];
948                 dst[3] = 0xFF;
949                 src += 3;
950                 dst += 4;
951             }
952         }
953     }
954
955     else
956     {
957         png_byte *dst = tex.data;
958         int pitch = width * 4;
959         for (int i = height-1; i >= 0; i--, dst += pitch)
960             memcpy(dst, row_pointers[i], pitch);
961     }
962
963     tex.sizeX = width;
964     tex.sizeY = height;
965     tex.bpp = 32;
966     retval = true;
967
968 png_done:
969     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
970     if (fp)
971         fclose(fp);
972     return (retval);
973 }
974
975
976 bool save_image(const char *file_name)
977 {
978     const char *ptr = strrchr((char *)file_name, '.');
979     if (ptr)
980     {
981         if (strcasecmp(ptr+1, "png") == 0)
982             return save_png(file_name);
983     }
984
985     STUBBED("Unsupported image type");
986     return false;
987 }
988
989
990 static bool save_png(const char *file_name)
991 {
992     FILE *fp = NULL;
993     png_structp png_ptr = NULL;
994     png_infop info_ptr = NULL;
995     bool retval = false;
996
997     fp = fopen(file_name, "wb");
998     if (fp == NULL)
999         return false;
1000
1001     png_bytep *row_pointers = new png_bytep[kContextHeight];
1002     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1003     if ((!screenshot) || (!row_pointers))
1004         goto save_png_done;
1005
1006     glGetError();
1007     glReadPixels(0, 0, kContextWidth, kContextHeight,
1008                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1009     if (glGetError() != GL_NO_ERROR)
1010         goto save_png_done;
1011
1012     for (int i = 0; i < kContextHeight; i++)
1013         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1014
1015     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1016     if (png_ptr == NULL)
1017         goto save_png_done;
1018
1019     info_ptr = png_create_info_struct(png_ptr);
1020     if (info_ptr == NULL)
1021         goto save_png_done;
1022
1023     if (setjmp(png_jmpbuf(png_ptr)))
1024         goto save_png_done;
1025
1026     png_init_io(png_ptr, fp);
1027
1028     if (setjmp(png_jmpbuf(png_ptr)))
1029         goto save_png_done;
1030
1031     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1032                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1033                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1034
1035     png_write_info(png_ptr, info_ptr);
1036
1037     if (setjmp(png_jmpbuf(png_ptr)))
1038         goto save_png_done;
1039
1040         png_write_image(png_ptr, row_pointers);
1041
1042         if (setjmp(png_jmpbuf(png_ptr)))
1043         goto save_png_done;
1044
1045     png_write_end(png_ptr, NULL);
1046     retval = true;
1047
1048 save_png_done:
1049     png_destroy_write_struct(&png_ptr, &info_ptr);
1050     delete[] screenshot;
1051     delete[] row_pointers;
1052     if (fp)
1053         fclose(fp);
1054     if (!retval)
1055         unlink(ConvertFileName(file_name));
1056     return retval;
1057 }
1058
1059
1060