Recogmize jack64 for finding the JACK library name
[openal-soft.git] / examples / almultireverb.c
blobf9a46c4f0e8af103bbca99c1e9f402b1e1415bd4
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.
33 #include <assert.h>
34 #include <inttypes.h>
35 #include <limits.h>
36 #include <math.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
41 #include "sndfile.h"
43 #include "AL/al.h"
44 #include "AL/alc.h"
45 #include "AL/efx.h"
46 #include "AL/efx-presets.h"
48 #include "common/alhelpers.h"
50 #include "win_main_utf8.h"
53 #ifndef M_PI
54 #define M_PI 3.14159265358979323846
55 #endif
58 /* Filter object functions */
59 static LPALGENFILTERS alGenFilters;
60 static LPALDELETEFILTERS alDeleteFilters;
61 static LPALISFILTER alIsFilter;
62 static LPALFILTERI alFilteri;
63 static LPALFILTERIV alFilteriv;
64 static LPALFILTERF alFilterf;
65 static LPALFILTERFV alFilterfv;
66 static LPALGETFILTERI alGetFilteri;
67 static LPALGETFILTERIV alGetFilteriv;
68 static LPALGETFILTERF alGetFilterf;
69 static LPALGETFILTERFV alGetFilterfv;
71 /* Effect object functions */
72 static LPALGENEFFECTS alGenEffects;
73 static LPALDELETEEFFECTS alDeleteEffects;
74 static LPALISEFFECT alIsEffect;
75 static LPALEFFECTI alEffecti;
76 static LPALEFFECTIV alEffectiv;
77 static LPALEFFECTF alEffectf;
78 static LPALEFFECTFV alEffectfv;
79 static LPALGETEFFECTI alGetEffecti;
80 static LPALGETEFFECTIV alGetEffectiv;
81 static LPALGETEFFECTF alGetEffectf;
82 static LPALGETEFFECTFV alGetEffectfv;
84 /* Auxiliary Effect Slot object functions */
85 static LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots;
86 static LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots;
87 static LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot;
88 static LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti;
89 static LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv;
90 static LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf;
91 static LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv;
92 static LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti;
93 static LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv;
94 static LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf;
95 static LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv;
98 /* LoadEffect loads the given initial reverb properties into the given OpenAL
99 * effect object, and returns non-zero on success.
101 static int LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES *reverb)
103 ALenum err;
105 alGetError();
107 /* Prepare the effect for EAX Reverb (standard reverb doesn't contain
108 * the needed panning vectors).
110 alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB);
111 err = alGetError();
112 if(err != AL_NO_ERROR)
114 fprintf(stderr, "Failed to set EAX Reverb: %s (0x%04x)\n", alGetString(err), err);
115 return 0;
118 /* Load the reverb properties. */
119 alEffectf(effect, AL_EAXREVERB_DENSITY, reverb->flDensity);
120 alEffectf(effect, AL_EAXREVERB_DIFFUSION, reverb->flDiffusion);
121 alEffectf(effect, AL_EAXREVERB_GAIN, reverb->flGain);
122 alEffectf(effect, AL_EAXREVERB_GAINHF, reverb->flGainHF);
123 alEffectf(effect, AL_EAXREVERB_GAINLF, reverb->flGainLF);
124 alEffectf(effect, AL_EAXREVERB_DECAY_TIME, reverb->flDecayTime);
125 alEffectf(effect, AL_EAXREVERB_DECAY_HFRATIO, reverb->flDecayHFRatio);
126 alEffectf(effect, AL_EAXREVERB_DECAY_LFRATIO, reverb->flDecayLFRatio);
127 alEffectf(effect, AL_EAXREVERB_REFLECTIONS_GAIN, reverb->flReflectionsGain);
128 alEffectf(effect, AL_EAXREVERB_REFLECTIONS_DELAY, reverb->flReflectionsDelay);
129 alEffectfv(effect, AL_EAXREVERB_REFLECTIONS_PAN, reverb->flReflectionsPan);
130 alEffectf(effect, AL_EAXREVERB_LATE_REVERB_GAIN, reverb->flLateReverbGain);
131 alEffectf(effect, AL_EAXREVERB_LATE_REVERB_DELAY, reverb->flLateReverbDelay);
132 alEffectfv(effect, AL_EAXREVERB_LATE_REVERB_PAN, reverb->flLateReverbPan);
133 alEffectf(effect, AL_EAXREVERB_ECHO_TIME, reverb->flEchoTime);
134 alEffectf(effect, AL_EAXREVERB_ECHO_DEPTH, reverb->flEchoDepth);
135 alEffectf(effect, AL_EAXREVERB_MODULATION_TIME, reverb->flModulationTime);
136 alEffectf(effect, AL_EAXREVERB_MODULATION_DEPTH, reverb->flModulationDepth);
137 alEffectf(effect, AL_EAXREVERB_AIR_ABSORPTION_GAINHF, reverb->flAirAbsorptionGainHF);
138 alEffectf(effect, AL_EAXREVERB_HFREFERENCE, reverb->flHFReference);
139 alEffectf(effect, AL_EAXREVERB_LFREFERENCE, reverb->flLFReference);
140 alEffectf(effect, AL_EAXREVERB_ROOM_ROLLOFF_FACTOR, reverb->flRoomRolloffFactor);
141 alEffecti(effect, AL_EAXREVERB_DECAY_HFLIMIT, reverb->iDecayHFLimit);
143 /* Check if an error occurred, and return failure if so. */
144 err = alGetError();
145 if(err != AL_NO_ERROR)
147 fprintf(stderr, "Error setting up reverb: %s\n", alGetString(err));
148 return 0;
151 return 1;
155 /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
156 * returns the new buffer ID.
158 static ALuint LoadSound(const char *filename)
160 ALenum err, format;
161 ALuint buffer;
162 SNDFILE *sndfile;
163 SF_INFO sfinfo;
164 short *membuf;
165 sf_count_t num_frames;
166 ALsizei num_bytes;
168 /* Open the audio file and check that it's usable. */
169 sndfile = sf_open(filename, SFM_READ, &sfinfo);
170 if(!sndfile)
172 fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
173 return 0;
175 if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(short))/sfinfo.channels)
177 fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
178 sf_close(sndfile);
179 return 0;
182 /* Get the sound format, and figure out the OpenAL format */
183 if(sfinfo.channels == 1)
184 format = AL_FORMAT_MONO16;
185 else if(sfinfo.channels == 2)
186 format = AL_FORMAT_STEREO16;
187 else
189 fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
190 sf_close(sndfile);
191 return 0;
194 /* Decode the whole audio file to a buffer. */
195 membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short));
197 num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames);
198 if(num_frames < 1)
200 free(membuf);
201 sf_close(sndfile);
202 fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
203 return 0;
205 num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short);
207 /* Buffer the audio data into a new buffer object, then free the data and
208 * close the file.
210 buffer = 0;
211 alGenBuffers(1, &buffer);
212 alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
214 free(membuf);
215 sf_close(sndfile);
217 /* Check if an error occurred, and clean up if so. */
218 err = alGetError();
219 if(err != AL_NO_ERROR)
221 fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
222 if(buffer && alIsBuffer(buffer))
223 alDeleteBuffers(1, &buffer);
224 return 0;
227 return buffer;
231 /* Helper to calculate the dot-product of the two given vectors. */
232 static ALfloat dot_product(const ALfloat vec0[3], const ALfloat vec1[3])
234 return vec0[0]*vec1[0] + vec0[1]*vec1[1] + vec0[2]*vec1[2];
237 /* Helper to normalize a given vector. */
238 static void normalize(ALfloat vec[3])
240 ALfloat mag = sqrtf(dot_product(vec, vec));
241 if(mag > 0.00001f)
243 vec[0] /= mag;
244 vec[1] /= mag;
245 vec[2] /= mag;
247 else
249 vec[0] = 0.0f;
250 vec[1] = 0.0f;
251 vec[2] = 0.0f;
256 /* The main update function to update the listener and environment effects. */
257 static void UpdateListenerAndEffects(float timediff, const ALuint slots[2], const ALuint effects[2], const EFXEAXREVERBPROPERTIES reverbs[2])
259 static const ALfloat listener_move_scale = 10.0f;
260 /* Individual reverb zones are connected via "portals". Each portal has a
261 * position (center point of the connecting area), a normal (facing
262 * direction), and a radius (approximate size of the connecting area).
264 const ALfloat portal_pos[3] = { 0.0f, 0.0f, 0.0f };
265 const ALfloat portal_norm[3] = { sqrtf(0.5f), 0.0f, -sqrtf(0.5f) };
266 const ALfloat portal_radius = 2.5f;
267 ALfloat other_dir[3], this_dir[3];
268 ALfloat listener_pos[3];
269 ALfloat local_norm[3];
270 ALfloat local_dir[3];
271 ALfloat near_edge[3];
272 ALfloat far_edge[3];
273 ALfloat dist, edist;
275 /* Update the listener position for the amount of time passed. This uses a
276 * simple triangular LFO to offset the position (moves along the X axis
277 * between -listener_move_scale and +listener_move_scale for each
278 * transition).
280 listener_pos[0] = (fabsf(2.0f - timediff/2.0f) - 1.0f) * listener_move_scale;
281 listener_pos[1] = 0.0f;
282 listener_pos[2] = 0.0f;
283 alListenerfv(AL_POSITION, listener_pos);
285 /* Calculate local_dir, which represents the listener-relative point to the
286 * adjacent zone (should also include orientation). Because EAX Reverb uses
287 * left-handed coordinates instead of right-handed like the rest of OpenAL,
288 * negate Z for the local values.
290 local_dir[0] = portal_pos[0] - listener_pos[0];
291 local_dir[1] = portal_pos[1] - listener_pos[1];
292 local_dir[2] = -(portal_pos[2] - listener_pos[2]);
293 /* A normal application would also rotate the portal's normal given the
294 * listener orientation, to get the listener-relative normal.
296 local_norm[0] = portal_norm[0];
297 local_norm[1] = portal_norm[1];
298 local_norm[2] = -portal_norm[2];
300 /* Calculate the distance from the listener to the portal, and ensure it's
301 * far enough away to not suffer severe floating-point precision issues.
303 dist = sqrtf(dot_product(local_dir, local_dir));
304 if(dist > 0.00001f)
306 const EFXEAXREVERBPROPERTIES *other_reverb, *this_reverb;
307 ALuint other_effect, this_effect;
308 ALfloat magnitude, dir_dot_norm;
310 /* Normalize the direction to the portal. */
311 local_dir[0] /= dist;
312 local_dir[1] /= dist;
313 local_dir[2] /= dist;
315 /* Calculate the dot product of the portal's local direction and local
316 * normal, which is used for angular and side checks later on.
318 dir_dot_norm = dot_product(local_dir, local_norm);
320 /* Figure out which zone we're in. */
321 if(dir_dot_norm <= 0.0f)
323 /* We're in front of the portal, so we're in Zone 0. */
324 this_effect = effects[0];
325 other_effect = effects[1];
326 this_reverb = &reverbs[0];
327 other_reverb = &reverbs[1];
329 else
331 /* We're behind the portal, so we're in Zone 1. */
332 this_effect = effects[1];
333 other_effect = effects[0];
334 this_reverb = &reverbs[1];
335 other_reverb = &reverbs[0];
338 /* Calculate the listener-relative extents of the portal. */
339 /* First, project the listener-to-portal vector onto the portal's plane
340 * to get the portal-relative direction along the plane that goes away
341 * from the listener (toward the farthest edge of the portal).
343 far_edge[0] = local_dir[0] - local_norm[0]*dir_dot_norm;
344 far_edge[1] = local_dir[1] - local_norm[1]*dir_dot_norm;
345 far_edge[2] = local_dir[2] - local_norm[2]*dir_dot_norm;
347 edist = sqrtf(dot_product(far_edge, far_edge));
348 if(edist > 0.0001f)
350 /* Rescale the portal-relative vector to be at the radius edge. */
351 ALfloat mag = portal_radius / edist;
352 far_edge[0] *= mag;
353 far_edge[1] *= mag;
354 far_edge[2] *= mag;
356 /* Calculate the closest edge of the portal by negating the
357 * farthest, and add an offset to make them both relative to the
358 * listener.
360 near_edge[0] = local_dir[0]*dist - far_edge[0];
361 near_edge[1] = local_dir[1]*dist - far_edge[1];
362 near_edge[2] = local_dir[2]*dist - far_edge[2];
363 far_edge[0] += local_dir[0]*dist;
364 far_edge[1] += local_dir[1]*dist;
365 far_edge[2] += local_dir[2]*dist;
367 /* Normalize the listener-relative extents of the portal, then
368 * calculate the panning magnitude for the other zone given the
369 * apparent size of the opening. The panning magnitude affects the
370 * envelopment of the environment, with 1 being a point, 0.5 being
371 * half coverage around the listener, and 0 being full coverage.
373 normalize(far_edge);
374 normalize(near_edge);
375 magnitude = 1.0f - acosf(dot_product(far_edge, near_edge))/(float)(M_PI*2.0);
377 /* Recalculate the panning direction, to be directly between the
378 * direction of the two extents.
380 local_dir[0] = far_edge[0] + near_edge[0];
381 local_dir[1] = far_edge[1] + near_edge[1];
382 local_dir[2] = far_edge[2] + near_edge[2];
383 normalize(local_dir);
385 else
387 /* If we get here, the listener is directly in front of or behind
388 * the center of the portal, making all aperture edges effectively
389 * equidistant. Calculating the panning magnitude is simplified,
390 * using the arctangent of the radius and distance.
392 magnitude = 1.0f - (atan2f(portal_radius, dist) / (float)M_PI);
395 /* Scale the other zone's panning vector. */
396 other_dir[0] = local_dir[0] * magnitude;
397 other_dir[1] = local_dir[1] * magnitude;
398 other_dir[2] = local_dir[2] * magnitude;
399 /* Pan the current zone to the opposite direction of the portal, and
400 * take the remaining percentage of the portal's magnitude.
402 this_dir[0] = local_dir[0] * (magnitude-1.0f);
403 this_dir[1] = local_dir[1] * (magnitude-1.0f);
404 this_dir[2] = local_dir[2] * (magnitude-1.0f);
406 /* Now set the effects' panning vectors and gain. Energy is shared
407 * between environments, so attenuate according to each zone's
408 * contribution (note: gain^2 = energy).
410 alEffectf(this_effect, AL_EAXREVERB_REFLECTIONS_GAIN, this_reverb->flReflectionsGain * sqrtf(magnitude));
411 alEffectf(this_effect, AL_EAXREVERB_LATE_REVERB_GAIN, this_reverb->flLateReverbGain * sqrtf(magnitude));
412 alEffectfv(this_effect, AL_EAXREVERB_REFLECTIONS_PAN, this_dir);
413 alEffectfv(this_effect, AL_EAXREVERB_LATE_REVERB_PAN, this_dir);
415 alEffectf(other_effect, AL_EAXREVERB_REFLECTIONS_GAIN, other_reverb->flReflectionsGain * sqrtf(1.0f-magnitude));
416 alEffectf(other_effect, AL_EAXREVERB_LATE_REVERB_GAIN, other_reverb->flLateReverbGain * sqrtf(1.0f-magnitude));
417 alEffectfv(other_effect, AL_EAXREVERB_REFLECTIONS_PAN, other_dir);
418 alEffectfv(other_effect, AL_EAXREVERB_LATE_REVERB_PAN, other_dir);
420 else
422 /* We're practically in the center of the portal. Give the panning
423 * vectors a 50/50 split, with Zone 0 covering the half in front of
424 * the normal, and Zone 1 covering the half behind.
426 this_dir[0] = local_norm[0] / 2.0f;
427 this_dir[1] = local_norm[1] / 2.0f;
428 this_dir[2] = local_norm[2] / 2.0f;
430 other_dir[0] = local_norm[0] / -2.0f;
431 other_dir[1] = local_norm[1] / -2.0f;
432 other_dir[2] = local_norm[2] / -2.0f;
434 alEffectf(effects[0], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[0].flReflectionsGain * sqrtf(0.5f));
435 alEffectf(effects[0], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[0].flLateReverbGain * sqrtf(0.5f));
436 alEffectfv(effects[0], AL_EAXREVERB_REFLECTIONS_PAN, this_dir);
437 alEffectfv(effects[0], AL_EAXREVERB_LATE_REVERB_PAN, this_dir);
439 alEffectf(effects[1], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[1].flReflectionsGain * sqrtf(0.5f));
440 alEffectf(effects[1], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[1].flLateReverbGain * sqrtf(0.5f));
441 alEffectfv(effects[1], AL_EAXREVERB_REFLECTIONS_PAN, other_dir);
442 alEffectfv(effects[1], AL_EAXREVERB_LATE_REVERB_PAN, other_dir);
445 /* Finally, update the effect slots with the updated effect parameters. */
446 alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]);
447 alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]);
451 int main(int argc, char **argv)
453 static const int MaxTransitions = 8;
454 EFXEAXREVERBPROPERTIES reverbs[2] = {
455 EFX_REVERB_PRESET_CARPETEDHALLWAY,
456 EFX_REVERB_PRESET_BATHROOM
458 ALCdevice *device = NULL;
459 ALCcontext *context = NULL;
460 ALuint effects[2] = { 0, 0 };
461 ALuint slots[2] = { 0, 0 };
462 ALuint direct_filter = 0;
463 ALuint buffer = 0;
464 ALuint source = 0;
465 ALCint num_sends = 0;
466 ALenum state = AL_INITIAL;
467 ALfloat direct_gain = 1.0f;
468 int basetime = 0;
469 int loops = 0;
471 /* Print out usage if no arguments were specified */
472 if(argc < 2)
474 fprintf(stderr, "Usage: %s [-device <name>] [options] <filename>\n\n"
475 "Options:\n"
476 "\t-nodirect\tSilence direct path output (easier to hear reverb)\n\n",
477 argv[0]);
478 return 1;
481 /* Initialize OpenAL, and check for EFX support with at least 2 auxiliary
482 * sends (if multiple sends are supported, 2 are provided by default; if
483 * you want more, you have to request it through alcCreateContext).
485 argv++; argc--;
486 if(InitAL(&argv, &argc) != 0)
487 return 1;
489 while(argc > 0)
491 if(strcmp(argv[0], "-nodirect") == 0)
492 direct_gain = 0.0f;
493 else
494 break;
495 argv++;
496 argc--;
498 if(argc < 1)
500 fprintf(stderr, "No filename specified.\n");
501 CloseAL();
502 return 1;
505 context = alcGetCurrentContext();
506 device = alcGetContextsDevice(context);
508 if(!alcIsExtensionPresent(device, "ALC_EXT_EFX"))
510 fprintf(stderr, "Error: EFX not supported\n");
511 CloseAL();
512 return 1;
515 num_sends = 0;
516 alcGetIntegerv(device, ALC_MAX_AUXILIARY_SENDS, 1, &num_sends);
517 if(alcGetError(device) != ALC_NO_ERROR || num_sends < 2)
519 fprintf(stderr, "Error: Device does not support multiple sends (got %d, need 2)\n",
520 num_sends);
521 CloseAL();
522 return 1;
525 /* Define a macro to help load the function pointers. */
526 #define LOAD_PROC(T, x) ((x) = FUNCTION_CAST(T, alGetProcAddress(#x)))
527 LOAD_PROC(LPALGENFILTERS, alGenFilters);
528 LOAD_PROC(LPALDELETEFILTERS, alDeleteFilters);
529 LOAD_PROC(LPALISFILTER, alIsFilter);
530 LOAD_PROC(LPALFILTERI, alFilteri);
531 LOAD_PROC(LPALFILTERIV, alFilteriv);
532 LOAD_PROC(LPALFILTERF, alFilterf);
533 LOAD_PROC(LPALFILTERFV, alFilterfv);
534 LOAD_PROC(LPALGETFILTERI, alGetFilteri);
535 LOAD_PROC(LPALGETFILTERIV, alGetFilteriv);
536 LOAD_PROC(LPALGETFILTERF, alGetFilterf);
537 LOAD_PROC(LPALGETFILTERFV, alGetFilterfv);
539 LOAD_PROC(LPALGENEFFECTS, alGenEffects);
540 LOAD_PROC(LPALDELETEEFFECTS, alDeleteEffects);
541 LOAD_PROC(LPALISEFFECT, alIsEffect);
542 LOAD_PROC(LPALEFFECTI, alEffecti);
543 LOAD_PROC(LPALEFFECTIV, alEffectiv);
544 LOAD_PROC(LPALEFFECTF, alEffectf);
545 LOAD_PROC(LPALEFFECTFV, alEffectfv);
546 LOAD_PROC(LPALGETEFFECTI, alGetEffecti);
547 LOAD_PROC(LPALGETEFFECTIV, alGetEffectiv);
548 LOAD_PROC(LPALGETEFFECTF, alGetEffectf);
549 LOAD_PROC(LPALGETEFFECTFV, alGetEffectfv);
551 LOAD_PROC(LPALGENAUXILIARYEFFECTSLOTS, alGenAuxiliaryEffectSlots);
552 LOAD_PROC(LPALDELETEAUXILIARYEFFECTSLOTS, alDeleteAuxiliaryEffectSlots);
553 LOAD_PROC(LPALISAUXILIARYEFFECTSLOT, alIsAuxiliaryEffectSlot);
554 LOAD_PROC(LPALAUXILIARYEFFECTSLOTI, alAuxiliaryEffectSloti);
555 LOAD_PROC(LPALAUXILIARYEFFECTSLOTIV, alAuxiliaryEffectSlotiv);
556 LOAD_PROC(LPALAUXILIARYEFFECTSLOTF, alAuxiliaryEffectSlotf);
557 LOAD_PROC(LPALAUXILIARYEFFECTSLOTFV, alAuxiliaryEffectSlotfv);
558 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTI, alGetAuxiliaryEffectSloti);
559 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTIV, alGetAuxiliaryEffectSlotiv);
560 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTF, alGetAuxiliaryEffectSlotf);
561 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTFV, alGetAuxiliaryEffectSlotfv);
562 #undef LOAD_PROC
564 /* Load the sound into a buffer. */
565 buffer = LoadSound(argv[0]);
566 if(!buffer)
568 CloseAL();
569 return 1;
572 /* Generate two effects for two "zones", and load a reverb into each one.
573 * Note that unlike single-zone reverb, where you can store one effect per
574 * preset, for multi-zone reverb you should have one effect per environment
575 * instance, or one per audible zone. This is because we'll be changing the
576 * effects' properties in real-time based on the environment instance
577 * relative to the listener.
579 alGenEffects(2, effects);
580 if(!LoadEffect(effects[0], &reverbs[0]) || !LoadEffect(effects[1], &reverbs[1]))
582 alDeleteEffects(2, effects);
583 alDeleteBuffers(1, &buffer);
584 CloseAL();
585 return 1;
588 /* Create the effect slot objects, one for each "active" effect. */
589 alGenAuxiliaryEffectSlots(2, slots);
591 /* Tell the effect slots to use the loaded effect objects, with slot 0 for
592 * Zone 0 and slot 1 for Zone 1. Note that this effectively copies the
593 * effect properties. Modifying or deleting the effect object afterward
594 * won't directly affect the effect slot until they're reapplied like this.
596 alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]);
597 alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]);
598 assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot");
600 /* For the purposes of this example, prepare a filter that optionally
601 * silences the direct path which allows us to hear just the reverberation.
602 * A filter like this is normally used for obstruction, where the path
603 * directly between the listener and source is blocked (the exact
604 * properties depending on the type and thickness of the obstructing
605 * material).
607 alGenFilters(1, &direct_filter);
608 alFilteri(direct_filter, AL_FILTER_TYPE, AL_FILTER_LOWPASS);
609 alFilterf(direct_filter, AL_LOWPASS_GAIN, direct_gain);
610 assert(alGetError()==AL_NO_ERROR && "Failed to set direct filter");
612 /* Create the source to play the sound with, place it in front of the
613 * listener's path in the left zone.
615 source = 0;
616 alGenSources(1, &source);
617 alSourcei(source, AL_LOOPING, AL_TRUE);
618 alSource3f(source, AL_POSITION, -5.0f, 0.0f, -2.0f);
619 alSourcei(source, AL_DIRECT_FILTER, (ALint)direct_filter);
620 alSourcei(source, AL_BUFFER, (ALint)buffer);
622 /* Connect the source to the effect slots. Here, we connect source send 0
623 * to Zone 0's slot, and send 1 to Zone 1's slot. Filters can be specified
624 * to occlude the source from each zone by varying amounts; for example, a
625 * source within a particular zone would be unfiltered, while a source that
626 * can only see a zone through a window or thin wall may be attenuated for
627 * that zone.
629 alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[0], 0, AL_FILTER_NULL);
630 alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[1], 1, AL_FILTER_NULL);
631 assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
633 /* Get the current time as the base for timing in the main loop. */
634 basetime = altime_get();
635 loops = 0;
636 printf("Transition %d of %d...\n", loops+1, MaxTransitions);
638 /* Play the sound for a while. */
639 alSourcePlay(source);
640 do {
641 int curtime;
642 ALfloat timediff;
644 /* Start a batch update, to ensure all changes apply simultaneously. */
645 alcSuspendContext(context);
647 /* Get the current time to track the amount of time that passed.
648 * Convert the difference to seconds.
650 curtime = altime_get();
651 timediff = (float)(curtime - basetime) / 1000.0f;
653 /* Avoid negative time deltas, in case of non-monotonic clocks. */
654 if(timediff < 0.0f)
655 timediff = 0.0f;
656 else while(timediff >= 4.0f*(float)((loops&1)+1))
658 /* For this example, each transition occurs over 4 seconds, and
659 * there's 2 transitions per cycle.
661 if(++loops < MaxTransitions)
662 printf("Transition %d of %d...\n", loops+1, MaxTransitions);
663 if(!(loops&1))
665 /* Cycle completed. Decrease the delta and increase the base
666 * time to start a new cycle.
668 timediff -= 8.0f;
669 basetime += 8000;
673 /* Update the listener and effects, and finish the batch. */
674 UpdateListenerAndEffects(timediff, slots, effects, reverbs);
675 alcProcessContext(context);
677 al_nssleep(10000000);
679 alGetSourcei(source, AL_SOURCE_STATE, &state);
680 } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING && loops < MaxTransitions);
682 /* All done. Delete resources, and close down OpenAL. */
683 alDeleteSources(1, &source);
684 alDeleteAuxiliaryEffectSlots(2, slots);
685 alDeleteEffects(2, effects);
686 alDeleteFilters(1, &direct_filter);
687 alDeleteBuffers(1, &buffer);
689 CloseAL();
691 return 0;