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