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