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