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