-
Notifications
You must be signed in to change notification settings - Fork 1
/
audio.go
743 lines (638 loc) · 21 KB
/
audio.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
package game
import (
"fmt"
"math"
"sync"
"time"
"github.com/adrianbrad/queue"
"github.com/hajimehoshi/ebiten/v2/audio"
"github.com/harbdog/raycaster-go/geom"
"github.com/harbdog/raycaster-go/geom3d"
"github.com/pixelmek-3d/pixelmek-3d/game/model"
"github.com/pixelmek-3d/pixelmek-3d/game/render"
"github.com/pixelmek-3d/pixelmek-3d/game/resources"
"github.com/solarlune/resound"
log "github.com/sirupsen/logrus"
)
type AudioMainSource int
const (
AUDIO_INTERFACE AudioMainSource = iota
AUDIO_ENGINE
AUDIO_STOMP_LEFT
AUDIO_STOMP_RIGHT
AUDIO_JUMP_JET
_AUDIO_MAIN_SOURCE_COUNT
)
type AudioInterfaceResource string
const (
AUDIO_BUTTON_AFF AudioInterfaceResource = "audio/sfx/button-aff.ogg"
AUDIO_BUTTON_NEG AudioInterfaceResource = "audio/sfx/button-neg.ogg"
AUDIO_BUTTON_OVER AudioInterfaceResource = "audio/sfx/button-over.ogg"
AUDIO_CLICK_AFF AudioInterfaceResource = "audio/sfx/click-aff.ogg"
AUDIO_CLICK_NEG AudioInterfaceResource = "audio/sfx/click-neg.ogg"
AUDIO_SELECT_TARGET AudioInterfaceResource = "audio/sfx/select-target.ogg"
)
var (
bgmVolume float64
sfxVolume float64
sfxChannels int
)
type AudioHandler struct {
bgm *BGMHandler
sfx *SFXHandler
sfxMap *sync.Map // map[string][]byte
}
type BGMHandler struct {
channel *resound.DSPChannel
player *resound.DSPPlayer
}
type SFXHandler struct {
mainSources []*SFXSource
entitySources *sync.Map // map[model.Entity]*SFXSource
extSources *queue.Priority[*SFXSource]
_extSFXCount *sync.Map // map[string]float64
}
type SFXSource struct {
channel *resound.DSPChannel
player *resound.DSPPlayer
volume float64
_sfxFile string
_pausedWhilePlaying bool
_sfxType _sfxTypeHint
}
type _sfxTypeHint int
const (
_SFX_HINT_NONE _sfxTypeHint = iota
_SFX_HINT_ENGINE
_SFX_HINT_POWER_ON
_SFX_HINT_POWER_OFF
)
func init() {
audio.NewContext(resources.SampleRate)
}
// NewAudioHandler creates a new audio handler instance
func NewAudioHandler() *AudioHandler {
a := &AudioHandler{}
a.bgm = &BGMHandler{}
a.bgm.channel = resound.NewDSPChannel()
a.bgm.channel.Add("volume", resound.NewVolume(nil))
a.SetMusicVolume(bgmVolume)
a.sfxMap = &sync.Map{}
a.sfx = &SFXHandler{}
a.sfx.mainSources = make([]*SFXSource, _AUDIO_MAIN_SOURCE_COUNT)
a.sfx.entitySources = &sync.Map{}
a.sfx.mainSources[AUDIO_INTERFACE] = NewSoundEffectSource(0.8)
// engine audio source file setup later since it is a looping ambient source
// TODO: increase engine noise level a bit when running or at high heat levels
a.sfx.mainSources[AUDIO_ENGINE] = NewSoundEffectSource(0.3)
// stomp audio track to be initialized based on player unit selection
a.sfx.mainSources[AUDIO_STOMP_LEFT] = NewSoundEffectSource(0.5)
a.sfx.mainSources[AUDIO_STOMP_LEFT].SetPan(-0.5)
a.sfx.mainSources[AUDIO_STOMP_RIGHT] = NewSoundEffectSource(0.5)
a.sfx.mainSources[AUDIO_STOMP_RIGHT].SetPan(0.5)
a.sfx.mainSources[AUDIO_JUMP_JET] = NewSoundEffectSource(0.7)
a.sfx.mainSources[AUDIO_JUMP_JET].LoadSFX(a, "audio/sfx/jet-thrust.ogg")
a.SetSFXChannels(sfxChannels)
a.SetSFXVolume(sfxVolume)
return a
}
// NewSoundEffectSource creates a new sound effect channel
func NewSoundEffectSource(sourceVolume float64) *SFXSource {
s := &SFXSource{volume: sourceVolume}
s.channel = resound.NewDSPChannel()
s.channel.Add("volume", resound.NewVolume(nil).SetStrength(sourceVolume))
s.channel.Add("pan", resound.NewPan(nil))
return s
}
// LoadSFX loads a new sound effect player into the sound effect channel
func (s *SFXSource) LoadSFX(a *AudioHandler, sfxFile string) error {
// make sure current source is closed before loading a new one
s.Close()
// use cache of audio if possible
var audioBytes []byte
iAudioBytes, found := a.sfxMap.Load(sfxFile)
if audioBytesCheck, ok := iAudioBytes.([]byte); found && ok {
audioBytes = audioBytesCheck
} else {
var err error
audioBytes, err = resources.ReadFile(sfxFile)
if err != nil {
log.Error("Error reading sound effect file: " + sfxFile)
return err
}
a.sfxMap.Store(sfxFile, audioBytes)
}
stream, _, err := resources.NewAudioStream(audioBytes, sfxFile)
if err != nil {
log.Error("Error playing sound effect file: " + sfxFile)
return err
}
s.player = s.channel.CreatePlayer(stream)
s.player.SetBufferSize(time.Millisecond * 100)
s._sfxFile = sfxFile
return nil
}
// LoadLoopSFX loads a new looping sound effect player into the sound effect channel
func (s *SFXSource) LoadLoopSFX(a *AudioHandler, sfxFile string) error {
// make sure current source is closed before loading a new one
s.Close()
// use cache of audio if possible
var audioBytes []byte
iAudioBytes, found := a.sfxMap.Load(sfxFile)
if audioBytesCheck, ok := iAudioBytes.([]byte); found && ok {
audioBytes = audioBytesCheck
} else {
var err error
audioBytes, err = resources.ReadFile(sfxFile)
if err != nil {
log.Error("Error reading looping sound effect file: " + sfxFile)
return err
}
a.sfxMap.Store(sfxFile, audioBytes)
}
stream, length, err := resources.NewAudioStream(audioBytes, sfxFile)
if err != nil {
log.Error("Error playing looping sound effect file: " + sfxFile)
return err
}
loop := audio.NewInfiniteLoop(stream, length)
s.player = s.channel.CreatePlayer(loop)
s.player.SetBufferSize(time.Millisecond * 100)
s._sfxFile = sfxFile
return nil
}
// UpdateVolume updates the volume of the sound channel taking into account relative volume modifier
func (s *SFXSource) UpdateVolume() {
v := s.channel.Effects["volume"].(*resound.Volume)
v.SetStrength(sfxVolume * s.volume)
}
// SetSourceVolume sets the relative volume modifier of the sound channel
func (s *SFXSource) SetSourceVolume(sourceVolume float64) {
s.volume = sourceVolume
s.UpdateVolume()
}
// SetPan sets the left/right panning percent of the sound channel
func (s *SFXSource) SetPan(panPercent float64) {
if pan, ok := s.channel.Effects["pan"].(*resound.Pan); ok {
pan.SetPan(panPercent)
} else {
s.channel.Add("pan", resound.NewPan(nil).SetPan(panPercent))
}
}
// IsPlaying returns true if the sound effect is currently playing
func (s *SFXSource) IsPlaying() bool {
if s.player != nil {
return s.player.IsPlaying()
}
return false
}
// Play starts playing the sound effect player from the beginning of the effect
func (s *SFXSource) Play() {
s._pausedWhilePlaying = false
if s.player != nil {
s.player.Rewind()
s.player.Play()
}
}
// Pause pauses the sound effect player
func (s *SFXSource) Pause() {
if s.player != nil {
s._pausedWhilePlaying = s.player.IsPlaying()
s.player.Pause()
}
}
// Resume resumes the sound effect player without rewinding
func (s *SFXSource) Resume() {
if s.player != nil && s._pausedWhilePlaying {
s.player.Play()
}
}
// Close stops and closes the sound effect player
func (s *SFXSource) Close() {
s._pausedWhilePlaying = false
if s.player != nil {
s.player.Close()
s.player = nil
}
}
// PlaySFX plays given external sound effect file
func (a *AudioHandler) PlaySFX(sfxFile string, sourceVolume, panPercent float64) {
if sfxVolume <= 0 || sourceVolume <= 0 {
return
}
// get and close the lowest priority source for reuse
source, _ := a.sfx.extSources.Get()
if source == nil {
source = NewSoundEffectSource(0.0)
} else {
// decrement count of the previous sound effect
a.sfx._updateExtSFXCount(source._sfxFile, -1)
source.Close()
}
source.SetSourceVolume(sourceVolume)
source.SetPan(panPercent)
source.LoadSFX(a, sfxFile)
source.Play()
// increment count of this sound effect
a.sfx._updateExtSFXCount(sfxFile, 1)
a.sfx.extSources.Offer(source)
}
// PlayLoopEntitySFX plays given looping sound effect as emitted from an Entity object, if not already playing
func (a *AudioHandler) PlayLoopEntitySFX(sfxFile string, entity model.Entity, sourceVolume, panPercent float64) {
if sfxVolume <= 0 || sourceVolume <= 0 {
return
}
// check if entity is already playing a looping source to update instead of playing as new source
var source *SFXSource
a.sfx.entitySources.Range(func(k, v interface{}) bool {
if entity == k.(model.Entity) {
source = v.(*SFXSource)
return false
}
return true
})
// get and close the lowest priority source for reuse
// source, _ := a.sfx.extSources.Get()
if source == nil {
source = NewSoundEffectSource(0.0)
} else if source._sfxFile != sfxFile {
// close out the source to play a new source
source.Close()
}
// update volume and panning, even if continuing to play current loop
source.SetSourceVolume(sourceVolume)
source.SetPan(panPercent)
if source._sfxFile == sfxFile {
// TODO: any better way to get the volume and pan to update in a playing loop?
source.player.Pause()
source.player.Play()
} else {
source.LoadLoopSFX(a, sfxFile)
source.Play()
}
// store the sound effect against the Entity
a.sfx.entitySources.Store(entity, source)
}
// StopLoopEntitySFX stops given looping sound effect as emitted from an Entity object
func (a *AudioHandler) StopLoopEntitySFX(sfxFile string, entity model.Entity) {
var source *SFXSource
a.sfx.entitySources.Range(func(k, v interface{}) bool {
if entity == k.(model.Entity) {
source = v.(*SFXSource)
return false
}
return true
})
if source != nil && sfxFile == source._sfxFile {
source.Close()
source._sfxFile = ""
}
}
// _updateExtSFXCount is used to keep track of duplicate sound effects being played to prioritize channel reuse
func (s *SFXHandler) _updateExtSFXCount(sfxFile string, countDiff int) {
var newCount float64
if value, ok := s._extSFXCount.Load(sfxFile); ok {
if count, ok := value.(float64); ok {
newCount = count
}
}
newCount += float64(countDiff)
if newCount < 0 {
newCount = 0
}
s._extSFXCount.Store(sfxFile, newCount)
}
// SetMusicVolume sets volume of background music
func (a *AudioHandler) SetMusicVolume(strength float64) {
bgmVolume = strength
v := a.bgm.channel.Effects["volume"].(*resound.Volume)
v.SetStrength(bgmVolume)
if bgmVolume == 0 {
a.PauseMusic()
} else {
a.ResumeMusic()
}
}
// SetSFXVolume sets volume of all sound effect sources
func (a *AudioHandler) SetSFXVolume(strength float64) {
sfxVolume = strength
for _, s := range a.sfx.mainSources {
s.UpdateVolume()
}
for s := range a.sfx.extSources.Iterator() {
s.UpdateVolume()
a.sfx.extSources.Offer(s)
}
}
// SetSFXChannels sets max number of external sound effect channels
func (a *AudioHandler) SetSFXChannels(numChannels int) {
sfxChannels = numChannels
extInit := make([]*SFXSource, 0, sfxChannels)
for i := 0; i < sfxChannels; i++ {
// reuse existing channels if available
if a.sfx.extSources != nil && !a.sfx.extSources.IsEmpty() {
s, _ := a.sfx.extSources.Get()
extInit = append(extInit, s)
} else {
extInit = append(extInit, NewSoundEffectSource(0.0))
}
}
if a.sfx.extSources != nil && !a.sfx.extSources.IsEmpty() {
// close out any excess channels as necessary
for s := range a.sfx.extSources.Iterator() {
s.Close()
}
}
a.sfx.extSources = queue.NewPriority(
extInit,
a.sfxSourcePriorityCompare,
queue.WithCapacity(sfxChannels),
)
a.sfx._extSFXCount = &sync.Map{}
}
func (a *AudioHandler) sfxSourcePriorityCompare(elem, other *SFXSource) bool {
// give higher priority rating to sources that are still playing and with higher volume
var elemRating, otherRating float64
if elem.player != nil && elem.player.IsPlaying() {
elemRating = elem.player.Volume()
}
if other.player != nil && other.player.IsPlaying() {
otherRating = other.player.Volume()
}
// give lower priority rating to sources that have multiple of the same sound effect currently playing
if elemRating > 0 {
if value, ok := a.sfx._extSFXCount.Load(elem._sfxFile); ok {
elemCount, ok := value.(float64)
if ok {
elemRating *= 1 / (elemCount + 1)
}
}
}
if otherRating > 0 {
if value, ok := a.sfx._extSFXCount.Load(other._sfxFile); ok {
otherCount, ok := value.(float64)
if ok {
otherRating *= 1 / (otherCount + 1)
}
}
}
return elemRating < otherRating
}
// IsMusicPlaying return true if background music is currently playing
func (a *AudioHandler) IsMusicPlaying() bool {
return a.bgm.player != nil && a.bgm.player.IsPlaying()
}
// StopMusic stops and closes the background music source
func (a *AudioHandler) StopMusic() {
if a.bgm.player != nil {
a.bgm.player.Close()
a.bgm.player = nil
}
}
// PauseMusic pauses play of background music
func (a *AudioHandler) PauseMusic() {
if a.bgm.player != nil && a.bgm.player.IsPlaying() {
a.bgm.player.Pause()
}
}
// ResumeMusic resumes play of background music
func (a *AudioHandler) ResumeMusic() {
if a.bgm.player != nil && !a.bgm.player.IsPlaying() {
a.bgm.player.Play()
}
}
// StopSFX stops and closes all sound effect sources
func (a *AudioHandler) StopSFX() {
for _, s := range a.sfx.mainSources {
if s.player != nil {
s.player.Close()
}
}
a.sfx.entitySources.Range(func(_, v interface{}) bool {
s := v.(*SFXSource)
s.Close()
return true
})
for s := range a.sfx.extSources.Iterator() {
s.Close()
a.sfx.extSources.Offer(s)
}
}
// PauseSFX pauses all sound effect sources
func (a *AudioHandler) PauseSFX() {
for _, s := range a.sfx.mainSources {
s.Pause()
}
a.sfx.entitySources.Range(func(_, v interface{}) bool {
s := v.(*SFXSource)
s.Pause()
return true
})
for s := range a.sfx.extSources.Iterator() {
s.Pause()
a.sfx.extSources.Offer(s)
}
}
// ResumeSFX resumes play of all sound effect sources
func (a *AudioHandler) ResumeSFX() {
for _, s := range a.sfx.mainSources {
s.Resume()
}
a.sfx.entitySources.Range(func(_, v interface{}) bool {
s := v.(*SFXSource)
s.Resume()
return true
})
for s := range a.sfx.extSources.Iterator() {
s.Resume()
a.sfx.extSources.Offer(s)
}
}
// StartMenuMusic starts main menu background music audio loop
func (a *AudioHandler) StartMenuMusic() {
a.StartMusicFromFile("audio/music/crossing_horizon.mp3")
}
// StartMusicFromFile starts background music audio loop
func (a *AudioHandler) StartMusicFromFile(path string) {
if a.bgm.player != nil {
a.StopMusic()
}
stream, length, err := resources.NewAudioStreamFromFile(path)
if err != nil {
log.Error("Error loading music:")
log.Error(err)
return
}
bgm := audio.NewInfiniteLoop(stream, length)
vol := resound.NewVolume(bgm)
a.bgm.player = a.bgm.channel.CreatePlayer(vol)
a.bgm.player.SetBufferSize(time.Millisecond * 100)
a.bgm.player.Play()
}
// StartEngineAmbience starts the ambient engine audio loop
func (a *AudioHandler) StartEngineAmbience() {
engine := a.sfx.mainSources[AUDIO_ENGINE]
engine._sfxType = _SFX_HINT_ENGINE
if engine.player != nil {
engine.player.Close()
}
// TODO: different ambient angine sound for different tonnages/unit types
stream, length, err := resources.NewAudioStreamFromFile("audio/sfx/ambience-engine.ogg")
if err != nil {
log.Error("Error loading engine ambience file:")
log.Error(err)
engine.player = nil
return
}
engAmb := audio.NewInfiniteLoop(stream, length)
vol := resound.NewVolume(engAmb)
engine.player = engine.channel.CreatePlayer(vol)
engine.player.SetBufferSize(time.Millisecond * 50)
engine.player.Play()
}
// StopEngineAmbience stop the ambient engine audio loop
func (a *AudioHandler) StopEngineAmbience() {
engine := a.sfx.mainSources[AUDIO_ENGINE]
if engine._sfxType == _SFX_HINT_ENGINE && engine.player != nil && engine.player.IsPlaying() {
engine._sfxType = _SFX_HINT_NONE
engine.player.Close()
}
}
// IsEngineAmbience indicates whether the current engine audio is the ambience loop
func (a *AudioHandler) EngineAmbience() _sfxTypeHint {
return a.sfx.mainSources[AUDIO_ENGINE]._sfxType
}
// PlayPowerOnSequence plays the power on sound using the engine audio source
func (a *AudioHandler) PlayPowerOnSequence() {
engine := a.sfx.mainSources[AUDIO_ENGINE]
engine._sfxType = _SFX_HINT_POWER_ON
if engine.player != nil {
engine.player.Close()
}
// TODO: different power on sounds for different tonnages/unit types
engine.LoadSFX(a, "audio/sfx/power-on.ogg")
engine.player.Play()
}
// PlayPowerOffSequence plays the power down sound using the engine audio source
func (a *AudioHandler) PlayPowerOffSequence() {
engine := a.sfx.mainSources[AUDIO_ENGINE]
engine._sfxType = _SFX_HINT_POWER_OFF
if engine.player != nil {
engine.player.Close()
}
engine.LoadSFX(a, "audio/sfx/power-off.ogg")
engine.player.Play()
}
func (a *AudioHandler) SetStompSFX(sfxFile string) {
a.sfx.mainSources[AUDIO_STOMP_LEFT].LoadSFX(a, sfxFile)
a.sfx.mainSources[AUDIO_STOMP_RIGHT].LoadSFX(a, sfxFile)
}
func StompSFXForMech(m *model.Mech) (string, error) {
if m == nil {
return "", fmt.Errorf("can not get stomp SFX for nil mech")
}
mechClass := m.Class()
mechStompFile := fmt.Sprintf("audio/sfx/stomp-%d.ogg", mechClass)
return mechStompFile, nil
}
func JumpJetSFXForMech(m *model.Mech) (string, error) {
if m == nil {
return "", fmt.Errorf("can not get jump jet SFX for nil mech")
}
return "audio/sfx/jet-thrust.ogg", nil
}
// PlayButtonAudio plays the indicated button audio channel resource
func (a *AudioHandler) PlayButtonAudio(buttonResource AudioInterfaceResource) {
sfxSource := a.sfx.mainSources[AUDIO_INTERFACE]
sfxSource.LoadSFX(a, string(buttonResource))
sfxSource.Play()
}
// IsButtonAudioPlaying returns true if the button audio channel is still playing
func (a *AudioHandler) IsButtonAudioPlaying() bool {
sfxSource := a.sfx.mainSources[AUDIO_INTERFACE]
return sfxSource.player != nil && sfxSource.player.IsPlaying()
}
// PlayLocalWeaponFireAudio plays weapon fire audio intended only if fired by the player unit
func (a *AudioHandler) PlayLocalWeaponFireAudio(weapon model.Weapon) {
if len(weapon.Audio()) > 0 {
var panPercent float64
offsetX := -weapon.Offset().X
switch {
case offsetX < 0:
// pan left
panPercent = geom.Clamp(offsetX-0.4, -0.8, 0)
case offsetX > 0:
// pan right
panPercent = geom.Clamp(offsetX+0.4, 0, 0.8)
}
go a.PlaySFX(weapon.Audio(), 1.0, panPercent)
}
}
// PlayExternalWeaponFireAudio plays weapon fire audio fired by units other than the player
func (a *AudioHandler) PlayExternalWeaponFireAudio(g *Game, weapon model.Weapon, extUnit model.Unit) {
if len(weapon.Audio()) > 0 {
// TODO: introduce volume modifier based on weapon type, classification, and size
extPos, extPosZ := extUnit.Pos(), extUnit.PosZ()
a.PlayExternalAudio(g, weapon.Audio(), extPos.X, extPos.Y, extPosZ, 10, 1.0)
}
}
// PlayProjectileImpactAudio plays projectile impact audio near the player
func (a *AudioHandler) PlayProjectileImpactAudio(g *Game, p *render.ProjectileSprite) {
impactAudio := p.ImpactAudio()
if len(impactAudio) > 0 {
// TODO: introduce volume modifier based on projectile's weapon type, classification, and size
extPos, extPosZ := p.Pos(), p.PosZ()
a.PlayExternalAudio(g, impactAudio, extPos.X, extPos.Y, extPosZ, 10, 1.0)
}
}
// PlayEffectAudio plays effect audio near the player
func (a *AudioHandler) PlayEffectAudio(g *Game, p *render.EffectSprite) {
fxAudio := p.AudioFile
if len(fxAudio) > 0 {
extPos, extPosZ := p.Pos(), p.PosZ()
a.PlayExternalAudio(g, fxAudio, extPos.X, extPos.Y, extPosZ, 10, 0.7)
}
}
// PlayExternalAudio plays audio that may be near the player taking into account distance/direction for volume/panning
// intensityDist - distance of 100% sound intensity before volume begins to dropoff at a rate of 1/d^2
// maxVolume - the maximum volume percent to be perceived by the player
func (a *AudioHandler) PlayExternalAudio(g *Game, sfxFile string, extPosX, extPosY, extPosZ, intensityDist, maxVolume float64) {
playerPos := g.player.Pos()
playerHeading := g.player.cameraAngle
extLine := geom3d.Line3d{
X1: playerPos.X, Y1: playerPos.Y, Z1: g.player.cameraZ,
X2: extPosX, Y2: extPosY, Z2: extPosZ,
}
extDist := extLine.Distance()
extHeading := extLine.Heading()
relHeading := -model.AngleDistance(playerHeading, extHeading)
relPercent := 1 - (geom.HalfPi-relHeading)/geom.HalfPi
extVolume := geom.Clamp(math.Pow(intensityDist/extDist, 2), 0.0, maxVolume)
if extVolume > 0.05 {
go g.audio.PlaySFX(sfxFile, extVolume, relPercent)
}
}
// PlayEntityAudioLoop plays audio that may be near the player emitted from an Entity object
// intensityDist - distance of 100% sound intensity before volume begins to dropoff at a rate of 1/d^2
// maxVolume - the maximum volume percent to be perceived by the player
func (a *AudioHandler) PlayEntityAudioLoop(g *Game, sfxFile string, entity model.Entity, intensityDist, maxVolume float64) {
playerPos := g.player.Pos()
playerHeading := g.player.cameraAngle
extPosX, extPosY, extPosZ := entity.Pos().X, entity.Pos().Y, entity.PosZ()
extLine := geom3d.Line3d{
X1: playerPos.X, Y1: playerPos.Y, Z1: g.player.cameraZ,
X2: extPosX, Y2: extPosY, Z2: extPosZ,
}
extDist := extLine.Distance()
extHeading := extLine.Heading()
relHeading := -model.AngleDistance(playerHeading, extHeading)
relPercent := 1 - (geom.HalfPi-relHeading)/geom.HalfPi
extVolume := geom.Clamp(math.Pow(intensityDist/extDist, 2), 0.0, maxVolume)
if extVolume > 0.05 {
go g.audio.PlayLoopEntitySFX(sfxFile, entity, extVolume, relPercent)
}
}
// StopEntityAudioLoop stops audio emitted from an Entity object that may have been playing
func (a *AudioHandler) StopEntityAudioLoop(g *Game, sfxFile string, entity model.Entity) {
g.audio.StopLoopEntitySFX(sfxFile, entity)
}