fork/m-overlay

git clone https://git.julia.blue/fork/m-overlay

BkacjiosMerge branch 'tmp' into settings-overhaulf7324a4

settings-overhaul
15.1 KiB495 linesraw
1local music = {
2	PLAYLIST = {},
3	PLAYLIST_ID = -1,
4	PLAYING = nil,
5	FINISHED = true,
6	LOOP = false,
7	USE_WEIGHTS = false,
8	TRACK_ID = {},
9	RNG_SEED = nil,
10}
11
12local log = require("log")
13local melee = require("melee")
14local memory = require("memory")
15local notification = require("notification")
16local overlay = require("overlay")
17local wav = require("wav")
18
19require("extensions.math")
20
21-- Given a list of {element, weight} pairs, do a weighted random sample
22-- of the elements (returns an index, not the element itself)
23local function weightedRandomChoice(list)
24	if not list or #list == 0 then return nil end
25	if #list == 1 then return 1 end
26
27	local sum = 0
28	for _, v in pairs(list) do
29		sum = sum + v.WEIGHT
30	end
31
32	local choice = math.random(1, sum)
33	for k, v in pairs(list) do
34		choice = choice - v.WEIGHT
35		if choice <= 0 then
36			return k
37		end
38	end
39	return choice
40end
41
42local function moveFolderContentsTo(from, to)
43	local info = love.filesystem.getInfo(from)
44
45	if info and info.type == "directory" then
46		-- Upgrade to new folder layout
47		local configdir = love.filesystem.getSaveDirectory()
48
49		local files = love.filesystem.getDirectoryItems(from)
50		for k, file in ipairs(files) do
51			os.rename(("%s/%s/%s"):format(configdir, from, file), ("%s/%s/%s"):format(configdir, to, file))
52		end
53
54		love.filesystem.remove(from)
55	end
56end
57
58function music.update()
59	if not music.PLAYING or music.FINISHED then return end
60
61	local duration = music.PLAYING.STREAM:getDuration("samples")
62	local position = music.PLAYING.STREAM:tell("samples")
63
64	if music.LOOP then
65		local finished = not music.PLAYING.STREAM:isPlaying()
66
67		if finished then
68			-- If the song is no longer playing, that means it reached the end
69			-- Immediately play it again
70			log.debug("[MUSIC] End of song reached, replaying")
71			music.PLAYING.STREAM:play()
72		end
73
74		local info = music.PLAYING.WAV
75
76		if info then
77			for k, loop in pairs(info.loops) do
78				if finished or position >= loop.sample_end then
79					log.debug("[MUSIC] Loop point reached, seeking to %d", loop.sample_start)
80					-- If the song finished playing or reached the looping point, loop back to the start?
81					music.PLAYING.STREAM:seek(loop.sample_start, "samples")
82					break -- Only handle the first loop for now..
83				end
84			end
85		end
86	else
87		if not music.PLAYING.STREAM:isPlaying() or position >= duration then
88			-- We mark that the song has completed, allowing the next game frame hook to play the next song in the playlist
89			music.FINISHED = true
90		end
91	end
92end
93
94function music.init()
95	love.filesystem.createDirectory("Melee")
96
97	local info = love.filesystem.getInfo("Stage Music")
98
99	if info and info.type == "directory" then
100		-- Upgrade to new folder layout
101		local configdir = love.filesystem.getSaveDirectory()
102		os.rename(("%s/Stage Music"):format(configdir), ("%s/Melee/Stage Music"):format(configdir))
103	end
104
105	local info = love.filesystem.getInfo("Melee/Stage Music/Menu")
106
107	if info and info.type == "directory" then
108		-- Upgrade to new folder layout
109		local configdir = love.filesystem.getSaveDirectory()
110		os.rename(("%s/Melee/Stage Music/Menu"):format(configdir), ("%s/Melee/Menu Music"):format(configdir))
111	else
112		love.filesystem.createDirectory("Melee/Menu Music")
113	end
114
115	-- VS mode folders
116
117	for stageid, name in pairs(melee.getAllStages()) do
118		love.filesystem.createDirectory(("Melee/Stage Music/%s"):format(name))
119	end
120	moveFolderContentsTo("Melee/Stage Music/All", "Melee/Stage Music")
121
122	-- Single player folders
123
124	love.filesystem.createDirectory("Melee/Single Player Music")
125	
126	for stageid, name in pairs(melee.getSinglePlayerStages()) do
127		love.filesystem.createDirectory(("Melee/Single Player Music/%s"):format(name))
128	end
129
130	-- Series folders
131
132	for stageid, series in pairs(melee.getAllStageSeries()) do
133		love.filesystem.createDirectory(("Melee/Series Music/%s"):format(series))
134	end
135	moveFolderContentsTo("Melee/Series Music/All", "Melee/Series Music")
136
137	love.filesystem.createDirectory("Melee/Single Player Music/Break the Targets")
138
139	for stageid, name in pairs(melee.getAkaneiaStages()) do
140		love.filesystem.createDirectory(("Melee/Akaneia Stage Music/%s"):format(name))
141	end
142	for stageid, name in pairs(melee.getBeyondMeleeStages()) do
143		love.filesystem.createDirectory(("Melee/Beyond Melee Stage Music/%s"):format(name))
144	end
145end
146
147function music.kill()
148	if music.PLAYING then
149		if music.PLAYING.STREAM then
150			if music.PLAYING.STREAM:isPlaying() then
151				music.PLAYING.STREAM:stop()
152				music.FINISHED = true
153			end
154			music.PLAYING.STREAM:release()
155		end
156		music.PLAYING = nil
157	end
158end
159
160local LOOPING_OFF = 1
161local LOOPING_MENU = 2
162local LOOPING_STAGE = 3
163local LOOPING_ALL = 4
164
165-- Set to true when the announcer says 'GAME!'
166local MATCH_SOFT_END = false
167
168function music.shouldPlayMusic()
169	return melee.isInMenus() or (melee.isInGame() and not melee.matchFinsihed() and not MATCH_SOFT_END)
170end
171
172function music.onLoopChange(mode)
173	if music.PLAYING and music.PLAYING.STREAM:isPlaying() then
174		local loop = false
175		-- Handle the different loop settings properly
176		if mode == LOOPING_MENU and melee.isInMenus() then
177			loop = true
178		elseif mode == LOOPING_STAGE and melee.isInGame() then
179			loop = true
180		elseif mode == LOOPING_ALL then
181			loop = true
182		end
183		--music.PLAYING.STREAM:setLooping(loop)
184		music.LOOP = loop
185	end
186end
187
188function music.getVolume()
189	return PANEL_SETTINGS:GetVolume()
190end
191
192local LOADED = false
193local ALLOW_INGAME_VOLUME = false
194
195memory.hook("OnGameClosed", "Set state unloaded", function()
196	LOADED = false
197end)
198
199memory.hook("menu.major", "Load Initial Volume", function(menu)
200	if memory.isMelee() and ALLOW_INGAME_VOLUME and not LOADED and menu == MENU_MAIN_MENU then
201		LOADED = true
202		-- Set the games music value to our value
203		music.setVolume(music.getVolume())
204	end
205end)
206
207memory.hook("volume.slider", "Ingame Volume Adjust", function(volume)
208	if memory.isMelee() and ALLOW_INGAME_VOLUME and LOADED then
209		PANEL_SETTINGS:SetVolume(100-volume)
210	end
211end)
212
213function music.refreshRNGseed()
214	local getSeed = function()
215		if not music.RNG_SEED or not memory.isMelee() then return os.time(), "the system time" end
216		if melee.isInMenus() then return music.RNG_SEED + 1, "the previous seed" end
217		if melee.isNetplayGame() then return memory.online.rng_offset, "Slippi" end
218		return memory.rng.seed, "Melee"
219	end
220
221	local seed, source = getSeed()
222	math.randomseed(seed)
223	music.RNG_SEED = seed
224	log.debug("[RANDOM] Obtained seed \"0x%X\" from %s", seed, source)
225end
226
227function music.setVolume(vol)
228	if ALLOW_INGAME_VOLUME and memory.isMelee() then
229		-- Melee's slider goes in increments of 5
230		-- It seems to add +5 or -5 no matter what, but it can actually take numbers in between and still work
231		--local nearest5 = math.round((100-vol) / 5)*5
232
233		-- volume.slider adjust (0-100)
234		memory.writeByte(0x8045C384, math.round(100-vol))
235
236		-- volume.music adjust (0-127)
237		memory.writeByte(0x804D3887, (vol/100) * 127)
238	end
239
240	if music.PLAYING and music.PLAYING.STREAM:isPlaying() then
241		music.PLAYING.STREAM:setVolume((vol/100) * (memory.match.paused and 0.35 or 1))
242	end
243end
244
245do
246local function getNextTrack(songs)
247	if music.USE_WEIGHTS then
248		local track_id = weightedRandomChoice(songs)
249		return track_id, track_id
250	end
251
252	music.TRACK_ID[music.PLAYLIST_ID] = ((music.TRACK_ID[music.PLAYLIST_ID] or -1) + 1) % #songs
253	local track_id = music.TRACK_ID[music.PLAYLIST_ID] + 1
254
255	-- Only shuffle if we have more than 2 songs..
256	if #songs > 2 then
257		-- Every time we play a song, we randomly place it towards the start of the playlist
258		-- This keeps the playlist in a constantly shuffled order
259		local track = table.remove(songs, track_id)
260		local newpos = math.random(1, track_id)
261		table.insert(songs, newpos, track)
262		return track_id, newpos
263	end
264
265	return track_id, track_id
266end
267
268local function loadTrack(songs, index)
269	local track_info = songs[index]
270
271	local filepath = track_info.FILEPATH
272
273	local success, source = pcall(love.audio.newSource, filepath, "stream")
274	if not (success and source) then
275		local err = ("invalid music file %q"):format(filepath)
276		log.error("[MUSIC] %s", err)
277		notification.error(err)
278		table.remove(songs, index)
279		return nil
280	end
281
282	return { STREAM = source, WAV = track_info.IS_WAV and wav.parse(filepath) or nil }
283end
284
285function music.playNextTrack()
286	if not memory.isMelee() or not PANEL_SETTINGS:PlayStageMusic() then return end
287	if music.PLAYING ~= nil and not music.FINISHED then return end
288	if not music.PLAYLIST_ID then return end
289	if not music.shouldPlayMusic() then return end
290
291	local songs = music.PLAYLIST
292
293	if #songs > 0 then
294		local track_id, track_index = getNextTrack(songs)
295
296		if not track_index then return end
297
298		music.PLAYING = loadTrack(songs, track_index)
299		
300		if music.PLAYING then
301			if music.PLAYLIST_ID == 0x0 then
302				log.info("[MUSIC] Playing track #%d for menu", track_id)
303			else
304				log.info("[MUSIC] Playing track #%d for stage %q", track_id, melee.getStageName(music.PLAYLIST_ID))
305			end
306
307			local loop = PANEL_SETTINGS:GetMusicLoopMode()
308
309			if music.PLAYLIST_ID == 0 then
310				music.LOOP = loop == LOOPING_MENU or loop == LOOPING_ALL
311			else
312				music.LOOP = loop == LOOPING_STAGE or loop == LOOPING_ALL
313			end
314
315			music.PLAYING.STREAM:setVolume((PANEL_SETTINGS:GetVolume()/100) * (memory.match.paused and 0.35 or 1))
316			music.PLAYING.STREAM:play()
317			music.FINISHED = false
318		end
319	end
320end
321end
322
323function music.onStateChange()
324	if melee.isInGame() then
325		music.loadForStage(memory.stage)
326	elseif melee.isInMenus() then
327		music.loadForStage(0)
328	end
329end
330
331memory.hook("frame", "Melee - Music Think", music.playNextTrack)
332
333memory.hook("OnGameClosed", "Dolphin - Game closed", function()
334	music.kill()
335end)
336
337memory.hook("menu.major", "Melee - Menu state", function(menu)
338	if melee.isInMenus() then
339		music.loadForStage(0)
340	elseif not melee.isInGame() then
341		music.kill()
342	end
343end)
344
345memory.hook("menu.minor", "Melee - Menu state", function(menu)
346	if melee.isInMenus() then
347		music.loadForStage(0)
348	elseif melee.isInGame() then
349		MATCH_SOFT_END = false
350		music.loadForStage(memory.stage)
351	else
352		music.kill()
353	end
354end)
355
356memory.hook("stage", "Melee - Stage loaded", function(stage)
357	if melee.isInGame() then
358		music.loadForStage(stage)
359	end
360end)
361
362memory.hook("match.playing", "Melee - Classic Mode Master Hand Fix?", function(playing)
363	-- In classic mode, when you kill masterhand the match result is never set, but the "playing" flag is set to false.
364	-- Mute the music right when masterhand is killed.
365	if not playing and (memory.menu.major == MENU_CLASSIC_MODE and memory.stage == 0x25) then
366		MATCH_SOFT_END = true
367		music.kill()
368	end
369end)
370
371memory.hook("match.paused", "Melee - Pause volume", function(paused)
372	music.setVolume(music.getVolume())
373end)
374
375memory.hook("match.finished", "Melee - GAME kill music", function(finished)
376	if finished then
377		-- The match ended, so no matter what the music should be killed
378		music.kill()
379	end
380end)
381
382memory.hook("match.result", "Melee - GAME kill music", function(result)
383	-- LRAB+Start/Saltyrunback causes a result of MATCH_NO_CONTEST.. We don't want to end the music in this case only.
384	-- The match.finished hook will end the music instead when actually exiting the match using normal LRA+Start.
385	-- If the match actually ends normally, we kill the music early when it announces the end of the game.
386
387	if result ~= MATCH_NO_RESULT and (memory.menu.major ~= MENU_VS_MODE or (memory.menu.major == MENU_VS_MODE and result ~= MATCH_NO_CONTEST)) then
388		MATCH_SOFT_END = true
389		music.kill()
390	end
391end)
392
393memory.hook("controller.*.buttons.pressed", "Melee - Music skipper", function(port, pressed)
394	if PANEL_SETTINGS:IsBinding() or PANEL_SETTINGS:IsSlippiReplay() then return end -- Don't skip when the user is setting a button combination or when watching a replay
395	local mask = PANEL_SETTINGS:GetMusicSkipMask()
396	if mask ~= 0x0 and port == overlay.getPort() and pressed == mask and #music.PLAYLIST > 1 then
397		log.debug("[MUSIC] [MASK = 0x%X] Button combo pressed, stopping music.", mask)
398		music.kill()
399	end
400end)
401
402local valid_music_ext = {
403	["mp3"] = true,
404	["ogg"] = true,
405	["wav"] = true,
406	["flac"] = true
407}
408
409function music.loadPlaylistForStage(stageid, name)
410	local found = 0
411	local files = love.filesystem.getDirectoryItems(name)
412	table.sort(files) -- Sort our list of files alphabetically, giving our table a deterministic state
413	for k, file in ipairs(files) do
414		local filepath = ("%s/%s"):format(name, file)
415		local info = love.filesystem.getInfo(filepath)
416		if info then
417			if info.type == "file" then
418				local ext = string.getFileExtension(file):lower()
419
420				if valid_music_ext[ext] then
421					found = found + 1
422
423					-- Insert the newly found track into a random position in the playlist
424					local pos = math.random(1, #music.PLAYLIST)
425					local prob = tonumber(string.match(filepath, ".-_(%d+)%.%w+$")) or 1
426
427					if prob > 1 then
428						music.USE_WEIGHTS = true
429					end
430
431					table.insert(music.PLAYLIST, pos, {FILEPATH = filepath, WEIGHT = prob, IS_WAV = ext == "wav"})
432				end
433			end
434		else
435			log.warn("[MUSIC] Unable to get file information for file %q", filepath)
436		end
437	end
438	if found > 0 then
439		log.info("[MUSIC] Found %d songs in %q", found, name)
440	end
441end
442
443function music.loadForStage(stageid)
444	if music.PLAYLIST_ID == stageid then return end
445
446	music.kill()
447	if not memory.isMelee() or not PANEL_SETTINGS:PlayStageMusic() then return end
448
449	music.PLAYLIST_ID = stageid
450	music.PLAYLIST = {}
451	music.USE_WEIGHTS = false
452
453	music.refreshRNGseed()
454
455	music.loadPlaylistForStage(stageid, "Melee")
456
457	if stageid == 0x0 then
458		music.loadPlaylistForStage(stageid, "Melee/Menu Music")
459		return
460	elseif melee.isBTTStage(stageid) then
461		music.loadPlaylistForStage(stageid, "Melee/Single Player Music/Break the Targets")
462		return
463	end
464
465	local name = melee.getStageName(stageid)
466	local series = melee.getStageSeries(stageid)
467	local sp = melee.isSinglePlayerStage(stageid)
468	local aka = melee.isAkaneiaStage(stageid)
469	local bm = melee.isBeyondMeleeStage(stageid)
470
471	if not name then music.PLAYLIST_ID = nil return end
472
473	if sp then
474		music.loadPlaylistForStage(stageid, ("Melee/Single Player Music/%s"):format(name)) -- Load everything in the stage specific folder
475		music.loadPlaylistForStage(stageid, "Melee/Single Player Music") -- Load everything that's not in a stage folder as well
476	elseif aka then
477		music.loadPlaylistForStage(stageid, ("Melee/Akaneia Stage Music/%s"):format(name)) -- Load everything in the stage specific folder
478		music.loadPlaylistForStage(stageid, "Melee/Akaneia Stage Music") -- Load everything in the akaneia folder
479		music.loadPlaylistForStage(stageid, "Melee/Stage Music") -- Load everything in the stage folder
480	elseif bm then
481		music.loadPlaylistForStage(stageid, ("Melee/Beyond Melee Stage Music/%s"):format(name)) -- Load everything in the stage specific folder
482		music.loadPlaylistForStage(stageid, "Melee/Beyond Melee Stage Music") -- Load everything in the akaneia folder
483		music.loadPlaylistForStage(stageid, "Melee/Stage Music") -- Load everything in the stage folder
484	else
485		music.loadPlaylistForStage(stageid, ("Melee/Stage Music/%s"):format(name)) -- Load everything in the stage specific folder
486		music.loadPlaylistForStage(stageid, "Melee/Stage Music") -- Load everything in the stage folder
487	end
488
489	if series then
490		music.loadPlaylistForStage(stageid, ("Melee/Series Music/%s"):format(series)) -- Load everything in the series folder
491		music.loadPlaylistForStage(stageid, "Melee/Series Music") -- Load everything that's not in a stage folder as well
492	end
493end
494
495return music