-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathOggSoundManager.java
More file actions
416 lines (372 loc) · 17 KB
/
OggSoundManager.java
File metadata and controls
416 lines (372 loc) · 17 KB
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
/*
* Copyright 2020 The Terasology Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.destinationsol.assets.sound;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.math.Vector2;
import org.destinationsol.Const;
import org.destinationsol.SolApplication;
import org.destinationsol.assets.Assets;
import org.destinationsol.common.NotNull;
import org.destinationsol.common.Nullable;
import org.destinationsol.common.SolMath;
import org.destinationsol.common.SolRandom;
import org.destinationsol.game.DebugOptions;
import org.destinationsol.game.GameDrawer;
import org.destinationsol.game.Hero;
import org.destinationsol.game.SolCam;
import org.destinationsol.game.SolGame;
import org.destinationsol.game.SolObject;
import org.destinationsol.game.UpdateAwareSystem;
import org.destinationsol.game.context.Context;
import org.destinationsol.game.planet.Planet;
import org.destinationsol.game.sound.DebugHintDrawer;
import org.terasology.gestalt.entitysystem.entity.EntityRef;
import java.util.HashMap;
import java.util.Map;
/**
* This class represents the sound manager used in DestinationSol. It is responsible for handling and playing all
* sounds in the game.
* <p>
* This class loads the sound as required from {@link Assets}, all you need to do for your sound to be registered is to
* place the sound in {@code .ogg} format in one of the asset-scanned directories.
* <p>
* You can also optionally place a text file with the same name as the ogg file and {@code .soundinfo} extension, that
* might contain the following: {@code
* volume=xxx
* loopTime=xxx
* }
* In there, the {@code xxx} stands for a floating point number.<br>
* {@code volume} specifies the default volume multiplier for the sound, with {@code 1.0} being the value unchanged.<br>
* {@code loopTime} works as follows: if the loopTime is not specified or set to 0, any new request to play the sound
* will play it again, even concurrently with itself. If the loopTime is set greater than 0, new request to play the
* sound will be accepted only when loopTime time units has passed since the beginning of the sound's prior playback, or
* the request is from different object.
*/
public class OggSoundManager implements UpdateAwareSystem {
/**
* A container for all the sounds that have been so far loaded in the game. Sounds are loaded on as needed basis,
* and once loaded, they persist here till the end of game. String is the fully qualified name of the sound
* ("module:sound_name").
*/
private final Map<String, OggSound> soundMap;
/**
* A container for working with looping sounds. Looped sounds are stored here per-object, and this map is every
* while cleared, on basis provided by calling each object's {@link SolObject#shouldBeRemoved(SolGame)} method.
* {@code SolObject} is the object the sound belongs to, inner map's {@code OggSound} is the sound in question,
* {@code Float} is an absolute time the sound will stop playing. (Absolute as in not relative to the current time)
*/
private final Map<SolObject, Map<OggSound, Float>> loopedSoundMapOfSolObjects;
/**
* A container for working with looping sounds. Looped sounds are stored here per-entity, and this map is every so often
* cleared, on the basis provided by calling each entity's {@link EntityRef#exists()} method.
* {@code EntityRef} is the object the sound belongs to, inner map's {@code OggSound} is the sound in question,
* {@code Float} is an absolute time the sound will stop playing. (Absolute as in not relative to the current time)
*/
private final Map<EntityRef, Map<OggSound, Float>> loopedSoundMapOfEntities;
/**
* Used for drawing debug hints when {@link DebugOptions#SOUND_INFO} flag is set. See
* {@link #drawDebug(GameDrawer, SolCam)} for more info.
*/
private final DebugHintDrawer debugHintDrawer;
//A reference to the camera, which represents the on-screen area.
private final SolCam solCam;
/**
* This is used only in {@link #update(SolGame, float)}, and is used for ensuring some more resource expensive operations
* happen only once in a while. This variable functions as millisecond countdown, with {@code <= 0} values meaning
* "Do the operations now".
*/
private float myLoopAwait;
private final SolApplication solApplication;
public OggSoundManager(Context context) {
soundMap = new HashMap<>();
loopedSoundMapOfSolObjects = new HashMap<>();
loopedSoundMapOfEntities = new HashMap<>();
debugHintDrawer = new DebugHintDrawer();
solApplication = context.get(SolApplication.class);
this.solCam = context.get(SolCam.class);
}
/**
* Returns an {@link OggSound} specified by name.
*
* @param path Name of the sound in th form "module:soundName"
* @return The specified sound object.
*/
public OggSound getSound(String path) {
return getSound(path, 1.0f);
}
/**
* Returns an {@link OggSound} specified by name and highered/lowered by {@code basePitch}.
*
* @param path Name of the sound in th form "module:soundName"
* @param basePitch Multiplier to higher/lower sound by.
* @return The specified sound object.
*/
public OggSound getSound(String path, float basePitch) {
if (soundMap.containsKey(path)) {
final OggSound sound = soundMap.get(path);
sound.setBasePitch(basePitch);
return sound;
}
OggSound sound = Assets.getSound(path);
sound.setBasePitch(basePitch);
soundMap.put(path, sound);
return sound;
}
/**
* Plays a sound at specified position, or coming from specific source.
* <p>
* {@code source} must not be null if the sound is specified to loop, and at least one of {@code source} or
* {@code position} must be specified.
*
* @param game Game to play the sound in.
* @param sound The sound to play
* @param position Position to play the sound at. If null, source.getPosition() will be used.
* @param source Bearer of a sound. Must not be null for looped sounds or when {@code position} is null.
*/
public void play(SolGame game, PlayableSound sound, @Nullable Vector2 position, @Nullable SolObject source) {
play(game, sound, position, source, 1f);
}
/**
* Plays a sound at specified position, or coming from specific source.
* <p>
* {@code source} must not be null if the sound is specified to loop, and at least one of {@code source} or
* {@code position} must be specified.
*
* @param game Game to play the sound in.
* @param playableSound The sound to play
* @param position Position to play the sound at. If null, source.getPosition() will be used.
* @param source Bearer of a sound. Must not be null for looped sounds or when {@code position} is null.
* @param volumeMultiplier Multiplier for sound volume.
*/
public void play(SolGame game, PlayableSound playableSound, @Nullable Vector2 position, @Nullable SolObject source, float volumeMultiplier) {
if (playableSound == null) {
return;
}
OggSound sound = playableSound.getOggSound();
// Perform some initial argument validation
if (source == null && position == null) {
throw new AssertionError("Either position or source must be non-null");
}
if (source == null && sound.getLoopTime() > 0) {
throw new AssertionError("Attempted to loop a sound without a parent object: " + sound.getUrn());
}
if (position == null) {
position = source.getPosition();
}
float volume = getVolume(game, position, volumeMultiplier, sound);
if (volume <= 0) {
return;
}
// Calculate the pitch for the sound
float pitch = SolRandom.randomFloat(.97f, 1.03f) * game.getTimeFactor() * playableSound.getBasePitch();
if (skipLooped(source, sound, game.getTime())) {
return;
}
if (DebugOptions.SOUND_INFO) {
debugHintDrawer.add(source, position, sound.toString());
}
Sound gdxSound = sound.getSound();
gdxSound.play(volume, pitch, 0);
}
/**
* Plays a sound at a particular position. If the sound has an associated loop, this will loop the sound, coming
* from the entity.
* <p>
* {@code source} must not be null if the sound is specified to loop, and at least one of {@code source} or
* {@code position} must be specified.
*
* @param game Game to play the sound in
* @param playableSound The sound to play
* @param position Position to play the sound at
* @param soundSource Bearer of a sound. Must not be null for looped sounds.
*/
public void play(SolGame game, PlayableSound playableSound, @NotNull Vector2 position, @NotNull EntityRef soundSource) {
play(game, playableSound, position, soundSource, 1f);
}
/**
* Plays a sound at a particular position. If the sound has an associated loop, this will loop the sound, coming
* from the entity.
*
* @param game Game to play the sound in
* @param playableSound The sound to play
* @param position Position to play the sound at
* @param soundSource Bearer of a sound. Must not be null for looped sounds.
* @param volumeMultiplier Multiplier for sound volume
*/
public void play(SolGame game, PlayableSound playableSound, @NotNull Vector2 position, @NotNull EntityRef soundSource, float volumeMultiplier) {
if (playableSound == null) {
return;
}
if (soundSource == null || position == null) {
throw new AssertionError("Position and source must be non-null");
}
OggSound sound = playableSound.getOggSound();
float volume = getVolume(game, position, volumeMultiplier, sound);
if (volume <= 0) {
return;
}
// Calculate the pitch for the sound
float pitch = SolRandom.randomFloat(.97f, 1.03f) * game.getTimeFactor() * playableSound.getBasePitch();
if (skipLooped(soundSource, sound, game.getTime())) {
return;
}
if (DebugOptions.SOUND_INFO) {
debugHintDrawer.add(soundSource, position, sound.toString());
}
Sound gdxSound = sound.getSound();
gdxSound.play(volume, pitch, 0);
}
/**
* Calculates the volume a sound should be played at.
* This method takes several factors in account, more exactly: global game's volume, spreading of sound in vacuum
* (aka distance to atmosphere of a planet), distance to player, sound's volume multiplier, and volume multiplier
* passed in as an argument to the method.
*
* @param game Game to play this sound in.
* @param position Position to play the sound at.
* @param volumeMultiplier Special multiplier to multiply the resulting volume by.
* @param sound Sound to be played with the calculated volume.
* @return Volume the sound should play at.
*/
private float getVolume(SolGame game, Vector2 position, float volumeMultiplier, OggSound sound) {
float globalVolumeMultiplier = solApplication.getOptions().sfxVolume.getVolume();
Vector2 cameraPosition = solCam.getPosition();
Planet nearestPlanet = game.getPlanetManager().getNearestPlanet();
float airPercentage = 0;
if (nearestPlanet.getConfig().skyConfig != null) {
float distanceToAtmosphere = cameraPosition.dst(nearestPlanet.getPosition()) - nearestPlanet.getGroundHeight() - Const.ATM_HEIGHT / 2;
airPercentage = SolMath.clamp(1 - distanceToAtmosphere / (Const.ATM_HEIGHT / 2));
}
if (DebugOptions.SOUND_IN_SPACE) {
airPercentage = 1;
}
float maxSoundDist = 1 + 1.5f * Const.CAM_VIEW_DIST_GROUND * airPercentage;
Hero hero = game.getHero();
float soundRadius = hero.isTranscendent() ? 0 : hero.getHull().config.getApproxRadius();
float distance = position.dst(cameraPosition) - soundRadius;
float distanceMultiplier = SolMath.clamp(1 - distance / maxSoundDist);
return sound.getBaseVolume() * volumeMultiplier * distanceMultiplier * globalVolumeMultiplier;
}
/**
* Returns true when sound should not be played because of loop, false otherwise.
* <p>
* Sound should not be played when its {@code loopTime > 0} and {@code loopTime} time units have not yet passed
* since it was last played on the object.
* TODO: now handles even adding the sound to the list of looping sounds. Possibly extract that?
*
* @param source Object playing this sound.
* @param sound Sound to be played.
* @param time Game's current time.
* @return true when sound should not be played because of loop, false otherwise.
*/
private boolean skipLooped(SolObject source, OggSound sound, float time) {
if (sound.getLoopTime() == 0) {
return false;
}
Map<OggSound, Float> looped = loopedSoundMapOfSolObjects.get(source);
if (looped == null) {
looped = new HashMap<>();
loopedSoundMapOfSolObjects.put(source, looped);
return false;
} else {
Float endTime = looped.get(sound);
if (endTime == null || endTime <= time) {
looped.put(sound, time + sound.getLoopTime()); // argh, performance loss
return false;
} else {
return true;
}
}
}
/**
* Returns true when sound should not be played because of loop, false otherwise.
* <p>
* Sound should not be played when its {@code loopTime > 0} and {@code loopTime} time units have not yet passed
* since it was last played on the object.
* TODO: now handles even adding the sound to the list of looping sounds. Possibly extract that?
*
* @param source Object playing this sound.
* @param sound Sound to be played.
* @param time Game's current time.
* @return true when sound should not be played because of loop, false otherwise.
*/
private boolean skipLooped(EntityRef source, OggSound sound, float time) {
if (sound.getLoopTime() == 0) {
return false;
}
Map<OggSound, Float> looped = loopedSoundMapOfEntities.get(source);
if (looped == null) {
looped = new HashMap<>();
loopedSoundMapOfEntities.put(source, looped);
return false;
} else {
Float endTime = looped.get(sound);
if (endTime == null || endTime <= time) {
looped.put(sound, time + sound.getLoopTime()); // argh, performance loss
return false;
} else {
return true;
}
}
}
/**
* Draws info about recently played sounds in player proximity when {@link DebugOptions#SOUND_INFO} flag is set.
*
* @param drawer GameDrawer to use for drawing
* @param solCam Display information for drawing
*/
public void drawDebug(GameDrawer drawer, SolCam solCam) {
if (DebugOptions.SOUND_INFO) {
debugHintDrawer.draw(drawer, solCam);
}
}
/**
* Updates drawer used in {@link #drawDebug(GameDrawer, SolCam)} and removes unnecessary objects.
*
* @param game Game currently in progress.
*/
@Override
public void update(SolGame game, float timeStep) {
if (DebugOptions.SOUND_INFO) {
debugHintDrawer.update(game);
}
myLoopAwait -= timeStep;
if (myLoopAwait <= 0) {
myLoopAwait = 30;
cleanLooped(game);
}
}
/**
* Iterates {@link #loopedSoundMapOfSolObjects} and {@link #loopedSoundMapOfEntities} and removes any entries that
* are no longer in the game.
* <p>
* (See {@link SolObject#shouldBeRemoved(SolGame)} and {@link EntityRef#exists()})
*
* @param game Game currently in progress.
*/
private void cleanLooped(SolGame game) {
loopedSoundMapOfSolObjects.keySet().removeIf(o -> o.shouldBeRemoved(game));
loopedSoundMapOfEntities.keySet().removeIf(entity -> !entity.exists());
}
/**
* Handles deallocation of resources by the libGdx backend.
*/
public void dispose() {
for (OggSound sound : soundMap.values()) {
sound.doDispose();
}
}
}