]> icculus.org git repositories - divverent/darkplaces.git/blob - snd_dma.c
added cl_beams_* cvars to effects options menu
[divverent/darkplaces.git] / snd_dma.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // snd_dma.c -- main control for any streaming sound output device
21
22 #include "quakedef.h"
23
24 #ifdef USE_DSOUND
25 #include <windows.h>
26 #include <dsound.h>
27 extern DWORD gSndBufSize;
28 extern LPDIRECTSOUND pDS;
29 extern LPDIRECTSOUNDBUFFER pDSBuf;
30 #endif
31
32 #include "snd_ogg.h"
33
34
35 void S_Play(void);
36 void S_PlayVol(void);
37 void S_Play2(void);
38 void S_SoundList(void);
39 void S_Update_();
40 void S_StopAllSounds(qboolean clear);
41 void S_StopAllSoundsC(void);
42
43 void S_ClearBuffer (void);
44
45
46 // =======================================================================
47 // Internal sound data & structures
48 // =======================================================================
49
50 channel_t channels[MAX_CHANNELS];
51 unsigned int total_channels;
52
53 int snd_blocked = 0;
54 cvar_t snd_initialized = { CVAR_READONLY, "snd_initialized", "0"};
55 cvar_t snd_streaming = { CVAR_SAVE, "snd_streaming", "1"};
56
57 // pointer should go away
58 volatile dma_t *shm = 0;
59 volatile dma_t sn;
60
61 vec3_t listener_origin;
62 matrix4x4_t listener_matrix;
63 vec_t sound_nominal_clip_dist=1000.0;
64 mempool_t *snd_mempool;
65
66 // sample PAIRS
67 int soundtime;
68 int paintedtime;
69
70
71 //LordHavoc: increased the client sound limit from 512 to 4096 for the Nehahra movie
72 #define MAX_SFX 4096
73 sfx_t *known_sfx; // allocated [MAX_SFX]
74 int num_sfx;
75
76 sfx_t *ambient_sfx[NUM_AMBIENTS];
77
78 int sound_started = 0;
79
80 cvar_t bgmvolume = {CVAR_SAVE, "bgmvolume", "1"};
81 cvar_t volume = {CVAR_SAVE, "volume", "0.7"};
82 cvar_t snd_staticvolume = {CVAR_SAVE, "snd_staticvolume", "1"};
83
84 cvar_t nosound = {0, "nosound", "0"};
85 cvar_t snd_precache = {0, "snd_precache", "1"};
86 cvar_t bgmbuffer = {0, "bgmbuffer", "4096"};
87 cvar_t ambient_level = {0, "ambient_level", "0.3"};
88 cvar_t ambient_fade = {0, "ambient_fade", "100"};
89 cvar_t snd_noextraupdate = {0, "snd_noextraupdate", "0"};
90 cvar_t snd_show = {0, "snd_show", "0"};
91 cvar_t _snd_mixahead = {CVAR_SAVE, "_snd_mixahead", "0.1"};
92 cvar_t snd_swapstereo = {CVAR_SAVE, "snd_swapstereo", "0"};
93
94
95 // ====================================================================
96 // User-setable variables
97 // ====================================================================
98
99
100 //
101 // Fake dma is a synchronous faking of the DMA progress used for
102 // isolating performance in the renderer.  The fakedma_updates is
103 // number of times S_Update() is called per second.
104 //
105
106 qboolean fakedma = false;
107 int fakedma_updates = 15;
108
109
110 void S_SoundInfo_f(void)
111 {
112         if (!sound_started || !shm)
113         {
114                 Con_Print("sound system not started\n");
115                 return;
116         }
117
118         Con_Printf("%5d stereo\n", shm->format.channels - 1);
119         Con_Printf("%5d samples\n", shm->samples);
120         Con_Printf("%5d samplepos\n", shm->samplepos);
121         Con_Printf("%5d samplebits\n", shm->format.width * 8);
122         Con_Printf("%5d speed\n", shm->format.speed);
123         Con_Printf("%p dma buffer\n", shm->buffer);
124         Con_Printf("%5u total_channels\n", total_channels);
125 }
126
127 void S_UnloadSounds(void)
128 {
129         int i;
130         for (i = 0;i < num_sfx;i++)
131                 S_UnloadSound(known_sfx + i);
132 }
133
134 void S_LoadSounds(void)
135 {
136         int i;
137         for (i = 0;i < num_sfx;i++)
138                 S_LoadSound(known_sfx + i, false);
139 }
140
141 void S_Startup(void)
142 {
143         if (!snd_initialized.integer)
144                 return;
145
146         shm = &sn;
147         memset((void *)shm, 0, sizeof(*shm));
148
149 // create a piece of DMA memory
150
151         if (fakedma)
152         {
153                 shm->format.width = 2;
154                 shm->format.speed = 22050;
155                 shm->format.channels = 2;
156                 shm->samples = 32768;
157                 shm->samplepos = 0;
158                 shm->buffer = Mem_Alloc(snd_mempool, shm->format.channels * shm->samples * shm->format.width);
159         }
160         else
161         {
162                 if (!SNDDMA_Init())
163                 {
164                         Con_Print("S_Startup: SNDDMA_Init failed.\n");
165                         sound_started = 0;
166                         shm = NULL;
167                         return;
168                 }
169         }
170
171         sound_started = 1;
172
173         Con_DPrintf("Sound sampling rate: %i\n", shm->format.speed);
174
175         //S_LoadSounds();
176
177         S_StopAllSounds(true);
178 }
179
180 void S_Shutdown(void)
181 {
182         if (!sound_started)
183                 return;
184
185         //S_UnloadSounds();
186
187         if (fakedma)
188                 Mem_Free(shm->buffer);
189         else
190                 SNDDMA_Shutdown();
191
192         shm = NULL;
193         sound_started = 0;
194 }
195
196 void S_Restart_f(void)
197 {
198         S_Shutdown();
199         S_Startup();
200 }
201
202 /*
203 ================
204 S_Init
205 ================
206 */
207 void S_Init(void)
208 {
209         Con_DPrint("\nSound Initialization\n");
210
211         Cvar_RegisterVariable(&volume);
212         Cvar_RegisterVariable(&bgmvolume);
213         Cvar_RegisterVariable(&snd_staticvolume);
214
215 // COMMANDLINEOPTION: Sound: -nosound disables sound (including CD audio)
216         if (COM_CheckParm("-nosound") || COM_CheckParm("-safe"))
217                 return;
218
219         snd_mempool = Mem_AllocPool("sound", 0, NULL);
220
221 // COMMANDLINEOPTION: Sound: -simsound runs sound mixing but with no output
222         if (COM_CheckParm("-simsound"))
223                 fakedma = true;
224
225         Cmd_AddCommand("play", S_Play);
226         Cmd_AddCommand("play2", S_Play2);
227         Cmd_AddCommand("playvol", S_PlayVol);
228         Cmd_AddCommand("stopsound", S_StopAllSoundsC);
229         Cmd_AddCommand("soundlist", S_SoundList);
230         Cmd_AddCommand("soundinfo", S_SoundInfo_f);
231         Cmd_AddCommand("snd_restart", S_Restart_f);
232
233         Cvar_RegisterVariable(&nosound);
234         Cvar_RegisterVariable(&snd_precache);
235         Cvar_RegisterVariable(&snd_initialized);
236         Cvar_RegisterVariable(&snd_streaming);
237         Cvar_RegisterVariable(&bgmbuffer);
238         Cvar_RegisterVariable(&ambient_level);
239         Cvar_RegisterVariable(&ambient_fade);
240         Cvar_RegisterVariable(&snd_noextraupdate);
241         Cvar_RegisterVariable(&snd_show);
242         Cvar_RegisterVariable(&_snd_mixahead);
243         Cvar_RegisterVariable(&snd_swapstereo); // LordHavoc: for people with backwards sound wiring
244
245         Cvar_SetValueQuick(&snd_initialized, true);
246
247         known_sfx = Mem_Alloc(snd_mempool, MAX_SFX*sizeof(sfx_t));
248         num_sfx = 0;
249
250         SND_InitScaletable ();
251
252         ambient_sfx[AMBIENT_WATER] = S_PrecacheSound ("ambience/water1.wav", false, true);
253         ambient_sfx[AMBIENT_SKY] = S_PrecacheSound ("ambience/wind2.wav", false, true);
254
255         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
256         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
257
258         OGG_OpenLibrary ();
259 }
260
261
262 // =======================================================================
263 // Load a sound
264 // =======================================================================
265
266 /*
267 =========
268 S_GetCached
269
270 =========
271 */
272 sfx_t *S_GetCached (const char *name, qboolean stdpath)
273 {
274         char namebuffer [MAX_QPATH];
275         size_t len;
276         int i;
277
278         if (!snd_initialized.integer)
279                 return NULL;
280
281         if (!name)
282                 Host_Error("S_GetCached: NULL");
283
284         // Add the default sound directory to the path
285         len = snprintf (namebuffer, sizeof (namebuffer), stdpath ? "sound/%s" : "%s", name);
286         if (len >= sizeof (namebuffer))
287                 Host_Error ("S_GetCached: sound name too long (%s)", name);
288
289         for(i = 0;i < num_sfx;i++)
290                 if(!strcmp(known_sfx[i].name, namebuffer))
291                         return &known_sfx[i];
292
293         return NULL;
294 }
295
296 /*
297 ==================
298 S_FindName
299
300 ==================
301 */
302 sfx_t *S_FindName (const char *name, qboolean stdpath)
303 {
304         sfx_t *sfx;
305
306         if (!snd_initialized.integer)
307                 return NULL;
308
309         sfx = S_GetCached (name, stdpath);
310
311         // If we haven't allocated a sfx_t struct for it yet
312         if (sfx == NULL)
313         {
314                 if (num_sfx == MAX_SFX)
315                         Sys_Error ("S_FindName: out of sfx_t");
316
317                 sfx = &known_sfx[num_sfx++];
318                 memset (sfx, 0, sizeof(*sfx));
319                 snprintf (sfx->name, sizeof (sfx->name), stdpath ? "sound/%s" : "%s", name);
320         }
321         return sfx;
322 }
323
324
325 /*
326 ==================
327 S_TouchSound
328
329 ==================
330 */
331 void S_TouchSound (const char *name, qboolean stdpath)
332 {
333         sfx_t *sfx;
334
335         sfx = S_FindName (name, stdpath);
336
337         // Set the "used" flag for this sound
338         if (sfx != NULL)
339                 sfx->flags |= SFXFLAG_USED;
340 }
341
342
343 /*
344 ==================
345 S_ClearUsed
346
347 Reset the "used" flag of all precached sounds
348 ==================
349 */
350 void S_ClearUsed (void)
351 {
352         int i;
353
354         for (i = 0; i < num_sfx; i++)
355                 known_sfx[i].flags &= ~SFXFLAG_USED;
356 }
357
358
359 /*
360 ==================
361 S_PurgeUnused
362
363 Free all precached sounds without the "used" flag
364 ==================
365 */
366 void S_PurgeUnused (void)
367 {
368         int i;
369         sfx_t *sfx;
370
371         for (i = 0; i < num_sfx; i++)
372         {
373                 sfx = &known_sfx[i];
374                 if (! (sfx->flags & SFXFLAG_USED))
375                         S_UnloadSound (sfx);
376         }
377 }
378
379
380 /*
381 ==================
382 S_PrecacheSound
383
384 ==================
385 */
386 sfx_t *S_PrecacheSound (const char *name, qboolean complain, qboolean stdpath)
387 {
388         sfx_t *sfx;
389
390         if (!snd_initialized.integer)
391                 return NULL;
392
393         sfx = S_FindName (name, stdpath);
394
395         if (!nosound.integer && snd_precache.integer)
396                 S_LoadSound(sfx, complain);
397
398         return sfx;
399 }
400
401
402 //=============================================================================
403
404 /*
405 =================
406 SND_PickChannel
407
408 Picks a channel based on priorities, empty slots, number of channels
409 =================
410 */
411 channel_t *SND_PickChannel(int entnum, int entchannel)
412 {
413         int ch_idx;
414         int first_to_die;
415         int life_left;
416         channel_t* ch;
417
418 // Check for replacement sound, or find the best one to replace
419         first_to_die = -1;
420         life_left = 0x7fffffff;
421         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
422         {
423                 ch = &channels[ch_idx];
424                 if (entchannel != 0             // channel 0 never overrides
425                 && ch->entnum == entnum
426                 && (ch->entchannel == entchannel || entchannel == -1) )
427                 {       // always override sound from same entity
428                         first_to_die = ch_idx;
429                         break;
430                 }
431
432                 // don't let monster sounds override player sounds
433                 if (ch->entnum == cl.viewentity && entnum != cl.viewentity && ch->sfx)
434                         continue;
435
436                 // don't override looped sounds
437                 if ((ch->flags & CHANNELFLAG_FORCELOOP) != 0 ||
438                         (ch->sfx != NULL && ch->sfx->loopstart >= 0))
439                         continue;
440
441                 if (ch->end - paintedtime < life_left)
442                 {
443                         life_left = ch->end - paintedtime;
444                         first_to_die = ch_idx;
445                 }
446         }
447
448         if (first_to_die == -1)
449                 return NULL;
450
451         if (channels[first_to_die].sfx)
452                 channels[first_to_die].sfx = NULL;
453
454         return &channels[first_to_die];
455 }
456
457 /*
458 =================
459 SND_Spatialize
460
461 Spatializes a channel
462 =================
463 */
464 void SND_Spatialize(channel_t *ch, int isstatic)
465 {
466         vec_t dist, scale, pan;
467         vec3_t source_vec;
468
469         // anything coming from the view entity will always be full volume
470         // LordHavoc: make sounds with ATTN_NONE have no spatialization
471         if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
472         {
473                 ch->leftvol = ch->master_vol;
474                 ch->rightvol = ch->master_vol;
475         }
476         else
477         {
478                 // update sound origin if we know about the entity
479                 if (ch->entnum > 0 && cls.state == ca_connected && cl_entities[ch->entnum].state_current.active)
480                 {
481                         //Con_Printf("-- entnum %i origin %f %f %f neworigin %f %f %f\n", ch->entnum, ch->origin[0], ch->origin[1], ch->origin[2], cl_entities[ch->entnum].state_current.origin[0], cl_entities[ch->entnum].state_current.origin[1], cl_entities[ch->entnum].state_current.origin[2]);
482                         VectorCopy(cl_entities[ch->entnum].state_current.origin, ch->origin);
483                         if (cl_entities[ch->entnum].state_current.modelindex && cl.model_precache[cl_entities[ch->entnum].state_current.modelindex]->soundfromcenter)
484                                 VectorMAMAM(1.0f, ch->origin, 0.5f, cl.model_precache[cl_entities[ch->entnum].state_current.modelindex]->normalmins, 0.5f, cl.model_precache[cl_entities[ch->entnum].state_current.modelindex]->normalmaxs, ch->origin);
485                 }
486
487                 // calculate stereo seperation and distance attenuation
488                 Matrix4x4_Transform(&listener_matrix, ch->origin, source_vec);
489                 dist = VectorNormalizeLength(source_vec);
490                 // distance
491                 scale = ch->master_vol * (1.0 - (dist * ch->dist_mult));
492                 // panning
493                 pan = scale * source_vec[1];
494                 // calculate the volumes
495                 ch->leftvol = (int) (scale + pan);
496                 ch->rightvol = (int) (scale - pan);
497         }
498
499         // LordHavoc: allow adjusting volume of static sounds
500         if (isstatic)
501         {
502                 ch->leftvol *= snd_staticvolume.value;
503                 ch->rightvol *= snd_staticvolume.value;
504         }
505
506         // clamp volumes
507         ch->leftvol = bound(0, ch->leftvol, 255);
508         ch->rightvol = bound(0, ch->rightvol, 255);
509 }
510
511
512 // =======================================================================
513 // Start a sound effect
514 // =======================================================================
515
516 int S_StartSound(int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
517 {
518         channel_t *target_chan, *check;
519         int             vol;
520         int             ch_idx;
521         size_t  skip;
522
523         if (!sound_started || !sfx || !sfx->fetcher || nosound.integer)
524                 return -1;
525
526         vol = fvol*255;
527
528 // pick a channel to play on
529         target_chan = SND_PickChannel(entnum, entchannel);
530         if (!target_chan)
531                 return -1;
532
533 // spatialize
534         memset (target_chan, 0, sizeof(*target_chan));
535         VectorCopy(origin, target_chan->origin);
536         target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
537         target_chan->master_vol = vol;
538         target_chan->entnum = entnum;
539         target_chan->entchannel = entchannel;
540         SND_Spatialize(target_chan, false);
541
542         // LordHavoc: spawn the sound anyway because the player might teleport to it
543         //if (!target_chan->leftvol && !target_chan->rightvol)
544         //      return;         // not audible at all
545
546         // new channel
547         if (!S_LoadSound (sfx, true))
548         {
549                 target_chan->sfx = NULL;
550                 return -1;              // couldn't load the sound's data
551         }
552
553         target_chan->sfx = sfx;
554         target_chan->flags = CHANNELFLAG_NONE;
555         target_chan->pos = 0.0;
556         target_chan->end = paintedtime + sfx->total_length;
557         target_chan->lastptime = paintedtime;
558
559 // if an identical sound has also been started this frame, offset the pos
560 // a bit to keep it from just making the first one louder
561         check = &channels[NUM_AMBIENTS];
562         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
563         {
564                 if (check == target_chan)
565                         continue;
566                 if (check->sfx == sfx && !check->pos)
567                 {
568                         // LordHavoc: fixed skip calculations
569                         skip = 0.1 * sfx->format.speed;
570                         if (skip > sfx->total_length)
571                                 skip = sfx->total_length;
572                         if (skip > 0)
573                                 skip = rand() % skip;
574                         target_chan->pos += skip;
575                         target_chan->end -= skip;
576                         break;
577                 }
578         }
579
580         return (target_chan - channels);
581 }
582
583 void S_StopChannel (unsigned int channel_ind)
584 {
585         channel_t *ch;
586
587         if (channel_ind >= total_channels)
588                 return;
589
590         ch = &channels[channel_ind];
591         if (ch->sfx != NULL)
592         {
593                 if (ch->sfx->fetcher != NULL)
594                 {
595                         snd_fetcher_end_t fetcher_end = ch->sfx->fetcher->end;
596                         if (fetcher_end != NULL)
597                                 fetcher_end (ch);
598                 }
599                 ch->sfx = NULL;
600         }
601         ch->end = 0;
602 }
603
604 void S_PauseChannel (unsigned int channel_ind, qboolean toggle)
605 {
606         if (toggle)
607                 channels[channel_ind].flags |= CHANNELFLAG_PAUSED;
608         else
609                 channels[channel_ind].flags &= ~CHANNELFLAG_PAUSED;
610 }
611
612 void S_LoopChannel (unsigned int channel_ind, qboolean toggle)
613 {
614         if (toggle)
615                 channels[channel_ind].flags |= CHANNELFLAG_FORCELOOP;
616         else
617                 channels[channel_ind].flags &= ~CHANNELFLAG_FORCELOOP;
618 }
619
620 void S_StopSound(int entnum, int entchannel)
621 {
622         unsigned int i;
623
624         for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
625                 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
626                 {
627                         S_StopChannel (i);
628                         return;
629                 }
630 }
631
632 void S_StopAllSounds(qboolean clear)
633 {
634         unsigned int i;
635
636         for (i = 0; i < total_channels; i++)
637                 S_StopChannel (i);
638
639         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
640         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
641
642         if (clear)
643                 S_ClearBuffer();
644 }
645
646 void S_StopAllSoundsC(void)
647 {
648         S_StopAllSounds(true);
649 }
650
651 void S_PauseGameSounds (void)
652 {
653         unsigned int i;
654
655         for (i = 0; i < total_channels; i++)
656         {
657                 channel_t *ch;
658
659                 ch = &channels[i];
660                 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
661                         ch->flags |= CHANNELFLAG_PAUSED;
662         }
663 }
664
665 void S_ResumeGameSounds (void)
666 {
667         unsigned int i;
668
669         for (i = 0; i < total_channels; i++)
670         {
671                 channel_t *ch;
672
673                 ch = &channels[i];
674                 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
675                         ch->flags &= ~CHANNELFLAG_PAUSED;
676         }
677 }
678
679 void S_SetChannelVolume (unsigned int ch_ind, float fvol)
680 {
681         channels[ch_ind].master_vol = fvol * 255;
682 }
683
684
685 void S_ClearBuffer(void)
686 {
687         int             clear;
688
689         if (!sound_started || !shm)
690                 return;
691
692         if (shm->format.width == 1)
693                 clear = 0x80;
694         else
695                 clear = 0;
696
697 #ifdef USE_DSOUND
698         if (pDSBuf)
699         {
700                 DWORD   dwSize;
701                 DWORD   *pData;
702                 int             reps;
703                 HRESULT hresult;
704
705                 reps = 0;
706
707                 while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, (LPVOID*)&pData, &dwSize, NULL, NULL, 0)) != DS_OK)
708                 {
709                         if (hresult != DSERR_BUFFERLOST)
710                         {
711                                 Con_Print("S_ClearBuffer: DS::Lock Sound Buffer Failed\n");
712                                 S_Shutdown ();
713                                 return;
714                         }
715
716                         if (++reps > 10000)
717                         {
718                                 Con_Print("S_ClearBuffer: DS: couldn't restore buffer\n");
719                                 S_Shutdown ();
720                                 return;
721                         }
722                 }
723
724                 memset(pData, clear, shm->samples * shm->format.width);
725
726                 pDSBuf->lpVtbl->Unlock(pDSBuf, pData, dwSize, NULL, 0);
727
728         }
729         else
730 #endif
731         if (shm->buffer)
732         {
733                 int             setsize = shm->samples * shm->format.width;
734                 char    *buf = shm->buffer;
735
736                 while (setsize--)
737                         *buf++ = clear;
738
739 // on i586/i686 optimized versions of glibc, glibc *wrongly* IMO,
740 // reads the memory area before writing to it causing a seg fault
741 // since the memory is PROT_WRITE only and not PROT_READ|PROT_WRITE
742 //              memset(shm->buffer, clear, shm->samples * shm->samplebits/8);
743         }
744 }
745
746
747 /*
748 =================
749 S_StaticSound
750 =================
751 */
752 void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation)
753 {
754         channel_t       *ss;
755
756         if (!sfx)
757                 return;
758
759         if (total_channels == MAX_CHANNELS)
760         {
761                 Con_Print("total_channels == MAX_CHANNELS\n");
762                 return;
763         }
764
765         if (!S_LoadSound (sfx, true))
766                 return;
767
768         if (sfx->loopstart == -1)
769                 Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
770
771         ss = &channels[total_channels++];
772         memset(ss, 0, sizeof(*ss));
773         ss->flags = CHANNELFLAG_FORCELOOP;
774         ss->sfx = sfx;
775         VectorCopy (origin, ss->origin);
776         ss->master_vol = vol;
777         ss->dist_mult = (attenuation/64) / sound_nominal_clip_dist;
778         ss->end = paintedtime + sfx->total_length;
779         ss->lastptime = paintedtime;
780
781         SND_Spatialize (ss, true);
782 }
783
784
785 //=============================================================================
786
787 /*
788 ===================
789 S_UpdateAmbientSounds
790 ===================
791 */
792 void S_UpdateAmbientSounds (void)
793 {
794         float           vol;
795         int                     ambient_channel;
796         channel_t       *chan;
797         qbyte           ambientlevels[NUM_AMBIENTS];
798
799         // LordHavoc: kill ambient sounds until proven otherwise
800         for (ambient_channel = 0 ; ambient_channel < NUM_AMBIENTS;ambient_channel++)
801                 channels[ambient_channel].sfx = NULL;
802
803         if (ambient_level.value <= 0 || !cl.worldmodel || !cl.worldmodel->brush.AmbientSoundLevelsForPoint)
804                 return;
805
806         cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
807
808 // calc ambient sound levels
809         for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
810         {
811                 if (ambient_sfx[ambient_channel] &&
812                         (ambient_sfx[ambient_channel]->flags & SFXFLAG_SILENTLYMISSING))
813                         continue;
814                 chan = &channels[ambient_channel];
815                 chan->flags |= CHANNELFLAG_FORCELOOP;
816                 chan->sfx = ambient_sfx[ambient_channel];
817
818                 vol = ambient_level.value * ambientlevels[ambient_channel];
819                 if (vol < 8)
820                         vol = 0;
821
822         // don't adjust volume too fast
823                 if (chan->master_vol < vol)
824                 {
825                         chan->master_vol += host_realframetime * ambient_fade.value;
826                         if (chan->master_vol > vol)
827                                 chan->master_vol = vol;
828                 }
829                 else if (chan->master_vol > vol)
830                 {
831                         chan->master_vol -= host_realframetime * ambient_fade.value;
832                         if (chan->master_vol < vol)
833                                 chan->master_vol = vol;
834                 }
835
836                 chan->leftvol = chan->rightvol = chan->master_vol;
837         }
838 }
839
840
841 /*
842 ============
843 S_Update
844
845 Called once each time through the main loop
846 ============
847 */
848 void S_Update(const matrix4x4_t *listenermatrix)
849 {
850         unsigned int i, j, total;
851         channel_t *ch, *combine;
852
853         if (!snd_initialized.integer || (snd_blocked > 0))
854                 return;
855
856         Matrix4x4_Invert_Simple(&listener_matrix, listenermatrix);
857         Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
858
859 // update general area ambient sound sources
860         S_UpdateAmbientSounds ();
861
862         combine = NULL;
863
864 // update spatialization for static and dynamic sounds
865         ch = channels+NUM_AMBIENTS;
866         for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
867         {
868                 if (!ch->sfx)
869                         continue;
870                 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);         // respatialize channel
871                 if (!ch->leftvol && !ch->rightvol)
872                         continue;
873
874         // try to combine static sounds with a previous channel of the same
875         // sound effect so we don't mix five torches every frame
876
877                 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
878                 {
879                 // see if it can just use the last one
880                         if (combine && combine->sfx == ch->sfx)
881                         {
882                                 combine->leftvol += ch->leftvol;
883                                 combine->rightvol += ch->rightvol;
884                                 ch->leftvol = ch->rightvol = 0;
885                                 continue;
886                         }
887                 // search for one
888                         combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;
889                         for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; j<i; j++, combine++)
890                                 if (combine->sfx == ch->sfx)
891                                         break;
892
893                         if (j == total_channels)
894                                 combine = NULL;
895                         else
896                         {
897                                 if (combine != ch)
898                                 {
899                                         combine->leftvol += ch->leftvol;
900                                         combine->rightvol += ch->rightvol;
901                                         ch->leftvol = ch->rightvol = 0;
902                                 }
903                                 continue;
904                         }
905                 }
906         }
907
908 //
909 // debugging output
910 //
911         if (snd_show.integer)
912         {
913                 total = 0;
914                 ch = channels;
915                 for (i=0 ; i<total_channels; i++, ch++)
916                         if (ch->sfx && (ch->leftvol || ch->rightvol) )
917                                 total++;
918
919                 Con_Printf("----(%u)----\n", total);
920         }
921
922 // mix some sound
923         S_Update_();
924 }
925
926 void GetSoundtime(void)
927 {
928         int             samplepos;
929         static  int             buffers;
930         static  int             oldsamplepos;
931         int             fullsamples;
932
933         fullsamples = shm->samples / shm->format.channels;
934
935 // it is possible to miscount buffers if it has wrapped twice between
936 // calls to S_Update.  Oh well.
937         samplepos = SNDDMA_GetDMAPos();
938
939         if (samplepos < oldsamplepos)
940         {
941                 buffers++;                                      // buffer wrapped
942
943                 if (paintedtime > 0x40000000)
944                 {       // time to chop things off to avoid 32 bit limits
945                         buffers = 0;
946                         paintedtime = fullsamples;
947                         S_StopAllSounds (true);
948                 }
949         }
950         oldsamplepos = samplepos;
951
952         soundtime = buffers * fullsamples + samplepos / shm->format.channels;
953 }
954
955 void IN_Accumulate (void);
956
957 void S_ExtraUpdate (void)
958 {
959
960 #ifdef USE_DSOUND
961         IN_Accumulate ();
962 #endif
963
964         if (snd_noextraupdate.integer)
965                 return;         // don't pollute timings
966         S_Update_();
967 }
968
969 void S_Update_(void)
970 {
971         unsigned        endtime;
972         int                             samps;
973
974         if (!sound_started || (snd_blocked > 0))
975                 return;
976
977 // Updates DMA time
978         GetSoundtime();
979
980 // check to make sure that we haven't overshot
981         if (paintedtime < soundtime)
982                 paintedtime = soundtime;
983
984 // mix ahead of current position
985         endtime = soundtime + _snd_mixahead.value * shm->format.speed;
986         samps = shm->samples >> (shm->format.channels - 1);
987         if (endtime > (unsigned int)(soundtime + samps))
988                 endtime = soundtime + samps;
989
990 #ifdef USE_DSOUND
991 // if the buffer was lost or stopped, restore it and/or restart it
992         {
993                 DWORD   dwStatus;
994
995                 if (pDSBuf)
996                 {
997                         if (pDSBuf->lpVtbl->GetStatus (pDSBuf, &dwStatus) != DS_OK)
998                                 Con_Print("Couldn't get sound buffer status\n");
999
1000                         if (dwStatus & DSBSTATUS_BUFFERLOST)
1001                                 pDSBuf->lpVtbl->Restore (pDSBuf);
1002
1003                         if (!(dwStatus & DSBSTATUS_PLAYING))
1004                                 pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING);
1005                 }
1006         }
1007 #endif
1008
1009         S_PaintChannels (endtime);
1010
1011         SNDDMA_Submit ();
1012 }
1013
1014 /*
1015 ===============================================================================
1016
1017 console functions
1018
1019 ===============================================================================
1020 */
1021
1022 static void S_Play_Common(float fvol, float attenuation)
1023 {
1024         int     i, ch_ind;
1025         char name[256];
1026         sfx_t   *sfx;
1027
1028         i = 1;
1029         while (i<Cmd_Argc())
1030         {
1031                 if (!strrchr(Cmd_Argv(i), '.'))
1032                         snprintf(name, sizeof(name), "%s.wav", Cmd_Argv(i));
1033                 else
1034                         strlcpy(name, Cmd_Argv(i), sizeof(name));
1035                 sfx = S_PrecacheSound(name, true, true);
1036
1037                 // If we need to get the volume from the command line
1038                 if (fvol == -1.0f)
1039                 {
1040                         fvol = atof(Cmd_Argv(i+1));
1041                         i += 2;
1042                 }
1043                 else
1044                         i++;
1045
1046                 ch_ind = S_StartSound(-1, 0, sfx, listener_origin, fvol, attenuation);
1047                 if (ch_ind >= 0)
1048                         channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
1049         }
1050 }
1051
1052 void S_Play(void)
1053 {
1054         S_Play_Common (1.0f, 1.0f);
1055 }
1056
1057 void S_Play2(void)
1058 {
1059         S_Play_Common (1.0f, 0.0f);
1060 }
1061
1062 void S_PlayVol(void)
1063 {
1064         S_Play_Common (-1.0f, 0.0f);
1065 }
1066
1067 void S_SoundList(void)
1068 {
1069         int             i;
1070         sfx_t   *sfx;
1071         int             size, total;
1072
1073         total = 0;
1074         for (sfx=known_sfx, i=0 ; i<num_sfx ; i++, sfx++)
1075         {
1076                 if (sfx->fetcher != NULL)
1077                 {
1078                         size = sfx->mempool->totalsize;
1079                         total += size;
1080                         Con_Printf ("%c%c(%2db, %6s) %8i : %s\n",
1081                                                 (sfx->loopstart >= 0) ? 'L' : ' ',
1082                                                 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
1083                                                 sfx->format.width * 8,
1084                                                 (sfx->format.channels == 2) ? "stereo" : "mono",
1085                                                 size,
1086                                                 sfx->name);
1087                 }
1088         }
1089         Con_Printf("Total resident: %i\n", total);
1090 }
1091
1092
1093 void S_LocalSound (const char *sound, qboolean stdpath)
1094 {
1095         sfx_t   *sfx;
1096         int             ch_ind;
1097
1098         if (!snd_initialized.integer || nosound.integer)
1099                 return;
1100
1101         sfx = S_PrecacheSound (sound, true, stdpath);
1102         if (!sfx)
1103         {
1104                 Con_Printf("S_LocalSound: can't precache %s\n", sound);
1105                 return;
1106         }
1107
1108         ch_ind = S_StartSound (cl.viewentity, 0, sfx, vec3_origin, 1, 1);
1109         if (ch_ind >= 0)
1110                 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
1111 }