Remove the last remaining uses of althrd_t
[openal-soft.git] / examples / almultireverb.c
bloba258758560de7aed80bdb094569f10853b7322dd
1 /*
2 * OpenAL Multi-Zone Reverb Example
4 * Copyright (c) 2018 by Chris Robinson <chris.kcat@gmail.com>
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 /* This file contains an example for controlling multiple reverb zones to
26 * smoothly transition between reverb environments. The general concept is to
27 * extend single-reverb by also tracking the closest adjacent environment, and
28 * utilize EAX Reverb's panning vectors to position them relative to the
29 * listener.
32 #include <stdio.h>
33 #include <assert.h>
34 #include <math.h>
36 #include <SDL_sound.h>
38 #include "AL/al.h"
39 #include "AL/alc.h"
40 #include "AL/alext.h"
41 #include "AL/efx-presets.h"
43 #include "common/alhelpers.h"
46 #ifndef M_PI
47 #define M_PI 3.14159265358979323846
48 #endif
51 /* Filter object functions */
52 static LPALGENFILTERS alGenFilters;
53 static LPALDELETEFILTERS alDeleteFilters;
54 static LPALISFILTER alIsFilter;
55 static LPALFILTERI alFilteri;
56 static LPALFILTERIV alFilteriv;
57 static LPALFILTERF alFilterf;
58 static LPALFILTERFV alFilterfv;
59 static LPALGETFILTERI alGetFilteri;
60 static LPALGETFILTERIV alGetFilteriv;
61 static LPALGETFILTERF alGetFilterf;
62 static LPALGETFILTERFV alGetFilterfv;
64 /* Effect object functions */
65 static LPALGENEFFECTS alGenEffects;
66 static LPALDELETEEFFECTS alDeleteEffects;
67 static LPALISEFFECT alIsEffect;
68 static LPALEFFECTI alEffecti;
69 static LPALEFFECTIV alEffectiv;
70 static LPALEFFECTF alEffectf;
71 static LPALEFFECTFV alEffectfv;
72 static LPALGETEFFECTI alGetEffecti;
73 static LPALGETEFFECTIV alGetEffectiv;
74 static LPALGETEFFECTF alGetEffectf;
75 static LPALGETEFFECTFV alGetEffectfv;
77 /* Auxiliary Effect Slot object functions */
78 static LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots;
79 static LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots;
80 static LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot;
81 static LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti;
82 static LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv;
83 static LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf;
84 static LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv;
85 static LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti;
86 static LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv;
87 static LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf;
88 static LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv;
91 /* LoadEffect loads the given initial reverb properties into the given OpenAL
92 * effect object, and returns non-zero on success.
94 static int LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES *reverb)
96 ALenum err;
98 alGetError();
100 /* Prepare the effect for EAX Reverb (standard reverb doesn't contain
101 * the needed panning vectors).
103 alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB);
104 if((err=alGetError()) != AL_NO_ERROR)
106 fprintf(stderr, "Failed to set EAX Reverb: %s (0x%04x)\n", alGetString(err), err);
107 return 0;
110 /* Load the reverb properties. */
111 alEffectf(effect, AL_EAXREVERB_DENSITY, reverb->flDensity);
112 alEffectf(effect, AL_EAXREVERB_DIFFUSION, reverb->flDiffusion);
113 alEffectf(effect, AL_EAXREVERB_GAIN, reverb->flGain);
114 alEffectf(effect, AL_EAXREVERB_GAINHF, reverb->flGainHF);
115 alEffectf(effect, AL_EAXREVERB_GAINLF, reverb->flGainLF);
116 alEffectf(effect, AL_EAXREVERB_DECAY_TIME, reverb->flDecayTime);
117 alEffectf(effect, AL_EAXREVERB_DECAY_HFRATIO, reverb->flDecayHFRatio);
118 alEffectf(effect, AL_EAXREVERB_DECAY_LFRATIO, reverb->flDecayLFRatio);
119 alEffectf(effect, AL_EAXREVERB_REFLECTIONS_GAIN, reverb->flReflectionsGain);
120 alEffectf(effect, AL_EAXREVERB_REFLECTIONS_DELAY, reverb->flReflectionsDelay);
121 alEffectfv(effect, AL_EAXREVERB_REFLECTIONS_PAN, reverb->flReflectionsPan);
122 alEffectf(effect, AL_EAXREVERB_LATE_REVERB_GAIN, reverb->flLateReverbGain);
123 alEffectf(effect, AL_EAXREVERB_LATE_REVERB_DELAY, reverb->flLateReverbDelay);
124 alEffectfv(effect, AL_EAXREVERB_LATE_REVERB_PAN, reverb->flLateReverbPan);
125 alEffectf(effect, AL_EAXREVERB_ECHO_TIME, reverb->flEchoTime);
126 alEffectf(effect, AL_EAXREVERB_ECHO_DEPTH, reverb->flEchoDepth);
127 alEffectf(effect, AL_EAXREVERB_MODULATION_TIME, reverb->flModulationTime);
128 alEffectf(effect, AL_EAXREVERB_MODULATION_DEPTH, reverb->flModulationDepth);
129 alEffectf(effect, AL_EAXREVERB_AIR_ABSORPTION_GAINHF, reverb->flAirAbsorptionGainHF);
130 alEffectf(effect, AL_EAXREVERB_HFREFERENCE, reverb->flHFReference);
131 alEffectf(effect, AL_EAXREVERB_LFREFERENCE, reverb->flLFReference);
132 alEffectf(effect, AL_EAXREVERB_ROOM_ROLLOFF_FACTOR, reverb->flRoomRolloffFactor);
133 alEffecti(effect, AL_EAXREVERB_DECAY_HFLIMIT, reverb->iDecayHFLimit);
135 /* Check if an error occured, and return failure if so. */
136 if((err=alGetError()) != AL_NO_ERROR)
138 fprintf(stderr, "Error setting up reverb: %s\n", alGetString(err));
139 return 0;
142 return 1;
146 /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
147 * returns the new buffer ID.
149 static ALuint LoadSound(const char *filename)
151 Sound_Sample *sample;
152 ALenum err, format;
153 ALuint buffer;
154 Uint32 slen;
156 /* Open the audio file */
157 sample = Sound_NewSampleFromFile(filename, NULL, 65536);
158 if(!sample)
160 fprintf(stderr, "Could not open audio in %s\n", filename);
161 return 0;
164 /* Get the sound format, and figure out the OpenAL format */
165 if(sample->actual.channels == 1)
167 if(sample->actual.format == AUDIO_U8)
168 format = AL_FORMAT_MONO8;
169 else if(sample->actual.format == AUDIO_S16SYS)
170 format = AL_FORMAT_MONO16;
171 else
173 fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
174 Sound_FreeSample(sample);
175 return 0;
178 else if(sample->actual.channels == 2)
180 if(sample->actual.format == AUDIO_U8)
181 format = AL_FORMAT_STEREO8;
182 else if(sample->actual.format == AUDIO_S16SYS)
183 format = AL_FORMAT_STEREO16;
184 else
186 fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
187 Sound_FreeSample(sample);
188 return 0;
191 else
193 fprintf(stderr, "Unsupported channel count: %d\n", sample->actual.channels);
194 Sound_FreeSample(sample);
195 return 0;
198 /* Decode the whole audio stream to a buffer. */
199 slen = Sound_DecodeAll(sample);
200 if(!sample->buffer || slen == 0)
202 fprintf(stderr, "Failed to read audio from %s\n", filename);
203 Sound_FreeSample(sample);
204 return 0;
207 /* Buffer the audio data into a new buffer object, then free the data and
208 * close the file. */
209 buffer = 0;
210 alGenBuffers(1, &buffer);
211 alBufferData(buffer, format, sample->buffer, slen, sample->actual.rate);
212 Sound_FreeSample(sample);
214 /* Check if an error occured, and clean up if so. */
215 err = alGetError();
216 if(err != AL_NO_ERROR)
218 fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
219 if(buffer && alIsBuffer(buffer))
220 alDeleteBuffers(1, &buffer);
221 return 0;
224 return buffer;
228 /* Helper to calculate the dot-product of the two given vectors. */
229 static ALfloat dot_product(const ALfloat vec0[3], const ALfloat vec1[3])
231 return vec0[0]*vec1[0] + vec0[1]*vec1[1] + vec0[2]*vec1[2];
234 /* Helper to normalize a given vector. */
235 static void normalize(ALfloat vec[3])
237 ALfloat mag = sqrtf(dot_product(vec, vec));
238 if(mag > 0.00001f)
240 vec[0] /= mag;
241 vec[1] /= mag;
242 vec[2] /= mag;
244 else
246 vec[0] = 0.0f;
247 vec[1] = 0.0f;
248 vec[2] = 0.0f;
253 /* The main update function to update the listener and environment effects. */
254 static void UpdateListenerAndEffects(float timediff, const ALuint slots[2], const ALuint effects[2], const EFXEAXREVERBPROPERTIES reverbs[2])
256 static const ALfloat listener_move_scale = 10.0f;
257 /* Individual reverb zones are connected via "portals". Each portal has a
258 * position (center point of the connecting area), a normal (facing
259 * direction), and a radius (approximate size of the connecting area).
261 const ALfloat portal_pos[3] = { 0.0f, 0.0f, 0.0f };
262 const ALfloat portal_norm[3] = { sqrtf(0.5f), 0.0f, -sqrtf(0.5f) };
263 const ALfloat portal_radius = 2.5f;
264 ALfloat other_dir[3], this_dir[3];
265 ALfloat listener_pos[3];
266 ALfloat local_norm[3];
267 ALfloat local_dir[3];
268 ALfloat near_edge[3];
269 ALfloat far_edge[3];
270 ALfloat dist, edist;
272 /* Update the listener position for the amount of time passed. This uses a
273 * simple triangular LFO to offset the position (moves along the X axis
274 * between -listener_move_scale and +listener_move_scale for each
275 * transition).
277 listener_pos[0] = (fabsf(2.0f - timediff/2.0f) - 1.0f) * listener_move_scale;
278 listener_pos[1] = 0.0f;
279 listener_pos[2] = 0.0f;
280 alListenerfv(AL_POSITION, listener_pos);
282 /* Calculate local_dir, which represents the listener-relative point to the
283 * adjacent zone (should also include orientation). Because EAX Reverb uses
284 * left-handed coordinates instead of right-handed like the rest of OpenAL,
285 * negate Z for the local values.
287 local_dir[0] = portal_pos[0] - listener_pos[0];
288 local_dir[1] = portal_pos[1] - listener_pos[1];
289 local_dir[2] = -(portal_pos[2] - listener_pos[2]);
290 /* A normal application would also rotate the portal's normal given the
291 * listener orientation, to get the listener-relative normal.
293 local_norm[0] = portal_norm[0];
294 local_norm[1] = portal_norm[1];
295 local_norm[2] = -portal_norm[2];
297 /* Calculate the distance from the listener to the portal, and ensure it's
298 * far enough away to not suffer severe floating-point precision issues.
300 dist = sqrtf(dot_product(local_dir, local_dir));
301 if(dist > 0.00001f)
303 const EFXEAXREVERBPROPERTIES *other_reverb, *this_reverb;
304 ALuint other_effect, this_effect;
305 ALfloat magnitude, dir_dot_norm;
307 /* Normalize the direction to the portal. */
308 local_dir[0] /= dist;
309 local_dir[1] /= dist;
310 local_dir[2] /= dist;
312 /* Calculate the dot product of the portal's local direction and local
313 * normal, which is used for angular and side checks later on.
315 dir_dot_norm = dot_product(local_dir, local_norm);
317 /* Figure out which zone we're in. */
318 if(dir_dot_norm <= 0.0f)
320 /* We're in front of the portal, so we're in Zone 0. */
321 this_effect = effects[0];
322 other_effect = effects[1];
323 this_reverb = &reverbs[0];
324 other_reverb = &reverbs[1];
326 else
328 /* We're behind the portal, so we're in Zone 1. */
329 this_effect = effects[1];
330 other_effect = effects[0];
331 this_reverb = &reverbs[1];
332 other_reverb = &reverbs[0];
335 /* Calculate the listener-relative extents of the portal. */
336 /* First, project the listener-to-portal vector onto the portal's plane
337 * to get the portal-relative direction along the plane that goes away
338 * from the listener (toward the farthest edge of the portal).
340 far_edge[0] = local_dir[0] - local_norm[0]*dir_dot_norm;
341 far_edge[1] = local_dir[1] - local_norm[1]*dir_dot_norm;
342 far_edge[2] = local_dir[2] - local_norm[2]*dir_dot_norm;
344 edist = sqrtf(dot_product(far_edge, far_edge));
345 if(edist > 0.0001f)
347 /* Rescale the portal-relative vector to be at the radius edge. */
348 ALfloat mag = portal_radius / edist;
349 far_edge[0] *= mag;
350 far_edge[1] *= mag;
351 far_edge[2] *= mag;
353 /* Calculate the closest edge of the portal by negating the
354 * farthest, and add an offset to make them both relative to the
355 * listener.
357 near_edge[0] = local_dir[0]*dist - far_edge[0];
358 near_edge[1] = local_dir[1]*dist - far_edge[1];
359 near_edge[2] = local_dir[2]*dist - far_edge[2];
360 far_edge[0] += local_dir[0]*dist;
361 far_edge[1] += local_dir[1]*dist;
362 far_edge[2] += local_dir[2]*dist;
364 /* Normalize the listener-relative extents of the portal, then
365 * calculate the panning magnitude for the other zone given the
366 * apparent size of the opening. The panning magnitude affects the
367 * envelopment of the environment, with 1 being a point, 0.5 being
368 * half coverage around the listener, and 0 being full coverage.
370 normalize(far_edge);
371 normalize(near_edge);
372 magnitude = 1.0f - acosf(dot_product(far_edge, near_edge))/(float)(M_PI*2.0);
374 /* Recalculate the panning direction, to be directly between the
375 * direction of the two extents.
377 local_dir[0] = far_edge[0] + near_edge[0];
378 local_dir[1] = far_edge[1] + near_edge[1];
379 local_dir[2] = far_edge[2] + near_edge[2];
380 normalize(local_dir);
382 else
384 /* If we get here, the listener is directly in front of or behind
385 * the center of the portal, making all aperture edges effectively
386 * equidistant. Calculating the panning magnitude is simplified,
387 * using the arctangent of the radius and distance.
389 magnitude = 1.0f - (atan2f(portal_radius, dist) / (float)M_PI);
392 /* Scale the other zone's panning vector. */
393 other_dir[0] = local_dir[0] * magnitude;
394 other_dir[1] = local_dir[1] * magnitude;
395 other_dir[2] = local_dir[2] * magnitude;
396 /* Pan the current zone to the opposite direction of the portal, and
397 * take the remaining percentage of the portal's magnitude.
399 this_dir[0] = local_dir[0] * (magnitude-1.0f);
400 this_dir[1] = local_dir[1] * (magnitude-1.0f);
401 this_dir[2] = local_dir[2] * (magnitude-1.0f);
403 /* Now set the effects' panning vectors and gain. Energy is shared
404 * between environments, so attenuate according to each zone's
405 * contribution (note: gain^2 = energy).
407 alEffectf(this_effect, AL_EAXREVERB_REFLECTIONS_GAIN, this_reverb->flReflectionsGain * sqrtf(magnitude));
408 alEffectf(this_effect, AL_EAXREVERB_LATE_REVERB_GAIN, this_reverb->flLateReverbGain * sqrtf(magnitude));
409 alEffectfv(this_effect, AL_EAXREVERB_REFLECTIONS_PAN, this_dir);
410 alEffectfv(this_effect, AL_EAXREVERB_LATE_REVERB_PAN, this_dir);
412 alEffectf(other_effect, AL_EAXREVERB_REFLECTIONS_GAIN, other_reverb->flReflectionsGain * sqrtf(1.0f-magnitude));
413 alEffectf(other_effect, AL_EAXREVERB_LATE_REVERB_GAIN, other_reverb->flLateReverbGain * sqrtf(1.0f-magnitude));
414 alEffectfv(other_effect, AL_EAXREVERB_REFLECTIONS_PAN, other_dir);
415 alEffectfv(other_effect, AL_EAXREVERB_LATE_REVERB_PAN, other_dir);
417 else
419 /* We're practically in the center of the portal. Give the panning
420 * vectors a 50/50 split, with Zone 0 covering the half in front of
421 * the normal, and Zone 1 covering the half behind.
423 this_dir[0] = local_norm[0] / 2.0f;
424 this_dir[1] = local_norm[1] / 2.0f;
425 this_dir[2] = local_norm[2] / 2.0f;
427 other_dir[0] = local_norm[0] / -2.0f;
428 other_dir[1] = local_norm[1] / -2.0f;
429 other_dir[2] = local_norm[2] / -2.0f;
431 alEffectf(effects[0], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[0].flReflectionsGain * sqrtf(0.5f));
432 alEffectf(effects[0], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[0].flLateReverbGain * sqrtf(0.5f));
433 alEffectfv(effects[0], AL_EAXREVERB_REFLECTIONS_PAN, this_dir);
434 alEffectfv(effects[0], AL_EAXREVERB_LATE_REVERB_PAN, this_dir);
436 alEffectf(effects[1], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[1].flReflectionsGain * sqrtf(0.5f));
437 alEffectf(effects[1], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[1].flLateReverbGain * sqrtf(0.5f));
438 alEffectfv(effects[1], AL_EAXREVERB_REFLECTIONS_PAN, other_dir);
439 alEffectfv(effects[1], AL_EAXREVERB_LATE_REVERB_PAN, other_dir);
442 /* Finally, update the effect slots with the updated effect parameters. */
443 alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, effects[0]);
444 alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, effects[1]);
448 int main(int argc, char **argv)
450 static const int MaxTransitions = 8;
451 EFXEAXREVERBPROPERTIES reverbs[2] = {
452 EFX_REVERB_PRESET_CARPETEDHALLWAY,
453 EFX_REVERB_PRESET_BATHROOM
455 struct timespec basetime;
456 ALCdevice *device = NULL;
457 ALCcontext *context = NULL;
458 ALuint effects[2] = { 0, 0 };
459 ALuint slots[2] = { 0, 0 };
460 ALuint direct_filter = 0;
461 ALuint buffer = 0;
462 ALuint source = 0;
463 ALCint num_sends = 0;
464 ALenum state = AL_INITIAL;
465 ALfloat direct_gain = 1.0f;
466 int loops = 0;
468 /* Print out usage if no arguments were specified */
469 if(argc < 2)
471 fprintf(stderr, "Usage: %s [-device <name>] [options] <filename>\n\n"
472 "Options:\n"
473 "\t-nodirect\tSilence direct path output (easier to hear reverb)\n\n",
474 argv[0]);
475 return 1;
478 /* Initialize OpenAL, and check for EFX support with at least 2 auxiliary
479 * sends (if multiple sends are supported, 2 are provided by default; if
480 * you want more, you have to request it through alcCreateContext).
482 argv++; argc--;
483 if(InitAL(&argv, &argc) != 0)
484 return 1;
486 while(argc > 0)
488 if(strcmp(argv[0], "-nodirect") == 0)
489 direct_gain = 0.0f;
490 else
491 break;
492 argv++;
493 argc--;
495 if(argc < 1)
497 fprintf(stderr, "No filename spacified.\n");
498 CloseAL();
499 return 1;
502 context = alcGetCurrentContext();
503 device = alcGetContextsDevice(context);
505 if(!alcIsExtensionPresent(device, "ALC_EXT_EFX"))
507 fprintf(stderr, "Error: EFX not supported\n");
508 CloseAL();
509 return 1;
512 num_sends = 0;
513 alcGetIntegerv(device, ALC_MAX_AUXILIARY_SENDS, 1, &num_sends);
514 if(alcGetError(device) != ALC_NO_ERROR || num_sends < 2)
516 fprintf(stderr, "Error: Device does not support multiple sends (got %d, need 2)\n",
517 num_sends);
518 CloseAL();
519 return 1;
522 /* Define a macro to help load the function pointers. */
523 #define LOAD_PROC(x) ((x) = alGetProcAddress(#x))
524 LOAD_PROC(alGenFilters);
525 LOAD_PROC(alDeleteFilters);
526 LOAD_PROC(alIsFilter);
527 LOAD_PROC(alFilteri);
528 LOAD_PROC(alFilteriv);
529 LOAD_PROC(alFilterf);
530 LOAD_PROC(alFilterfv);
531 LOAD_PROC(alGetFilteri);
532 LOAD_PROC(alGetFilteriv);
533 LOAD_PROC(alGetFilterf);
534 LOAD_PROC(alGetFilterfv);
536 LOAD_PROC(alGenEffects);
537 LOAD_PROC(alDeleteEffects);
538 LOAD_PROC(alIsEffect);
539 LOAD_PROC(alEffecti);
540 LOAD_PROC(alEffectiv);
541 LOAD_PROC(alEffectf);
542 LOAD_PROC(alEffectfv);
543 LOAD_PROC(alGetEffecti);
544 LOAD_PROC(alGetEffectiv);
545 LOAD_PROC(alGetEffectf);
546 LOAD_PROC(alGetEffectfv);
548 LOAD_PROC(alGenAuxiliaryEffectSlots);
549 LOAD_PROC(alDeleteAuxiliaryEffectSlots);
550 LOAD_PROC(alIsAuxiliaryEffectSlot);
551 LOAD_PROC(alAuxiliaryEffectSloti);
552 LOAD_PROC(alAuxiliaryEffectSlotiv);
553 LOAD_PROC(alAuxiliaryEffectSlotf);
554 LOAD_PROC(alAuxiliaryEffectSlotfv);
555 LOAD_PROC(alGetAuxiliaryEffectSloti);
556 LOAD_PROC(alGetAuxiliaryEffectSlotiv);
557 LOAD_PROC(alGetAuxiliaryEffectSlotf);
558 LOAD_PROC(alGetAuxiliaryEffectSlotfv);
559 #undef LOAD_PROC
561 /* Initialize SDL_sound. */
562 Sound_Init();
564 /* Load the sound into a buffer. */
565 buffer = LoadSound(argv[0]);
566 if(!buffer)
568 CloseAL();
569 Sound_Quit();
570 return 1;
573 /* Generate two effects for two "zones", and load a reverb into each one.
574 * Note that unlike single-zone reverb, where you can store one effect per
575 * preset, for multi-zone reverb you should have one effect per environment
576 * instance, or one per audible zone. This is because we'll be changing the
577 * effects' properties in real-time based on the environment instance
578 * relative to the listener.
580 alGenEffects(2, effects);
581 if(!LoadEffect(effects[0], &reverbs[0]) || !LoadEffect(effects[1], &reverbs[1]))
583 alDeleteEffects(2, effects);
584 alDeleteBuffers(1, &buffer);
585 Sound_Quit();
586 CloseAL();
587 return 1;
590 /* Create the effect slot objects, one for each "active" effect. */
591 alGenAuxiliaryEffectSlots(2, slots);
593 /* Tell the effect slots to use the loaded effect objects, with slot 0 for
594 * Zone 0 and slot 1 for Zone 1. Note that this effectively copies the
595 * effect properties. Modifying or deleting the effect object afterward
596 * won't directly affect the effect slot until they're reapplied like this.
598 alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, effects[0]);
599 alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, effects[1]);
600 assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot");
602 /* For the purposes of this example, prepare a filter that optionally
603 * silences the direct path which allows us to hear just the reverberation.
604 * A filter like this is normally used for obstruction, where the path
605 * directly between the listener and source is blocked (the exact
606 * properties depending on the type and thickness of the obstructing
607 * material).
609 alGenFilters(1, &direct_filter);
610 alFilteri(direct_filter, AL_FILTER_TYPE, AL_FILTER_LOWPASS);
611 alFilterf(direct_filter, AL_LOWPASS_GAIN, direct_gain);
612 assert(alGetError()==AL_NO_ERROR && "Failed to set direct filter");
614 /* Create the source to play the sound with, place it in front of the
615 * listener's path in the left zone.
617 source = 0;
618 alGenSources(1, &source);
619 alSourcei(source, AL_LOOPING, AL_TRUE);
620 alSource3f(source, AL_POSITION, -5.0f, 0.0f, -2.0f);
621 alSourcei(source, AL_DIRECT_FILTER, direct_filter);
622 alSourcei(source, AL_BUFFER, buffer);
624 /* Connect the source to the effect slots. Here, we connect source send 0
625 * to Zone 0's slot, and send 1 to Zone 1's slot. Filters can be specified
626 * to occlude the source from each zone by varying amounts; for example, a
627 * source within a particular zone would be unfiltered, while a source that
628 * can only see a zone through a window or thin wall may be attenuated for
629 * that zone.
631 alSource3i(source, AL_AUXILIARY_SEND_FILTER, slots[0], 0, AL_FILTER_NULL);
632 alSource3i(source, AL_AUXILIARY_SEND_FILTER, slots[1], 1, AL_FILTER_NULL);
633 assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
635 /* Get the current time as the base for timing in the main loop. */
636 altimespec_get(&basetime, AL_TIME_UTC);
637 loops = 0;
638 printf("Transition %d of %d...\n", loops+1, MaxTransitions);
640 /* Play the sound for a while. */
641 alSourcePlay(source);
642 do {
643 struct timespec curtime;
644 ALfloat timediff;
646 /* Start a batch update, to ensure all changes apply simultaneously. */
647 alcSuspendContext(context);
649 /* Get the current time to track the amount of time that passed.
650 * Convert the difference to seconds.
652 altimespec_get(&curtime, AL_TIME_UTC);
653 timediff = (ALfloat)(curtime.tv_sec - basetime.tv_sec);
654 timediff += (ALfloat)(curtime.tv_nsec - basetime.tv_nsec) / 1000000000.0f;
656 /* Avoid negative time deltas, in case of non-monotonic clocks. */
657 if(timediff < 0.0f)
658 timediff = 0.0f;
659 else while(timediff >= 4.0f*((loops&1)+1))
661 /* For this example, each transition occurs over 4 seconds, and
662 * there's 2 transitions per cycle.
664 if(++loops < MaxTransitions)
665 printf("Transition %d of %d...\n", loops+1, MaxTransitions);
666 if(!(loops&1))
668 /* Cycle completed. Decrease the delta and increase the base
669 * time to start a new cycle.
671 timediff -= 8.0f;
672 basetime.tv_sec += 8;
676 /* Update the listener and effects, and finish the batch. */
677 UpdateListenerAndEffects(timediff, slots, effects, reverbs);
678 alcProcessContext(context);
680 al_nssleep(10000000);
682 alGetSourcei(source, AL_SOURCE_STATE, &state);
683 } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING && loops < MaxTransitions);
685 /* All done. Delete resources, and close down SDL_sound and OpenAL. */
686 alDeleteSources(1, &source);
687 alDeleteAuxiliaryEffectSlots(2, slots);
688 alDeleteEffects(2, effects);
689 alDeleteFilters(1, &direct_filter);
690 alDeleteBuffers(1, &buffer);
692 Sound_Quit();
693 CloseAL();
695 return 0;