Debian Codegraph @

CorsixTH/Src/th_lua_sound.cpp

raw
1 /*
2 Copyright (c) 2010 Peter "Corsix" Cawley
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #include "config.h"
24
25 #include <SDL_events.h>
26 #include <SDL_rwops.h>
27 #include <SDL_stdinc.h>
28 #include <SDL_timer.h>
29
30 #include <array>
31 #include <cctype>
32 #include <cstdio>
33 #include <map>
34 #include <utility>
35
36 #include "lua.hpp"
37 #include "lua_sdl.h"
38 #include "th_lua.h"
39 #include "th_lua_internal.h"
40 #include "th_sound.h"
41
42 namespace {
43
44 struct map_timer_info {
45 SDL_TimerID timer_id;
46 Uint32 interval;
47 Uint32 start_time;
48 int* callback_id_ptr;
49 };
50
51 std::array<int, 1000> played_sound_callback_ids;
52 int played_sound_callback_index = 0;
53 std::map<int, map_timer_info> map_sound_timers;
54
55 int l_soundarc_new(lua_State* L) {
56 luaT_stdnew<sound_archive>(L, luaT_environindex, true);
57 return 1;
58 }
59
60 int l_soundarc_load(lua_State* L) {
61 sound_archive* pArchive = luaT_testuserdata<sound_archive>(L);
62 size_t iDataLen;
63 const uint8_t* pData = luaT_checkfile(L, 2, &iDataLen);
64
65 if (pArchive->load_from_th_file(pData, iDataLen))
66 lua_pushboolean(L, 1);
67 else
68 lua_pushboolean(L, 0);
69 return 1;
70 }
71
72 int l_soundarc_count(lua_State* L) {
73 sound_archive* pArchive = luaT_testuserdata<sound_archive>(L);
74 lua_pushnumber(L, (lua_Number)pArchive->get_number_of_sounds());
75 return 1;
76 }
77
78 /**
79 * Perform case-insensitive string compare.
80 * @param s1 First string to compare.
81 * @param s2 Second string to compare.
82 * @return Negative number when \a s1 should be before \a s2, zero if both
83 * string are equal, else a positive number.
84 */
85 int ignorecase_cmp(const char* s1, const char* s2) {
86 while (*s1 && *s2) {
87 if (std::tolower(*s1) != std::tolower(*s2)) break;
88
89 s1++;
90 s2++;
91 }
92 return std::tolower(*s1) - std::tolower(*s2);
93 }
94
95 size_t l_soundarc_checkidx(lua_State* L, int iArg, sound_archive* pArchive) {
96 if (lua_isnumber(L, iArg)) {
97 size_t iIndex = (size_t)lua_tonumber(L, iArg);
98 if (iIndex >= pArchive->get_number_of_sounds()) {
99 lua_pushnil(L);
100 lua_pushfstring(L,
101 "Sound index out of "
102 "bounds (%f is not in range [0, %d])",
103 lua_tonumber(L, iArg),
104 static_cast<int>(pArchive->get_number_of_sounds()) - 1);
105 return pArchive->get_number_of_sounds();
106 }
107 return iIndex;
108 }
109 const char* sName = luaL_checkstring(L, iArg);
110 lua_getfenv(L, 1);
111 lua_pushvalue(L, iArg);
112 lua_rawget(L, -2);
113 if (lua_type(L, -1) == LUA_TNUMBER) {
114 size_t iIndex = static_cast<size_t>(lua_tointeger(L, -1));
115 lua_pop(L, 2);
116 return iIndex;
117 }
118 lua_pop(L, 2);
119 size_t iCount = pArchive->get_number_of_sounds();
120 for (size_t i = 0; i < iCount; ++i) {
121 if (ignorecase_cmp(sName, pArchive->get_sound_name(i)) == 0) {
122 lua_getfenv(L, 1);
123 lua_pushvalue(L, iArg);
124 lua_pushinteger(L, static_cast<lua_Integer>(i));
125 lua_settable(L, -3);
126 lua_pop(L, 1);
127 return i;
128 }
129 }
130 lua_pushnil(L);
131 lua_pushliteral(L, "File not found in sound archive: ");
132 lua_pushvalue(L, iArg);
133 lua_concat(L, 2);
134 return pArchive->get_number_of_sounds();
135 }
136
137 int l_soundarc_sound_name(lua_State* L) {
138 sound_archive* pArchive = luaT_testuserdata<sound_archive>(L);
139 size_t iIndex = l_soundarc_checkidx(L, 2, pArchive);
140 if (iIndex == pArchive->get_number_of_sounds()) return 2;
141 lua_pushstring(L, pArchive->get_sound_name(iIndex));
142 return 1;
143 }
144
145 int l_soundarc_duration(lua_State* L) {
146 sound_archive* pArchive = luaT_testuserdata<sound_archive>(L);
147 size_t iIndex = l_soundarc_checkidx(L, 2, pArchive);
148 if (iIndex == pArchive->get_number_of_sounds()) return 2;
149 size_t iDuration = pArchive->get_sound_duration(iIndex);
150 lua_pushnumber(
151 L, static_cast<lua_Number>(iDuration) / static_cast<lua_Number>(1000));
152 return 1;
153 }
154
155 int l_soundarc_data(lua_State* L) {
156 sound_archive* pArchive = luaT_testuserdata<sound_archive>(L);
157 size_t iIndex = l_soundarc_checkidx(L, 2, pArchive);
158 if (iIndex == pArchive->get_number_of_sounds()) return 2;
159 SDL_RWops* pRWops = pArchive->load_sound(iIndex);
160 if (!pRWops) return 0;
161 size_t iLength = SDL_RWseek(pRWops, 0, SEEK_END);
162 SDL_RWseek(pRWops, 0, SEEK_SET);
163 // There is a potential leak of pRWops if either of these Lua calls cause
164 // a memory error, but it isn't very likely, and this a debugging function
165 // anyway, so it isn't very important.
166 void* pBuffer = lua_newuserdata(L, iLength);
167 lua_pushlstring(L, (const char*)pBuffer,
168 SDL_RWread(pRWops, pBuffer, 1, iLength));
169 SDL_RWclose(pRWops);
170 return 1;
171 }
172
173 int l_soundarc_sound_exists(lua_State* L) {
174 sound_archive* pArchive = luaT_testuserdata<sound_archive>(L);
175 size_t iIndex = l_soundarc_checkidx(L, 2, pArchive);
176 if (iIndex == pArchive->get_number_of_sounds())
177 lua_pushboolean(L, 0);
178 else
179 lua_pushboolean(L, 1);
180 return 1;
181 }
182
183 int l_soundfx_new(lua_State* L) {
184 luaT_stdnew<sound_player>(L, luaT_environindex, true);
185 return 1;
186 }
187
188 int l_soundfx_set_archive(lua_State* L) {
189 sound_player* pEffects = luaT_testuserdata<sound_player>(L);
190 sound_archive* pArchive = luaT_testuserdata<sound_archive>(L, 2);
191 pEffects->populate_from(pArchive);
192 lua_settop(L, 2);
193 luaT_setenvfield(L, 1, "archive");
194 return 1;
195 }
196
197 int l_soundfx_set_sound_volume(lua_State* L) {
198 sound_player* pEffects = luaT_testuserdata<sound_player>(L);
199 pEffects->set_sound_effect_volume(luaL_checknumber(L, 2));
200 return 1;
201 }
202
203 int l_soundfx_set_sound_effects_on(lua_State* L) {
204 sound_player* pEffects = luaT_testuserdata<sound_player>(L);
205 pEffects->set_sound_effects_enabled(lua_toboolean(L, 2) != 0);
206 return 1;
207 }
208
209 Uint32 played_sound_callback(Uint32 interval, void* param) {
210 SDL_Event e;
211 e.type = SDL_USEREVENT_SOUND_OVER;
212 e.user.data1 = param;
213 int iSoundID = *(static_cast<int*>(param));
214 SDL_RemoveTimer(map_sound_timers[iSoundID].timer_id);
215 map_sound_timers.erase(iSoundID);
216 SDL_PushEvent(&e);
217
218 return interval;
219 }
220
221 int l_soundfx_play(lua_State* L) {
222 sound_player* pEffects = luaT_testuserdata<sound_player>(L);
223
224 // Get the current sound_archive. We don't want to disrupt the lua stack
225 // so we put this after any possible argument.
226 lua_settop(L, 8);
227 lua_getfenv(L, 1);
228 lua_pushliteral(L, "archive");
229 lua_rawget(L, 9);
230 sound_archive* pArchive = (sound_archive*)lua_touserdata(L, 10);
231 if (pArchive == nullptr) {
232 return 0;
233 }
234 // l_soundarc_checkidx requires the archive at the bottom of the stack
235 // so we swap with sound_player
236 lua_replace(L, 1);
237 size_t iIndex = l_soundarc_checkidx(L, 2, pArchive);
238 if (iIndex == pArchive->get_number_of_sounds()) return 2;
239
240 double volume = luaL_checknumber(L, 3);
241 int loops = static_cast<int>(luaL_optinteger(L, 8, 0));
242
243 uint32_t handle;
244 if (lua_isnil(L, 4)) {
245 handle = pEffects->play(iIndex, volume, loops);
246 } else {
247 handle = pEffects->play_at(
248 iIndex, volume, static_cast<int>(luaL_checkinteger(L, 4)),
249 static_cast<int>(luaL_checkinteger(L, 5)), loops);
250 }
251 // SDL SOUND_OVER Callback Timer:
252 // 6: unusedPlayedCallbackID
253 if (!lua_isnil(L, 6) && loops >= 0) {
254 // 7: Callback delay
255 int iPlayedCallbackDelay = 0; // ms
256 if (!lua_isnil(L, 7))
257 iPlayedCallbackDelay = static_cast<int>(luaL_checknumber(L, 7));
258
259 if (played_sound_callback_index == played_sound_callback_ids.size())
260 played_sound_callback_index = 0;
261
262 played_sound_callback_ids[played_sound_callback_index] =
263 static_cast<int>(luaL_checkinteger(L, 6));
264 int& callback_id = played_sound_callback_ids[played_sound_callback_index];
265
266 Uint32 interval =
267 static_cast<Uint32>(pArchive->get_sound_duration(iIndex) * (loops + 1) +
268 iPlayedCallbackDelay);
269 SDL_TimerID timersID =
270 SDL_AddTimer(interval, played_sound_callback, &callback_id);
271 map_sound_timers.emplace(std::pair<int, map_timer_info>(
272 callback_id, {timersID, interval, SDL_GetTicks(), &callback_id}));
273 played_sound_callback_index++;
274 }
275
276 lua_pushinteger(L, handle);
277 return 1;
278 }
279
280 int l_soundfx_toggle_pause(lua_State* L) {
281 sound_player* pEffects = luaT_testuserdata<sound_player>(L);
282 const sound_player::toggle_pause_result pauseResult =
283 pEffects->toggle_pause(static_cast<int>(luaL_checkinteger(L, 2)));
284 int callbackId = static_cast<int>(luaL_optinteger(L, 3, -1));
285
286 if (auto itr = map_sound_timers.find(callbackId);
287 itr != map_sound_timers.end()) {
288 switch (pauseResult) {
289 case sound_player::toggle_pause_result::paused: {
290 Uint32 elapsed = SDL_GetTicks() - itr->second.start_time;
291 itr->second.interval -= elapsed;
292 SDL_RemoveTimer(itr->second.timer_id);
293 break;
294 }
295 case sound_player::toggle_pause_result::resumed:
296 itr->second.start_time = SDL_GetTicks();
297 itr->second.timer_id =
298 SDL_AddTimer(itr->second.interval, played_sound_callback,
299 itr->second.callback_id_ptr);
300 break;
301 case sound_player::toggle_pause_result::error:
302 // Do nothing with callback on error
303 break;
304 };
305 }
306
307 return 0;
308 }
309
310 int l_soundfx_stop(lua_State* L) {
311 sound_player* pEffects = luaT_testuserdata<sound_player>(L);
312 pEffects->stop(static_cast<int>(luaL_checkinteger(L, 2)));
313 int callbackId = static_cast<int>(luaL_optinteger(L, 3, -1));
314
315 if (auto itr = map_sound_timers.find(callbackId);
316 itr != map_sound_timers.end()) {
317 SDL_RemoveTimer(itr->second.timer_id);
318 map_sound_timers.erase(itr);
319 }
320 return 0;
321 }
322
323 int l_soundfx_is_playing(lua_State* L) {
324 sound_player* pEffects = luaT_testuserdata<sound_player>(L);
325 bool isPlaying =
326 pEffects->is_playing(static_cast<int>(luaL_checkinteger(L, 2)));
327 lua_pushboolean(L, isPlaying);
328 return 1;
329 }
330
331 int l_soundfx_set_camera(lua_State* L) {
332 sound_player* pEffects = luaT_testuserdata<sound_player>(L);
333 pEffects->set_camera(static_cast<int>(luaL_checkinteger(L, 2)),
334 static_cast<int>(luaL_checkinteger(L, 3)),
335 static_cast<int>(luaL_checkinteger(L, 4)));
336 return 0;
337 }
338
339 int l_soundfx_reserve_channel(lua_State* L) {
340 int iChannel;
341 sound_player* pEffects = luaT_testuserdata<sound_player>(L);
342 iChannel = pEffects->reserve_channel();
343 lua_pushinteger(L, iChannel);
344 return 1;
345 }
346
347 int l_soundfx_release_channel(lua_State* L) {
348 sound_player* pEffects = luaT_testuserdata<sound_player>(L);
349 pEffects->release_channel(static_cast<int>(luaL_checkinteger(L, 2)));
350 return 1;
351 }
352
353 } // namespace
354
355 void lua_register_sound(const lua_register_state* pState) {
356 // Sound Archive
357 {
358 lua_class_binding<sound_archive> lcb(pState, "soundArchive", l_soundarc_new,
359 lua_metatable::sound_archive);
360 lcb.add_metamethod(l_soundarc_count, "len");
361 lcb.add_function(l_soundarc_load, "load");
362 lcb.add_function(l_soundarc_sound_name,
363 "getFilename"); // Bad name, doesn't represent a file
364 lcb.add_function(l_soundarc_duration, "getDuration");
365 lcb.add_function(l_soundarc_data,
366 "getFileData"); // Bad name, doesn't represent a file
367 lcb.add_function(l_soundarc_sound_exists, "soundExists");
368 }
369
370 // Sound Effects
371 {
372 lua_class_binding<sound_player> lcb(pState, "soundEffects", l_soundfx_new,
373 lua_metatable::sound_fx);
374 lcb.add_function(l_soundfx_set_archive, "setSoundArchive",
375 lua_metatable::sound_archive);
376 lcb.add_function(l_soundfx_play, "play");
377 lcb.add_function(l_soundfx_toggle_pause, "togglePause");
378 lcb.add_function(l_soundfx_stop, "stop");
379 lcb.add_function(l_soundfx_is_playing, "isPlaying");
380 lcb.add_function(l_soundfx_set_sound_volume, "setSoundVolume");
381 lcb.add_function(l_soundfx_set_sound_effects_on, "setSoundEffectsOn");
382 lcb.add_function(l_soundfx_set_camera, "setCamera");
383 lcb.add_function(l_soundfx_reserve_channel, "reserveChannel");
384 lcb.add_function(l_soundfx_release_channel, "releaseChannel");
385 }
386 }