]> git.jsancho.org Git - lugaru.git/blob - Source/openal_wrapper.cpp
Cleanning up Sprite class. More can be done, but it's already prettier.
[lugaru.git] / Source / openal_wrapper.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 #if USE_OPENAL
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "openal_wrapper.h"
29
30 // NOTE:
31 // FMOD uses a Left Handed Coordinate system, OpenAL uses a Right Handed
32 //  one...so we just need to flip the sign on the Z axis when appropriate.
33
34 #define DYNAMIC_LOAD_OPENAL 0
35
36 #if DYNAMIC_LOAD_OPENAL
37
38 #include <dlfcn.h>
39
40 #define AL_FUNC(t,ret,fn,params,call,rt) \
41     extern "C" { \
42         static ret ALAPIENTRY (*p##fn) params = NULL; \
43         ret ALAPIENTRY fn params { rt p##fn call; } \
44     }
45 #include "alstubs.h"
46 #undef AL_FUNC
47
48 static void *aldlhandle = NULL;
49
50 static bool lookup_alsym(const char *funcname, void **func, const char *libname)
51 {
52     if (!aldlhandle)
53         return false;
54
55     *func = dlsym(aldlhandle, funcname);
56     if (*func == NULL)
57     {
58         fprintf(stderr, "Failed to find OpenAL symbol \"%s\" in \"%s\"\n",
59                  funcname, libname);
60         return false;
61     }
62     return true;
63 }
64
65 static void unload_alsyms(void)
66 {
67     #define AL_FUNC(t,ret,fn,params,call,rt) p##fn = NULL;
68     #include "alstubs.h"
69     #undef AL_FUNC
70     if (aldlhandle)
71     {
72         dlclose(aldlhandle);
73         aldlhandle = NULL;
74     }
75 }
76
77 static bool lookup_all_alsyms(const char *libname)
78 {
79     if (!aldlhandle)
80     {
81         if ( (aldlhandle = dlopen(libname, RTLD_GLOBAL | RTLD_NOW)) == NULL )
82             return false;
83     }
84
85     bool retval = true;
86     #define AL_FUNC(t,ret,fn,params,call,rt) \
87         if (!lookup_alsym(#fn, (void **) &p##fn, libname)) retval = false;
88     #include "alstubs.h"
89     #undef AL_FUNC
90
91     if (!retval)
92         unload_alsyms();
93
94     return retval;
95 }
96 #else
97 #define lookup_all_alsyms(x) (true)
98 #define unload_alsyms()
99 #endif
100
101 typedef struct
102 {
103     ALuint sid;
104     OPENAL_SAMPLE *sample;
105     bool startpaused;
106     float position[3];
107 } OPENAL_Channels;
108
109 typedef struct OPENAL_SAMPLE
110 {
111     char *name;
112     ALuint bid;  // buffer id.
113     int mode;
114     int is2d;
115     float min_distance;
116 } OPENAL_SAMPLE;
117
118 typedef struct OPENAL_STREAM
119 {
120     char *name;
121     ALuint bid;  // buffer id.
122     int mode;
123     int is2d;
124 } OPENAL_STREAM;
125
126 static size_t num_channels = 0;
127 static OPENAL_Channels *channels = NULL;
128 static bool initialized = false;
129 static float listener_position[3];
130
131 static inline bool source_too_close(const int channel)
132 {
133     const OPENAL_Channels *chan = &channels[channel];
134     const float *pos = chan->position;
135     const float distance = sqrtf(powf((pos[0] - listener_position[0]), 2.0f) +
136                                  powf((pos[1] - listener_position[1]), 2.0f) +
137                                  powf((pos[2] - listener_position[2]), 2.0f));
138     return (distance <= chan->sample->min_distance);
139 }
140
141
142 static void set_channel_position(const int channel, const float x,
143                                  const float y, const float z)
144 {
145     OPENAL_Channels *chan = &channels[channel];
146
147     chan->position[0] = x;
148     chan->position[1] = y;
149     chan->position[2] = z;
150
151     OPENAL_SAMPLE *sptr = chan->sample;
152     if (sptr == NULL)
153         return;
154
155     const ALuint sid = chan->sid;
156     const bool no_attenuate = ((sptr->is2d) || (source_too_close(channel)));
157
158     if (no_attenuate)
159     {
160         alSourcei(sid, AL_SOURCE_RELATIVE, AL_TRUE);
161         alSource3f(sid, AL_POSITION, 0.0f, 0.0f, 0.0f);
162     }
163     else
164     {
165         alSourcei(sid, AL_SOURCE_RELATIVE, AL_FALSE);
166         alSource3f(sid, AL_POSITION, x, y, z);
167     }
168 }
169
170
171 AL_API void OPENAL_3D_Listener_SetAttributes(const float *pos, const float *vel, float fx, float fy, float fz, float tx, float ty, float tz)
172 {
173     if (!initialized) return;
174     if (pos != NULL)
175     {
176         alListener3f(AL_POSITION, pos[0], pos[1], -pos[2]);
177         listener_position[0] = pos[0];
178         listener_position[1] = pos[1];
179         listener_position[2] = -pos[2];
180     }
181
182     ALfloat vec[6] = { fx, fy, -fz, tz, ty, -tz };
183     alListenerfv(AL_ORIENTATION, vec);
184
185     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
186
187     // adjust existing positions...
188     for (int i = 0; i < num_channels; i++)
189     {
190         const float *p = channels[i].position;
191         set_channel_position(i, p[0], p[1], p[2]);
192     }
193 }
194
195 AL_API signed char OPENAL_3D_SetAttributes(int channel, const float *pos, const float *vel)
196 {
197     if (!initialized) return false;
198     if ((channel < 0) || (channel >= num_channels)) return false;
199
200     if (pos != NULL)
201         set_channel_position(channel, pos[0], pos[1], -pos[2]);
202
203     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
204
205     return true;
206 }
207
208 AL_API void OPENAL_3D_SetDopplerFactor(float scale)
209 {
210     if (!initialized) return;
211     // unimplemented...looks like init routines just call this with scale == 0.0f anyhow.
212 }
213
214 AL_API signed char OPENAL_Init(int mixrate, int maxsoftwarechannels, unsigned int flags)
215 {
216     if (initialized) return false;
217     if (maxsoftwarechannels == 0) return false;
218
219     if (flags != 0)  // unsupported.
220         return false;
221
222     if (!lookup_all_alsyms("./openal.so"))  // !!! FIXME: linux specific lib name
223     {
224         if (!lookup_all_alsyms("openal.so.1"))  // !!! FIXME: linux specific lib name
225         {
226             if (!lookup_all_alsyms("openal.so"))  // !!! FIXME: linux specific lib name
227                 return false;
228         }
229     }
230
231     ALCdevice *dev = alcOpenDevice(NULL);
232     if (!dev)
233         return false;
234
235     ALint caps[] = { ALC_FREQUENCY, mixrate, 0 };
236     ALCcontext *ctx = alcCreateContext(dev, caps);
237     if (!ctx)
238     {
239         alcCloseDevice(dev);
240         return false;
241     }
242
243     alcMakeContextCurrent(ctx);
244     alcProcessContext(ctx);
245
246     bool cmdline(const char *cmd);
247     if (cmdline("openalinfo"))
248     {
249         printf("AL_VENDOR: %s\n", (char *) alGetString(AL_VENDOR));
250         printf("AL_RENDERER: %s\n", (char *) alGetString(AL_RENDERER));
251         printf("AL_VERSION: %s\n", (char *) alGetString(AL_VERSION));
252         printf("AL_EXTENSIONS: %s\n", (char *) alGetString(AL_EXTENSIONS));
253     }
254
255     num_channels = maxsoftwarechannels;
256     channels = new OPENAL_Channels[maxsoftwarechannels];
257     memset(channels, '\0', sizeof (OPENAL_Channels) * num_channels);
258     for (int i = 0; i < num_channels; i++)
259         alGenSources(1, &channels[i].sid);  // !!! FIXME: verify this didn't fail!
260
261     initialized = true;
262     return true;
263 }
264
265 AL_API void OPENAL_Close()
266 {
267     if (!initialized) return;
268
269     ALCcontext *ctx = alcGetCurrentContext();
270     if (ctx)
271     {
272         for (int i = 0; i < num_channels; i++)
273         {
274             alSourceStop(channels[i].sid);
275             alSourcei(channels[i].sid, AL_BUFFER, 0);
276             alDeleteSources(1, &channels[i].sid);
277         }
278         ALCdevice *dev = alcGetContextsDevice(ctx);
279         alcMakeContextCurrent(NULL);
280         alcSuspendContext(ctx);
281         alcDestroyContext(ctx);
282         alcCloseDevice(dev);
283     }
284
285     num_channels = 0;
286     delete[] channels;
287     channels = NULL;
288
289     unload_alsyms();
290     initialized = false;
291 }
292
293 AL_API OPENAL_SAMPLE *OPENAL_GetCurrentSample(int channel)
294 {
295     if (!initialized) return NULL;
296     if ((channel < 0) || (channel >= num_channels)) return NULL;
297     return channels[channel].sample;
298 }
299
300 AL_API signed char OPENAL_GetPaused(int channel)
301 {
302     if (!initialized) return false;
303     if ((channel < 0) || (channel >= num_channels)) return false;
304     if (channels[channel].startpaused)
305         return(true);
306
307     ALint state = 0;
308     alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
309     return((state == AL_PAUSED) ? true : false);
310 }
311
312 AL_API unsigned int OPENAL_GetLoopMode(int channel)
313 {
314     if (!initialized) return 0;
315     if ((channel < 0) || (channel >= num_channels)) return 0;
316     ALint loop = 0;
317     alGetSourceiv(channels[channel].sid, AL_LOOPING, &loop);
318     if (loop)
319         return(OPENAL_LOOP_NORMAL);
320     return OPENAL_LOOP_OFF;
321 }
322
323 AL_API signed char OPENAL_IsPlaying(int channel)
324 {
325     if (!initialized) return false;
326     if ((channel < 0) || (channel >= num_channels)) return false;
327     ALint state = 0;
328     alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
329     return((state == AL_PLAYING) ? true : false);
330 }
331
332 AL_API int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
333 {
334     if (!initialized) return -1;
335     if (sptr == NULL) return -1;
336     if (dsp != NULL) return -1;
337     if (channel == OPENAL_FREE)
338     {
339         for (int i = 0; i < num_channels; i++)
340         {
341             ALint state = 0;
342             alGetSourceiv(channels[i].sid, AL_SOURCE_STATE, &state);
343             if ((state != AL_PLAYING) && (state != AL_PAUSED))
344             {
345                 channel = i;
346                 break;
347             }
348         }
349     }
350
351     if ((channel < 0) || (channel >= num_channels)) return -1;
352     alSourceStop(channels[channel].sid);
353     channels[channel].sample = sptr;
354     alSourcei(channels[channel].sid, AL_BUFFER, sptr->bid);
355     alSourcei(channels[channel].sid, AL_LOOPING, (sptr->mode == OPENAL_LOOP_OFF) ? AL_FALSE : AL_TRUE);
356     set_channel_position(channel, 0.0f, 0.0f, 0.0f);
357
358     channels[channel].startpaused = ((startpaused) ? true : false);
359     if (!startpaused)
360         alSourcePlay(channels[channel].sid);
361     return channel;
362 }
363
364
365 static void *decode_to_pcm(const char *_fname, ALenum &format, ALsizei &size, ALuint &freq)
366 {
367 #ifdef __POWERPC__
368     const int bigendian = 1;
369 #else
370     const int bigendian = 0;
371 #endif
372
373     // !!! FIXME: if it's not Ogg, we don't have a decoder. I'm lazy.  :/
374     char *fname = (char *) alloca(strlen(_fname) + 16);
375     strcpy(fname, _fname);
376     char *ptr = strchr(fname, '.');
377     if (ptr) *ptr = '\0';
378     strcat(fname, ".ogg");
379
380     // just in case...
381     #undef fopen
382     FILE *io = fopen(fname, "rb");
383     if (io == NULL)
384         return NULL;
385
386     ALubyte *retval = NULL;
387
388     #if 0  // untested, so disable this!
389     // Can we just feed it to the AL compressed?
390     if (alIsExtensionPresent((const ALubyte *) "AL_EXT_vorbis"))
391     {
392         format = alGetEnumValue((const ALubyte *) "AL_FORMAT_VORBIS_EXT");
393         freq = 44100;
394         fseek(io, 0, SEEK_END);
395         size = ftell(io);
396         fseek(io, 0, SEEK_SET);
397         retval = (ALubyte *) malloc(size);
398         size_t rc = fread(retval, size, 1, io);
399         fclose(io);
400         if (rc != 1)
401         {
402             free(retval);
403             return NULL;
404         }
405         return retval;
406     }
407     #endif
408
409     // Uncompress and feed to the AL.
410     OggVorbis_File vf;
411     memset(&vf, '\0', sizeof (vf));
412     if (ov_open(io, &vf, NULL, 0) == 0)
413     {
414         int bitstream = 0;
415         vorbis_info *info = ov_info(&vf, -1);
416         size = 0;
417         format = (info->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
418         freq = info->rate;
419
420         if ((info->channels != 1) && (info->channels != 2))
421         {
422             ov_clear(&vf);
423             return NULL;
424         }
425
426         char buf[1024 * 16];
427         long rc = 0;
428         size_t allocated = 64 * 1024;
429         retval = (ALubyte *) malloc(allocated);
430         while ( (rc = ov_read(&vf, buf, sizeof (buf), bigendian, 2, 1, &bitstream)) != 0 )
431         {
432             if (rc > 0)
433             {
434                 size += rc;
435                 if (size >= allocated)
436                 {
437                     allocated *= 2;
438                     ALubyte *tmp = (ALubyte *) realloc(retval, allocated);
439                     if (tmp == NULL)
440                     {
441                         free(retval);
442                         retval = NULL;
443                         break;
444                     }
445                     retval = tmp;
446                 }
447                 memcpy(retval + (size - rc), buf, rc);
448             }
449         }
450         ov_clear(&vf);
451         return retval;
452     }
453
454     fclose(io);
455     return NULL;
456 }
457
458
459 AL_API OPENAL_SAMPLE *OPENAL_Sample_Load(int index, const char *name_or_data, unsigned int mode, int offset, int length)
460 {
461     if (!initialized) return NULL;
462     if (index != OPENAL_FREE) return NULL;  // this is all the game does...
463     if (offset != 0) return NULL;  // this is all the game does...
464     if (length != 0) return NULL;  // this is all the game does...
465     if ((mode != OPENAL_HW3D) && (mode != OPENAL_2D)) return NULL;  // this is all the game does...
466
467     OPENAL_SAMPLE *retval = NULL;
468     ALuint bufferName = 0;
469     ALenum format = AL_NONE;
470     ALsizei size = 0;
471     ALuint frequency = 0;
472     void *data = decode_to_pcm(name_or_data, format, size, frequency);
473     if (data == NULL)
474         return NULL;
475
476     ALuint bid = 0;
477     alGetError();
478     alGenBuffers(1, &bid);
479     if (alGetError() == AL_NO_ERROR)
480     {
481         alBufferData(bid, format, data, size, frequency);
482         retval = new OPENAL_SAMPLE;
483         retval->bid = bid;
484         retval->mode = OPENAL_LOOP_OFF;
485         retval->is2d = (mode == OPENAL_2D);
486         retval->name = new char[strlen(name_or_data) + 1];
487         if (retval->name)
488             strcpy(retval->name, name_or_data);
489     }
490
491     free(data);
492     return(retval);
493 }
494
495 AL_API void OPENAL_Sample_Free(OPENAL_SAMPLE *sptr)
496 {
497     if (!initialized) return;
498     if (sptr)
499     {
500         for (int i = 0; i < num_channels; i++)
501         {
502             if (channels[i].sample == sptr)
503             {
504                 alSourceStop(channels[i].sid);
505                 alSourcei(channels[i].sid, AL_BUFFER, 0);
506                 channels[i].sample = NULL;
507             }
508         }
509         alDeleteBuffers(1, &sptr->bid);
510         delete[] sptr->name;
511         delete sptr;
512     }
513 }
514
515 AL_API signed char OPENAL_Sample_SetMode(OPENAL_SAMPLE *sptr, unsigned int mode)
516 {
517     if (!initialized) return false;
518     if ((mode != OPENAL_LOOP_NORMAL) && (mode != OPENAL_LOOP_OFF)) return false;
519     if (!sptr) return false;
520     sptr->mode = mode;
521     return true;
522 }
523
524 AL_API signed char OPENAL_Sample_SetMinMaxDistance(OPENAL_SAMPLE *sptr, float mindist, float maxdist)
525 {
526     if (!initialized) return false;
527     if (sptr == NULL) return false;
528     sptr->min_distance = mindist;
529     // we ignore maxdist. It's not really important to this game, and the
530     //  FMOD docs suggest that it's worthless anyhow.
531
532     // recalc sources to see if we need to adjust attenuation.
533     for (int i = 0; i < num_channels; i++)
534     {
535         if (channels[i].sample == sptr)
536         {
537             const float *p = channels[i].position;
538             set_channel_position(i, p[0], p[1], p[2]);
539         }
540     }
541
542     return 0;
543 }
544
545 AL_API signed char OPENAL_SetFrequency(int channel, int freq)
546 {
547     if (!initialized) return false;
548     if (channel == OPENAL_ALL)
549     {
550         for (int i = 0; i < num_channels; i++)
551             OPENAL_SetFrequency(i, freq);
552         return true;
553     }
554
555     if ((channel < 0) || (channel >= num_channels)) return false;
556     if (freq == 8012)  // hack
557         alSourcef(channels[channel].sid, AL_PITCH, 8012.0f / 44100.0f);
558     else
559         alSourcef(channels[channel].sid, AL_PITCH, 1.0f);
560     return true;
561 }
562
563 AL_API signed char OPENAL_SetVolume(int channel, int vol)
564 {
565     if (!initialized) return false;
566
567     if (channel == OPENAL_ALL)
568     {
569         for (int i = 0; i < num_channels; i++)
570             OPENAL_SetVolume(i, vol);
571         return true;
572     }
573
574     if ((channel < 0) || (channel >= num_channels)) return false;
575
576     if (vol < 0) vol = 0;
577     else if (vol > 255) vol = 255;
578     ALfloat gain = ((ALfloat) vol) / 255.0f;
579     alSourcef(channels[channel].sid, AL_GAIN, gain);
580     return true;
581 }
582
583 AL_API signed char OPENAL_SetPaused(int channel, signed char paused)
584 {
585     if (!initialized) return false;
586
587     if (channel == OPENAL_ALL)
588     {
589         for (int i = 0; i < num_channels; i++)
590             OPENAL_SetPaused(i, paused);
591         return true;
592     }
593
594     if ((channel < 0) || (channel >= num_channels)) return false;
595
596     ALint state = 0;
597     if (channels[channel].startpaused)
598         state = AL_PAUSED;
599     else
600         alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
601
602     if ((paused) && (state == AL_PLAYING))
603         alSourcePause(channels[channel].sid);
604     else if ((!paused) && (state == AL_PAUSED))
605     {
606         alSourcePlay(channels[channel].sid);
607         channels[channel].startpaused = false;
608     }
609     return true;
610 }
611
612 AL_API void OPENAL_SetSFXMasterVolume(int volume)
613 {
614     if (!initialized) return;
615     ALfloat gain = ((ALfloat) volume) / 255.0f;
616     alListenerf(AL_GAIN, gain);
617 }
618
619 AL_API signed char OPENAL_StopSound(int channel)
620 {
621     if (!initialized) return false;
622
623     if (channel == OPENAL_ALL)
624     {
625         for (int i = 0; i < num_channels; i++)
626             OPENAL_StopSound(i);
627         return true;
628     }
629
630     if ((channel < 0) || (channel >= num_channels)) return false;
631     alSourceStop(channels[channel].sid);
632     channels[channel].startpaused = false;
633     return true;
634 }
635
636 AL_API OPENAL_STREAM *OPENAL_Stream_Open(const char *name_or_data, unsigned int mode, int offset, int length)
637 {
638     return (OPENAL_STREAM *) OPENAL_Sample_Load(OPENAL_FREE, name_or_data, mode, offset, length);
639 }
640
641 AL_API void OPENAL_Stream_Close(OPENAL_STREAM *stream)
642 {
643     OPENAL_Sample_Free((OPENAL_SAMPLE *) stream);
644 }
645
646 AL_API OPENAL_SAMPLE *OPENAL_Stream_GetSample(OPENAL_STREAM *stream)
647 {
648     if (!initialized) return NULL;
649     return (OPENAL_SAMPLE *) stream;
650 }
651
652 AL_API int OPENAL_Stream_PlayEx(int channel, OPENAL_STREAM *stream, OPENAL_DSPUNIT *dsp, signed char startpaused)
653 {
654     return OPENAL_PlaySoundEx(channel, (OPENAL_SAMPLE *) stream, dsp, startpaused);
655 }
656
657 AL_API signed char OPENAL_Stream_Stop(OPENAL_STREAM *stream)
658 {
659     if (!initialized) return false;
660     for (int i = 0; i < num_channels; i++)
661     {
662         if (channels[i].sample == (OPENAL_SAMPLE *) stream)
663         {
664             alSourceStop(channels[i].sid);
665             channels[i].startpaused = false;
666         }
667     }
668     return true;
669 }
670
671 AL_API signed char OPENAL_Stream_SetMode(OPENAL_STREAM *stream, unsigned int mode)
672 {
673     return OPENAL_Sample_SetMode((OPENAL_SAMPLE *) stream, mode);
674 }
675
676 AL_API void OPENAL_Update()
677 {
678     if (!initialized) return;
679     alcProcessContext(alcGetCurrentContext());
680 }
681
682 AL_API signed char OPENAL_SetOutput(int outputtype)
683 {
684     return true;
685 }
686
687 #endif
688