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