1#include "mapsounds.h"
2
3#include <base/log.h>
4
5#include <engine/demo.h>
6#include <engine/shared/config.h>
7#include <engine/sound.h>
8
9#include <game/client/components/camera.h>
10#include <game/client/components/sounds.h>
11#include <game/client/gameclient.h>
12#include <game/layers.h>
13#include <game/localization.h>
14#include <game/mapitems.h>
15
16CMapSounds::CMapSounds()
17{
18 m_Count = 0;
19}
20
21void CMapSounds::Play(int Channel, int SoundId)
22{
23 if(!SoundEnabled())
24 return;
25 if(SoundId < 0 || SoundId >= m_Count)
26 return;
27
28 GameClient()->m_Sounds.PlaySample(Channel, SampleId: m_aSounds[SoundId], Flags: 0, Volume: 1.0f);
29}
30
31void CMapSounds::PlayAt(int Channel, int SoundId, vec2 Position)
32{
33 if(!SoundEnabled())
34 return;
35 if(SoundId < 0 || SoundId >= m_Count)
36 return;
37
38 GameClient()->m_Sounds.PlaySampleAt(Channel, SampleId: m_aSounds[SoundId], Flags: 0, Volume: 1.0f, Position);
39}
40
41void CMapSounds::StopAll()
42{
43 for(auto &Source : m_vSourceQueue)
44 {
45 Sound()->StopVoice(Voice: Source.m_Voice);
46 Source.m_Voice = ISound::CVoiceHandle();
47 }
48}
49
50void CMapSounds::OnMapLoad()
51{
52 IMap *pMap = GameClient()->Map();
53
54 Clear();
55
56 if(!Sound()->IsSoundEnabled())
57 return;
58
59 // load samples
60 int Start;
61 pMap->GetType(Type: MAPITEMTYPE_SOUND, pStart: &Start, pNum: &m_Count);
62
63 m_Count = std::clamp<int>(val: m_Count, lo: 0, hi: MAX_MAPSOUNDS);
64
65 // load new samples
66 bool ShowWarning = false;
67 for(int i = 0; i < m_Count; i++)
68 {
69 CMapItemSound *pSound = (CMapItemSound *)pMap->GetItem(Index: Start + i);
70 const char *pName = pMap->GetDataString(Index: pSound->m_SoundName);
71 if(pName == nullptr || pName[0] == '\0')
72 {
73 if(pSound->m_External)
74 {
75 log_error("mapsounds", "Failed to load map sound %d: failed to load name.", i);
76 ShowWarning = true;
77 m_aSounds[i] = -1;
78 continue;
79 }
80 pName = "(error)";
81 }
82
83 if(pSound->m_External)
84 {
85 char aBuf[IO_MAX_PATH_LENGTH];
86 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "mapres/%s.opus", pName);
87 m_aSounds[i] = Sound()->LoadOpus(pFilename: aBuf);
88 pMap->UnloadData(Index: pSound->m_SoundName);
89 }
90 else
91 {
92 const void *pData = pMap->GetData(Index: pSound->m_SoundData);
93 if(pData == nullptr)
94 {
95 log_error("mapsounds", "Failed to load map sound %d: failed to load data.", i);
96 ShowWarning = true;
97 m_aSounds[i] = -1;
98 continue;
99 }
100 const int SoundDataSize = pMap->GetDataSize(Index: pSound->m_SoundData);
101 m_aSounds[i] = Sound()->LoadOpusFromMem(pData, DataSize: SoundDataSize, ForceLoad: false, pContextName: pName);
102 pMap->UnloadData(Index: pSound->m_SoundData);
103 }
104 ShowWarning = ShowWarning || m_aSounds[i] == -1;
105 }
106 if(ShowWarning)
107 {
108 Client()->AddWarning(Warning: SWarning(Localize(pStr: "Some map sounds could not be loaded. Check the local console for details.")));
109 }
110
111 // enqueue sound sources
112 for(int GroupIndex = 0; GroupIndex < Layers()->NumGroups(); GroupIndex++)
113 {
114 const CMapItemGroup *pGroup = Layers()->GetGroup(Index: GroupIndex);
115 if(!pGroup)
116 continue;
117
118 for(int LayerIndex = 0; LayerIndex < pGroup->m_NumLayers; LayerIndex++)
119 {
120 const CMapItemLayer *pLayer = Layers()->GetLayer(Index: pGroup->m_StartLayer + LayerIndex);
121 if(!pLayer)
122 continue;
123 if(pLayer->m_Type != LAYERTYPE_SOUNDS)
124 continue;
125
126 const CMapItemLayerSounds *pSoundLayer = reinterpret_cast<const CMapItemLayerSounds *>(pLayer);
127 if(pSoundLayer->m_Version < 1 || pSoundLayer->m_Version > 2)
128 continue;
129 if(pSoundLayer->m_Sound < 0 || pSoundLayer->m_Sound >= m_Count || m_aSounds[pSoundLayer->m_Sound] == -1)
130 continue;
131
132 const CSoundSource *pSources = static_cast<CSoundSource *>(Layers()->Map()->GetDataSwapped(Index: pSoundLayer->m_Data));
133 if(!pSources)
134 continue;
135
136 const size_t NumSources = std::min(a: (size_t)pSoundLayer->m_NumSources, b: (size_t)Layers()->Map()->GetDataSize(Index: pSoundLayer->m_Data) / sizeof(CSoundSource));
137 for(size_t SourceIndex = 0; SourceIndex < NumSources; SourceIndex++)
138 {
139 CSourceQueueEntry Source;
140 Source.m_Sound = pSoundLayer->m_Sound;
141 Source.m_HighDetail = pLayer->m_Flags & LAYERFLAG_DETAIL;
142 Source.m_pGroup = pGroup;
143 Source.m_pSource = &pSources[SourceIndex];
144 m_vSourceQueue.push_back(x: Source);
145 }
146 }
147 }
148}
149
150void CMapSounds::OnRender()
151{
152 if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK)
153 return;
154
155 const bool DemoPlayerPaused = GameClient()->IsDemoPlaybackPaused();
156
157 // enqueue sounds
158 for(auto &Source : m_vSourceQueue)
159 {
160 static float s_Time = 0.0f;
161 if(GameClient()->m_Snap.m_pGameInfoObj)
162 {
163 s_Time = mix(a: (Client()->PrevGameTick(Conn: g_Config.m_ClDummy) - GameClient()->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)Client()->GameTickSpeed(),
164 b: (Client()->GameTick(Conn: g_Config.m_ClDummy) - GameClient()->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)Client()->GameTickSpeed(),
165 amount: Client()->IntraGameTick(Conn: g_Config.m_ClDummy));
166 }
167 float Offset = s_Time - Source.m_pSource->m_TimeDelay;
168 if(!DemoPlayerPaused && Offset >= 0.0f && g_Config.m_SndEnable && (g_Config.m_GfxHighDetail || !Source.m_HighDetail))
169 {
170 if(Source.m_Voice.IsValid())
171 {
172 // currently playing, set offset
173 Sound()->SetVoiceTimeOffset(Voice: Source.m_Voice, TimeOffset: Offset);
174 }
175 else
176 {
177 // need to enqueue
178 int Flags = 0;
179 if(Source.m_pSource->m_Loop)
180 Flags |= ISound::FLAG_LOOP;
181 if(!Source.m_pSource->m_Pan)
182 Flags |= ISound::FLAG_NO_PANNING;
183
184 Source.m_Voice = GameClient()->m_Sounds.PlaySampleAt(Channel: CSounds::CHN_MAPSOUND, SampleId: m_aSounds[Source.m_Sound], Flags, Volume: 1.0f, Position: vec2(fx2f(v: Source.m_pSource->m_Position.x), fx2f(v: Source.m_pSource->m_Position.y)));
185 Sound()->SetVoiceTimeOffset(Voice: Source.m_Voice, TimeOffset: Offset);
186 Sound()->SetVoiceFalloff(Voice: Source.m_Voice, Falloff: Source.m_pSource->m_Falloff / 255.0f);
187 switch(Source.m_pSource->m_Shape.m_Type)
188 {
189 case CSoundShape::SHAPE_CIRCLE:
190 {
191 Sound()->SetVoiceCircle(Voice: Source.m_Voice, Radius: Source.m_pSource->m_Shape.m_Circle.m_Radius);
192 break;
193 }
194
195 case CSoundShape::SHAPE_RECTANGLE:
196 {
197 Sound()->SetVoiceRectangle(Voice: Source.m_Voice, Width: fx2f(v: Source.m_pSource->m_Shape.m_Rectangle.m_Width), Height: fx2f(v: Source.m_pSource->m_Shape.m_Rectangle.m_Height));
198 break;
199 }
200 };
201 }
202 }
203 else
204 {
205 // stop voice
206 Sound()->StopVoice(Voice: Source.m_Voice);
207 Source.m_Voice = ISound::CVoiceHandle();
208 }
209 }
210
211 CEnvelopeState &EnvEvaluator = GameClient()->m_MapLayersBackground.EnvEvaluator();
212 EnvEvaluator.Update();
213
214 const vec2 Center = GameClient()->m_Camera.m_Center;
215 for(const auto &Source : m_vSourceQueue)
216 {
217 if(!Source.m_Voice.IsValid())
218 continue;
219
220 ColorRGBA Position = ColorRGBA(0.0f, 0.0f, 0.0f, 0.0f);
221 EnvEvaluator.EnvelopeEval(TimeOffsetMillis: Source.m_pSource->m_PosEnvOffset, EnvelopeIndex: Source.m_pSource->m_PosEnv, Result&: Position, Channels: 2);
222
223 float x = fx2f(v: Source.m_pSource->m_Position.x) + Position.r;
224 float y = fx2f(v: Source.m_pSource->m_Position.y) + Position.g;
225
226 x += Center.x * (1.0f - Source.m_pGroup->m_ParallaxX / 100.0f);
227 y += Center.y * (1.0f - Source.m_pGroup->m_ParallaxY / 100.0f);
228
229 x -= Source.m_pGroup->m_OffsetX;
230 y -= Source.m_pGroup->m_OffsetY;
231
232 Sound()->SetVoicePosition(Voice: Source.m_Voice, Position: vec2(x, y));
233
234 ColorRGBA Volume = ColorRGBA(1.0f, 0.0f, 0.0f, 0.0f);
235 EnvEvaluator.EnvelopeEval(TimeOffsetMillis: Source.m_pSource->m_SoundEnvOffset, EnvelopeIndex: Source.m_pSource->m_SoundEnv, Result&: Volume, Channels: 1);
236
237 Sound()->SetVoiceVolume(Voice: Source.m_Voice, Volume: std::clamp(val: Volume.r, lo: 0.0f, hi: 1.0f));
238 }
239}
240
241void CMapSounds::Clear()
242{
243 // unload all samples
244 m_vSourceQueue.clear();
245 for(int i = 0; i < m_Count; i++)
246 {
247 Sound()->UnloadSample(SampleId: m_aSounds[i]);
248 m_aSounds[i] = -1;
249 }
250 m_Count = 0;
251}
252
253void CMapSounds::OnStateChange(int NewState, int OldState)
254{
255 if(NewState < IClient::STATE_ONLINE)
256 Clear();
257}
258
259bool CMapSounds::SoundEnabled()
260{
261 return g_Config.m_SndGame && g_Config.m_SndEnable;
262}
263