fork/m-overlay

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

BkacjiosBugfixes + Dark Mode skina8034e9

v2.1.1
20.3 KiB691 linesraw
1local music = {
2	PLAYLIST = {},
3	SONGS = {},
4	PLAYLIST_ID = -1,
5	PLAYING = nil,
6	FINISHED = true,
7	LOOP = false,
8	TRACK_ID = {},
9	RNG_SEED = nil,
10	PROBABILITY_FILE = "probability.json",
11	PROBABILITY_SETTINGS = {
12		global = {},
13		states = {},
14	},
15	MUTED = false
16}
17
18local MUTED_TEXTURE = love.graphics.newImage("textures/gui/muted.png")
19
20local log = require("log")
21local melee = require("melee")
22local memory = require("memory")
23local notification = require("notification")
24local overlay = require("overlay")
25local wav = require("wav")
26local json = require("serializer.json")
27local fs = require("util.filesystem")
28
29require("extensions.math")
30
31-- Given a list of {element, weight} pairs, do a weighted random sample
32-- of the elements (returns an index, not the element itself)
33local function weightedRandomChoice(list)
34	if not list or #list == 0 then return nil end
35	if #list == 1 then return 1 end
36
37	local sum = 0
38	for _, weight in pairs(list) do
39		sum = sum + weight
40	end
41
42	if sum <= 0 then return nil end
43
44	local choice = math.random(1, sum)
45	for k, weight in pairs(list) do
46		choice = choice - weight
47		if choice <= 0 then
48			return k
49		end
50	end
51	return choice
52end
53
54local function moveFolderContentsTo(from, to)
55	local info = love.filesystem.getInfo(from)
56
57	if info and info.type == "directory" then
58		-- Upgrade to new folder layout
59		local configdir = love.filesystem.getSaveDirectory()
60
61		local files = love.filesystem.getDirectoryItems(from)
62		for k, file in ipairs(files) do
63			os.rename(("%s/%s/%s"):format(configdir, from, file), ("%s/%s/%s"):format(configdir, to, file))
64		end
65
66		love.filesystem.remove(from)
67	end
68end
69
70function music.update()
71	if not music.PLAYING or music.FINISHED then return end
72
73	local duration = music.PLAYING.STREAM:getDuration("samples")
74	local position = music.PLAYING.STREAM:tell("samples")
75
76	if music.LOOP then
77		local finished = not music.PLAYING.STREAM:isPlaying()
78
79		if finished then
80			-- If the song is no longer playing, that means it reached the end
81			-- Immediately play it again
82			log.debug("[MUSIC] End of song reached, replaying")
83			music.PLAYING.STREAM:play()
84		end
85
86		local info = music.PLAYING.WAV
87
88		if info then
89			for k, loop in pairs(info.loops) do
90				if finished or position >= loop.sample_end then
91					log.debug("[MUSIC] Loop point reached, seeking to %d", loop.sample_start)
92					-- If the song finished playing or reached the looping point, loop back to the start?
93					music.PLAYING.STREAM:seek(loop.sample_start, "samples")
94					break -- Only handle the first loop for now..
95				end
96			end
97		end
98	else
99		if not music.PLAYING.STREAM:isPlaying() or position >= duration then
100			-- We mark that the song has completed, allowing the next game frame hook to play the next song in the playlist
101			music.FINISHED = true
102		end
103	end
104end
105
106function music.init()
107	love.filesystem.createDirectory("Melee")
108
109	local info = love.filesystem.getInfo("Stage Music")
110
111	if info and info.type == "directory" then
112		-- Upgrade to new folder layout
113		local configdir = love.filesystem.getSaveDirectory()
114		os.rename(("%s/Stage Music"):format(configdir), ("%s/Melee/Stage Music"):format(configdir))
115	end
116
117	local info = love.filesystem.getInfo("Melee/Stage Music/Menu")
118
119	if info and info.type == "directory" then
120		-- Upgrade to new folder layout
121		local configdir = love.filesystem.getSaveDirectory()
122		os.rename(("%s/Melee/Stage Music/Menu"):format(configdir), ("%s/Melee/Menu Music"):format(configdir))
123	else
124		love.filesystem.createDirectory("Melee/Menu Music")
125	end
126
127	-- VS mode folders
128
129	for stageid, name in pairs(melee.getAllStages()) do
130		love.filesystem.createDirectory(("Melee/Stage Music/%s"):format(name))
131	end
132	moveFolderContentsTo("Melee/Stage Music/All", "Melee/Stage Music")
133
134	-- Single player folders
135
136	love.filesystem.createDirectory("Melee/Single Player Music")
137	
138	for stageid, name in pairs(melee.getSinglePlayerStages()) do
139		love.filesystem.createDirectory(("Melee/Single Player Music/%s"):format(name))
140	end
141
142	-- Series folders
143
144	for stageid, series in pairs(melee.getAllStageSeries()) do
145		love.filesystem.createDirectory(("Melee/Series Music/%s"):format(series))
146	end
147	moveFolderContentsTo("Melee/Series Music/All", "Melee/Series Music")
148
149	love.filesystem.createDirectory("Melee/Single Player Music/Break the Targets")
150
151	for stageid, name in pairs(melee.getAkaneiaStages()) do
152		love.filesystem.createDirectory(("Melee/Akaneia Stage Music/%s"):format(name))
153	end
154	for stageid, name in pairs(melee.getBeyondMeleeStages()) do
155		love.filesystem.createDirectory(("Melee/Beyond Melee Stage Music/%s"):format(name))
156	end
157
158	music.loadProbablitities()
159end
160
161function music.kill()
162	if music.PLAYING then
163		if music.PLAYING.STREAM then
164			if music.PLAYING.STREAM:isPlaying() then
165				log.debug("[MUSIC] Killed music")
166				music.PLAYING.STREAM:stop()
167				music.FINISHED = true
168			end
169			music.PLAYING.STREAM:release()
170		end
171		music.PLAYING = nil
172	end
173end
174
175-- Set to true when the announcer says 'GAME!'
176local MATCH_SOFT_END = false
177
178function music.shouldPlayMusic()
179	return melee.isInMenus() or (melee.isInGame() and not melee.matchFinsihed() and not MATCH_SOFT_END)
180end
181
182function music.onLoopChange(mode)
183	if music.PLAYING and music.PLAYING.STREAM:isPlaying() then
184		music.LOOP = music.shouldLoop()
185	end
186end
187
188function music.getVolume()
189	return PANEL_SETTINGS:GetVolume()
190end
191
192function music.getPlaylist()
193	local playlist = table.copy(music.PLAYLIST)
194	table.sort(playlist, function(a, b)
195		return a.FILEPATH < b.FILEPATH
196	end)
197	return playlist
198end
199
200function music.getPlaylistTree()
201	local playlist = music.getPlaylist()
202	local tree = {}
203	for k, entry in ipairs(playlist) do
204		local directory = string.getFilePath(entry.FILEPATH)
205		if not tree[directory] then tree[directory] = {} end
206		table.insert(tree[directory], entry)
207	end
208	return tree
209end
210
211local LOADED = false
212local ALLOW_INGAME_VOLUME = false
213
214memory.hook("OnGameClosed", "Set state unloaded", function()
215	LOADED = false
216end)
217
218memory.hook("scene.major", "Load Initial Volume", function(menu)
219	if memory.isMelee() and ALLOW_INGAME_VOLUME and not LOADED and menu == SCENE_MAIN_MENU then
220		LOADED = true
221		-- Set the games music value to our value
222		music.setVolume(music.getVolume())
223	end
224end)
225
226memory.hook("volume.slider", "Ingame Volume Adjust", function(volume)
227	if memory.isMelee() and ALLOW_INGAME_VOLUME and LOADED then
228		PANEL_SETTINGS:SetVolume(100-volume)
229	end
230end)
231
232function music.refreshRNGseed()
233	local getSeed = function()
234		if not music.RNG_SEED or not memory.isMelee() then return os.time(), "the system time" end
235		if melee.isInMenus() then return music.RNG_SEED + 1, "the previous seed" end
236		if melee.isNetplayGame() then return memory.online.rng_offset, "Slippi" end
237		return memory.rng.seed, "Melee"
238	end
239
240	local seed, source = getSeed()
241	math.randomseed(seed)
242	music.RNG_SEED = seed
243	log.debug("[RANDOM] Obtained seed \"0x%X\" from %s", seed, source)
244end
245
246function music.setVolume(vol)
247	if ALLOW_INGAME_VOLUME and memory.isMelee() then
248		-- Melee's slider goes in increments of 5
249		-- It seems to add +5 or -5 no matter what, but it can actually take numbers in between and still work
250		--local nearest5 = math.round((100-vol) / 5)*5
251
252		-- volume.slider adjust (0-100)
253		memory.writeByte(0x8045C384, math.round(100-vol))
254
255		-- volume.music adjust (0-127)
256		memory.writeByte(0x804D3887, (vol/100) * 127)
257	end
258
259	if music.PLAYING then
260		if music.MUTED then
261			vol = 0
262		end
263		music.PLAYING.STREAM:setVolume((vol/100) * (melee.isPaused() and 0.35 or 1))
264	end
265end
266
267do
268	local LOOPING_NONE = 0
269	local LOOPING_MENU = 1
270	local LOOPING_STAGE_TIMED = 2
271	local LOOPING_STAGE_ENDLESS = 4
272	function music.shouldLoop()
273		local loop = PANEL_SETTINGS:GetMusicLoopMode()
274
275		if music.PLAYLIST_ID == 0 then
276			return bit.band(loop, LOOPING_MENU) == LOOPING_MENU
277		elseif melee.isCountdownTimer() then
278			return bit.band(loop, LOOPING_STAGE_TIMED) == LOOPING_STAGE_TIMED
279		else
280			return bit.band(loop, LOOPING_STAGE_ENDLESS) == LOOPING_STAGE_ENDLESS
281		end
282
283		return false
284	end
285end
286
287do
288local function getWeightTable(songs)
289	local tbl = {}
290	local useWeights = false
291	local firstValue
292	for k, song in pairs(songs) do
293		tbl[k] = music.getFileProbability(song.FILEPATH)
294		if not firstValue then
295			firstValue = tbl[k]
296		elseif firstValue ~= tbl[k] then
297			useWeights = true
298		end
299	end
300	return tbl, useWeights
301end
302
303local function getNextTrack(songs)
304	local weightTable, useWeights = getWeightTable(songs)
305
306	if useWeights then
307		local track_id = weightedRandomChoice(getWeightTable(songs))
308		return track_id, track_id
309	end
310
311	music.TRACK_ID[music.PLAYLIST_ID] = ((music.TRACK_ID[music.PLAYLIST_ID] or -1) + 1) % #songs
312	local track_id = music.TRACK_ID[music.PLAYLIST_ID] + 1
313
314	-- Only shuffle if we have more than 2 songs..
315	if #songs > 2 then
316		-- Every time we play a song, we randomly place it towards the start of the playlist
317		-- This keeps the playlist in a constantly shuffled order
318		local track = table.remove(songs, track_id)
319		local newpos = math.random(1, track_id)
320		table.insert(songs, newpos, track)
321		return track_id, newpos
322	end
323
324	return track_id, track_id
325end
326
327local function loadTrack(songs, index)
328	local track_info = songs[index]
329
330	local filepath = track_info.FILEPATH
331
332	local success, source = pcall(love.audio.newSource, filepath, "stream")
333	if not (success and source) then
334		log.error("[MUSIC] invalid music file %q", filepath)
335		notification.error("invalid music file %q", filepath)
336		table.remove(songs, index)
337		return nil
338	end
339
340	return { STREAM = source, WAV = track_info.IS_WAV and wav.parse(filepath) or nil, INFO = track_info }
341end
342
343function music.playNextTrack()
344	if not memory.isMelee() or not PANEL_SETTINGS:PlayStageMusic() then return end
345	if music.PLAYING ~= nil and not music.FINISHED then return end
346	if not music.PLAYLIST_ID then return end
347	if not music.shouldPlayMusic() then return end
348
349	local songs = music.PLAYLIST
350
351	if #songs > 0 then
352		local track_id, track_index = getNextTrack(songs)
353
354		if not track_index then return end
355
356		music.PLAYING = loadTrack(songs, track_index)
357		
358		if music.PLAYING then
359			local path = music.PLAYING.INFO.FILEPATH
360			if music.PLAYLIST_ID == 0x0 then
361				log.info("[MUSIC] Playing track #%d for menu (%q)", track_id, path)
362			else
363				log.info("[MUSIC] Playing track #%d for stage %q (%q)", track_id, melee.getStageName(music.PLAYLIST_ID), path)
364			end
365			music.setVolume(PANEL_SETTINGS:GetVolume())
366			music.LOOP = music.shouldLoop()
367			music.PLAYING.STREAM:play()
368			music.FINISHED = false
369		end
370	end
371end
372end
373
374function music.onStateChange()
375	if melee.isInGame() then
376		music.loadForStage(memory.stage.id)
377	elseif melee.isInMenus() then
378		music.loadForStage(0)
379	end
380end
381
382function music.draw()
383	if music.MUTED then
384		love.graphics.setColor(255, 255, 255, 255)
385		love.graphics.easyDraw(MUTED_TEXTURE, 256 - 16, 256 - 68, 0, 32, 32)
386	end
387end
388
389memory.hook("frame", "Melee - Music Think", music.playNextTrack)
390
391memory.hook("OnGameClosed", "Dolphin - Game closed", function()
392	music.kill()
393end)
394
395memory.hook("scene.major", "Melee - Menu state", function(menu)
396	if melee.isInMenus() then
397		music.loadForStage(0)
398	elseif not melee.isInGame() then
399		music.kill()
400	end
401end)
402
403memory.hook("scene.minor", "Melee - Menu state", function(menu)
404	if melee.isInMenus() then
405		music.loadForStage(0)
406	elseif melee.isInGame() then
407		MATCH_SOFT_END = false
408		music.loadForStage(memory.stage.id)
409	else
410		music.kill()
411	end
412end)
413
414memory.hook("stage.id", "Melee - Stage loaded", function(stage)
415	if melee.isInGame() then
416		music.loadForStage(stage)
417	end
418end)
419
420memory.hook("match.info.playing", "Melee - Classic Mode Master Hand Fix?", function(playing)
421	-- In classic mode, when you kill masterhand the match result is never set, but the "playing" flag is set to false.
422	-- Mute the music right when masterhand is killed.
423	if not playing and (memory.scene.major == SCENE_CLASSIC_MODE and memory.stage.id == 0x25) then
424		MATCH_SOFT_END = true
425		music.kill()
426	end
427end)
428
429memory.hook("match.info.paused", "Melee - Pause volume", function(paused)
430	music.setVolume(music.getVolume())
431end)
432
433memory.hook("match.info.finished", "Melee - GAME kill music", function(finished)
434	if finished then
435		-- The match ended, so no matter what the music should be killed
436		music.kill()
437	end
438end)
439
440memory.hook("match.info.result", "Melee - GAME kill music", function(result)
441	-- LRAB+Start/Saltyrunback causes a result of MATCH_NO_CONTEST.. We don't want to end the music in this case only.
442	-- The match.finished hook will end the music instead when actually exiting the match using normal LRA+Start.
443	-- If the match actually ends normally, we kill the music early when it announces the end of the game.
444
445	if result ~= MATCH_NO_RESULT and (memory.scene.major ~= SCENE_VS_MODE or (memory.scene.major == SCENE_VS_MODE and result ~= MATCH_NO_CONTEST)) then
446		MATCH_SOFT_END = true
447		music.kill()
448	end
449end)
450
451memory.hook("controller.*.buttons.pressed", "Melee - Music skipper", function(port, pressed)
452	if not memory.isMelee() or 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
453	local skipMask = PANEL_SETTINGS:GetMusicSkipMask()
454	local muteMask = PANEL_SETTINGS:GetMusicMuteMask()
455	if port == overlay.getPort() then
456		if pressed == skipMask and #music.PLAYLIST > 1 then
457			log.debug("[MUSIC] [MASK = 0x%X] Skip combo pressed, stopping music.", skipMask)
458			music.kill()
459		end
460		if pressed == muteMask then
461			music.MUTED = not music.MUTED
462			music.setVolume(music.getVolume())
463			log.debug("[MUSIC] [MASK = 0x%X] Mute combo pressed, %s music.", skipMask, music.MUTED and "muting" or "unmuting")
464		end
465	end
466end)
467
468local valid_music_ext = {
469	["mp3"] = true,
470	["ogg"] = true,
471	["wav"] = true,
472	["flac"] = true
473}
474
475function music.isValidMusicExt(ext)
476	return valid_music_ext[ext]
477end
478
479function music.loadPlaylistForStage(stageid, name)
480	local found = 0
481	local files = love.filesystem.getDirectoryItems(name)
482	table.sort(files) -- Sort our list of files alphabetically, giving our table a deterministic state
483	for k, file in ipairs(files) do
484		local filepath = ("%s/%s"):format(name, file)
485		local info = love.filesystem.getInfo(filepath)
486		if info then
487			if info.type == "file" then
488				local ext = string.getFileExtension(file):lower()
489
490				if music.isValidMusicExt(ext) then
491					found = found + 1
492
493					-- Insert the newly found track into a random position in the playlist
494					local pos = math.random(1, #music.PLAYLIST)
495					local prob = music.PROBABILITY_SETTINGS["global"][filepath] or tonumber(string.match(filepath, ".-_(%d+)%.%w+$")) or 100
496
497					if prob > 100 then
498						log.warn("[MUSIC] Song %q has a probability greater than 100%%", filepath)
499					end
500
501					music.PROBABILITY_SETTINGS["global"][filepath] = prob
502
503					table.insert(music.PLAYLIST, pos, {FILEPATH = filepath, FILENAME = file, WEIGHT = prob, IS_WAV = ext == "wav"})
504				end
505			end
506		else
507			log.warn("[MUSIC] Unable to get file information for file %q", filepath)
508		end
509	end
510	if found > 0 then
511		log.info("[MUSIC] Found %d songs in %q", found, name)
512	end
513end
514
515function music.loadProbablitities()
516	music.PROBABILITY_SETTINGS = {
517		global = {},
518		states = {},
519	}
520
521	local probFile = music.PROBABILITY_FILE
522
523	local f = love.filesystem.newFile(probFile, "r")
524	if f then
525		local settings = music.PROBABILITY_SETTINGS
526		local success, decoded = pcall(json.decode, f:read())
527		f:close()
528		if not success then
529			-- If we failed decoding, decoded is an error string.
530			-- Get the last bit of text after the file name and line number.
531			-- Error format: "filename.lua:1: (OUR ERROR STRING HERE)"
532			local err = string.match(decoded, "^.*:%s*(.*)$") or decoded
533			log.error("[MUSIC] Failed parsing %s: ('%s')", probFile, err)
534			notification.error("Failed parsing %s: ('%s')", probFile, err)
535		elseif decoded.global and decoded.states then
536			if decoded.global then
537				for file, prob in pairs(decoded.global) do
538					settings["global"][file] = prob
539				end
540			end
541			if decoded.states then
542				for stateid, files in pairs(decoded.states) do
543					stateid = tonumber(stateid)
544					settings["states"][stateid] = files
545				end
546			end
547		else
548			-- OLD SAVE FORMAT
549			for file, prob in pairs(decoded) do
550				settings["global"][file] = prob
551			end
552		end
553	end
554end
555
556function music.updateGlobalProbabilities(tbl)
557	local settings = music.PROBABILITY_SETTINGS
558
559	for file, prob in pairs(tbl) do
560		settings["global"][file] = prob
561	end
562end
563
564function music.updateStateProbabilities(tbl)
565	local state = music.PLAYLIST_ID
566	local settings = music.PROBABILITY_SETTINGS
567
568	for file, prob in pairs(tbl) do
569		if not settings["states"][state] then settings["states"][state] = {} end
570		settings["states"][state][file] = prob
571	end
572end
573
574function music.getFileProbability(file)
575	local stateP = music.getStateFileProbability(file)
576
577	if stateP < 100 then
578		return stateP
579	end
580
581	return music.getGlobalFileProbability(file)
582end
583
584function music.getGlobalFileProbability(file)
585	local settings = music.PROBABILITY_SETTINGS
586	if settings["global"] and settings["global"][file] then
587		return settings["global"][file]
588	end
589	return 100 -- Default to 100% chance
590end
591
592function music.getStateFileProbability(file)
593	local state = music.PLAYLIST_ID
594	local settings = music.PROBABILITY_SETTINGS
595	if settings["states"] and settings["states"][state] and settings["states"][state][file] then
596		return settings["states"][state][file]
597	end
598	return 100 -- Default to 100% chance
599end
600
601function music.getProbabilitySaveTable()
602	local tbl = {
603		global = {},
604		states = {},
605	}
606
607	-- Only get files that have a custom prob. set
608	for file, prob in pairs(music.PROBABILITY_SETTINGS["global"]) do
609		if prob < 100 then
610			tbl["global"][file] = prob
611		end
612	end
613	for stateid, files in pairs(music.PROBABILITY_SETTINGS["states"]) do
614		stateid = tostring(stateid) -- JSON objects can only use strings as keys
615		for file, prob in pairs(files) do
616			if prob < 100 then
617				if not tbl["states"][stateid] then tbl["states"][stateid] = {} end
618				tbl["states"][stateid][file] = prob
619			end
620		end
621	end
622	return tbl
623end
624
625function music.saveProbabilities()
626	local probFile = music.PROBABILITY_FILE
627
628	local f, err = love.filesystem.newFile(probFile, "w")
629	if f then
630		log.warn("Writing to %s", probFile)
631		notification.warning("Writing to %s", probFile)
632		f:write(json.encode(music.getProbabilitySaveTable(), true))
633		f:flush()
634	else
635		log.error("Failed writing to %s: %s", probFile, err)
636		notification.error("Failed writing to %s: %s", probFile, err)
637	end
638end
639
640function music.loadForStage(stageid)
641	if music.PLAYLIST_ID == stageid then return end
642
643	music.kill()
644	if not memory.isMelee() or not PANEL_SETTINGS:PlayStageMusic() then return end
645
646	music.PLAYLIST_ID = stageid
647	music.PLAYLIST = {}
648
649	music.refreshRNGseed()
650
651	music.loadPlaylistForStage(stageid, "Melee")
652
653	if stageid == 0x0 then
654		music.loadPlaylistForStage(stageid, "Melee/Menu Music")
655		return
656	elseif melee.isBTTStage(stageid) then
657		music.loadPlaylistForStage(stageid, "Melee/Single Player Music/Break the Targets")
658		return
659	end
660
661	local name = melee.getStageName(stageid)
662	local series = melee.getStageSeries(stageid)
663	local sp = melee.isSinglePlayerStage(stageid)
664	local aka = melee.isAkaneiaStage(stageid)
665	local bm = melee.isBeyondMeleeStage(stageid)
666
667	if not name then music.PLAYLIST_ID = nil return end
668
669	if sp then
670		music.loadPlaylistForStage(stageid, ("Melee/Single Player Music/%s"):format(name)) -- Load everything in the stage specific folder
671		music.loadPlaylistForStage(stageid, "Melee/Single Player Music") -- Load everything that's not in a stage folder as well
672	elseif aka then
673		music.loadPlaylistForStage(stageid, ("Melee/Akaneia Stage Music/%s"):format(name)) -- Load everything in the stage specific folder
674		music.loadPlaylistForStage(stageid, "Melee/Akaneia Stage Music") -- Load everything in the akaneia folder
675		music.loadPlaylistForStage(stageid, "Melee/Stage Music") -- Load everything in the stage folder
676	elseif bm then
677		music.loadPlaylistForStage(stageid, ("Melee/Beyond Melee Stage Music/%s"):format(name)) -- Load everything in the stage specific folder
678		music.loadPlaylistForStage(stageid, "Melee/Beyond Melee Stage Music") -- Load everything in the akaneia folder
679		music.loadPlaylistForStage(stageid, "Melee/Stage Music") -- Load everything in the stage folder
680	else
681		music.loadPlaylistForStage(stageid, ("Melee/Stage Music/%s"):format(name)) -- Load everything in the stage specific folder
682		music.loadPlaylistForStage(stageid, "Melee/Stage Music") -- Load everything in the stage folder
683	end
684
685	if series then
686		music.loadPlaylistForStage(stageid, ("Melee/Series Music/%s"):format(series)) -- Load everything in the series folder
687		music.loadPlaylistForStage(stageid, "Melee/Series Music") -- Load everything that's not in a stage folder as well
688	end
689end
690
691return music