fork/m-overlay

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

BkacjiosMusic support for Beyond Melee (#95)2efdb91

settings-overhaul
17.4 KiB674 linesraw
1local bit = require("bit")
2local ffi = require("ffi")
3local log = require("log")
4local cloneloader = require("memory.cloneloader")
5local process = require("memory." .. jit.os:lower())
6local notification = require("notification")
7
8require("extensions.string")
9require("extensions.table")
10
11local NULL = 0x00000000
12
13local GAME_ID_ADDR  = 0x80000000
14local GAME_VER_ADDR = 0x80000007
15local GAME_ID_LEN   = 0x06
16local GAME_NONE     = "\0\0\0\0\0\0"
17
18local VC_ID_ADDR    = 0x80003180
19local VC_ID_LEN     = 0x04
20local VC_NONE       = "\0\0\0\0"
21
22local memory = {
23	clones = require("games.clones"),
24	vcclones = require("games.vcclones"),
25
26	gameid = GAME_NONE,
27	vcid = VC_NONE,
28	process = process,
29	permissions = process:hasPermissions(),
30
31	hooked = false,
32	initialized = false,
33	ingame = false,
34	supportedgame = false,
35
36	map = {},
37	values = {},
38
39	hooks = {},
40	wildcard_hooks = {},
41
42	hook_queue = {},
43}
44
45cloneloader.loadFile("clones.lua", memory.clones)
46
47setmetatable(memory, {__index = memory.values})
48
49local bswap = bit.bswap
50local function bswap16(n)
51	return bit.bor(bit.rshift(n, 8), bit.lshift(bit.band(n, 0xFF), 8))
52end
53
54function memory.readGameID()
55	return memory.read(GAME_ID_ADDR, GAME_ID_LEN)
56end
57
58function memory.readVirtualConsoleID()
59	return memory.read(VC_ID_ADDR, VC_ID_LEN)
60end
61
62function memory.readGameVersion()
63	return memory.readUByte(GAME_VER_ADDR)
64end
65
66local typecache = {}
67
68local function cache(typ, len)
69	-- This stops us from constantly calling ffi.new by recycling old variables
70	len = len or 1
71	if not typecache[typ] then
72		-- Create new cache for this type
73		typecache[typ] = {}
74	elseif typecache[typ][len] then
75		-- Set the cached value to all 0's so it can be reused safely
76		ffi.fill(typecache[typ][len], len)
77		-- Return the cached value
78		return typecache[typ][len]
79	end
80	-- Create a new variable
81	local cached = ffi.new(string.format("%s[?]", typ), len)
82	-- Store it in the cache
83	typecache[typ][len] = cached
84	return cached
85end
86
87function memory.read(addr, len)
88	local output = cache("char", len)
89	local size = ffi.sizeof(output)
90	process:read(addr, output, size)
91	return ffi.string(output, size)
92end
93
94function memory.readByte(addr)
95	if not process:hasProcess() then return 0 end
96	local output = cache("int8_t")
97	process:read(addr, output, ffi.sizeof(output))
98	return output[0]
99end
100
101function memory.writeByte(addr, value)
102	if not process:hasProcess() then return end
103	local input = cache("int8_t")
104	return process:write(addr, input, ffi.sizeof(input))
105end
106
107function memory.readBool(addr)
108	if not process:hasProcess() then return false end
109	return memory.readByte(addr) == 1
110end
111
112function memory.writeBool(addr, value)
113	if not self:hasProcess() then return end
114	self:writeByte(addr, value == true and 1 or 0)
115end
116
117function memory.readUByte(addr)
118	if not process:hasProcess() then return 0 end
119	local output = cache("uint8_t")
120	process:read(addr, output, ffi.sizeof(output))
121	return output[0]
122end
123
124function memory.writeUByte(addr, value)
125	if not process:hasProcess() then return end
126	local input = cache("uint8_t")
127	return process:write(addr, input, ffi.sizeof(input))
128end
129
130function memory.readShort(addr)
131	if not process:hasProcess() then return 0 end
132	local output = cache("int16_t")
133	process:read(addr, output, ffi.sizeof(output))
134	return bswap16(output[0])
135end
136
137function memory.writeShort(addr, value)
138	if not process:hasProcess() then return end
139	local input = cache("int16_t")
140	return process:write(addr, input, ffi.sizeof(input))
141end
142
143function memory.readUShort(addr)
144	if not process:hasProcess() then return 0 end
145	local output = cache("uint16_t")
146	process:read(addr, output, ffi.sizeof(output))
147	return bswap16(output[0])
148end
149
150function memory.writeUShort(addr, value)
151	if not process:hasProcess() then return end
152	local input = cache("uint16_t")
153	return process:write(addr, input, ffi.sizeof(input))
154end
155
156do
157	local floatconversion = ffi.new("union { uint32_t i; float f; }")
158
159	function memory.readFloat(addr)
160		if not process:hasProcess() then return 0 end
161		local output = cache("uint32_t")
162		process:read(addr, output, ffi.sizeof(output))
163		floatconversion.i = bswap(output[0])
164		return floatconversion.f, floatconversion.i
165	end
166end
167
168function memory.writeFloat(addr, value)
169	if not process:hasProcess() then return end
170	local input = cache("float")
171	return process:write(addr, input, ffi.sizeof(input))
172end
173
174function memory.readInt(addr)
175	if not process:hasProcess() then return 0 end
176	local output = cache("int32_t")
177	process:read(addr, output, ffi.sizeof(output))
178	return bswap(output[0])
179end
180
181function memory.writeInt(addr, value)
182	if not process:hasProcess() then return end
183	local input = cache("int32_t")
184	return process:write(addr, input, ffi.sizeof(input))
185end
186
187function memory.readUInt(addr)
188	if not process:hasProcess() then return 0 end
189	local output = cache("uint32_t")
190	process:read(addr, output, ffi.sizeof(output))
191	return bswap(output[0])
192end
193
194function memory.writeUInt(addr, value)
195	if not process:hasProcess() then return end
196	local input = cache("uint32_t")
197	return process:write(addr, input, ffi.sizeof(input))
198end
199
200local TYPES_READ = {
201	["bool"] = memory.readBool,
202
203	["sbyte"] = memory.readByte,
204	["byte"] = memory.readUByte,
205	["short"] = memory.readShort,
206	["int"] = memory.readInt,
207
208	["u8"] = memory.readUByte,
209	["s8"] = memory.readByte,
210	["u16"] = memory.readUShort,
211	["s16"] = memory.readShort,
212	["u32"] = memory.readUInt,
213	["s32"] = memory.readInt,
214
215	["float"] = memory.readFloat,
216
217	["data"] = memory.read,
218}
219
220-- Creates or updates a tree of values for easy indexing
221-- Example a path of "player.name" will become memory.players = { name = value }
222function memory.cacheValue(table, path, value)
223	local last = table
224	local last_key = nil
225
226	local keys = {}
227	for key in string.gmatch(path, "[^%.]+") do
228		keys[#keys + 1] = tonumber(key) or key
229	end
230
231	for i, key in ipairs(keys) do
232		if i < #keys then
233			last[key] = last[key] or {}
234			last = last[key]
235		else
236			if type(last) ~= "table" then
237				return error(("Failed to index a %s value (%q)"):format(type(last), keys[i-1]))
238			end
239			last[key] = value
240			last_key = key
241		end
242	end
243
244	-- Return the table that the value is being stored in, and the key name
245	return last, last_key
246end
247
248local ADDRESS = {}
249ADDRESS.__index = ADDRESS
250
251function memory.newvalue(addr, offset, struct, name)
252	assert(type(addr) == "number", "argument #1 'address' must be a number")
253	assert(TYPES_READ[struct.type] ~= nil, "unhandled type: " .. struct.type)
254
255	name = name or struct.name or addr
256
257	local init = struct.init or NULL
258
259	-- create/get a new value cache based off of the value name
260	local tbl, key = memory.cacheValue(memory.values, name, init)
261
262	--log.debug("[MEMORY] VALUE CREATED %08X + %X %q", addr, offset, name)
263
264	return setmetatable({
265		name = name,
266
267		address = addr, -- Where in memory this value is located
268		offset = offset, -- How far past the address value we should get the value from
269
270		type = struct.type,
271		-- Assign the function we will be using to read from memory
272		read = TYPES_READ[struct.type],
273		len = struct.len,
274
275		-- Setup the cache
276		cache = tbl,
277		cache_key = key,
278		cache_value = init,
279
280		debug = struct.debug,
281	}, ADDRESS)
282end
283
284function ADDRESS:update()
285	if self.address == NULL then return end
286
287	-- value = converted value
288	-- orig = Non-converted value (Only available for floats)
289	local value, orig = self.read(self.address + self.offset, self.len)
290
291	-- Check if there has been a value change
292	if self.cache_value ~= value then
293		self.cache_value = value
294		self.cache[self.cache_key] = self.cache_value
295
296		if self.debug then
297			if self.type == "data" then
298				value = value:match("(.-)%z") -- Strip trailing 0's
299				log.debug("[MEMORY] [0x%08X  = 0x%s] %s = %q", self.address + self.offset, string.tohex(value), self.name, value)
300			else
301				local numValue = tonumber(orig) or tonumber(value) or (value and 1 or 0)
302				log.debug("[MEMORY] [0x%08X  = 0x%08X] %s = %s", self.address + self.offset, numValue, self.name, value)
303			end
304		end
305
306		-- Queue up a hook event
307		table.insert(memory.hook_queue, {name = self.name, value = value, debug = self.debug})
308	end
309end
310
311local POINTER = {}
312POINTER.__index = POINTER
313
314function memory.newpointer(addr, offset, pointer, name)
315	local pstruct = {}
316
317	name = name or pointer.name
318
319	--log.debug("[MEMORY] POINTER CREATED %08X + %X %q", addr, offset, name or "nil")
320
321	-- Loop through the pointers children
322	for poffset, struct in pairs(pointer.struct) do
323		local sname = name
324		if sname and struct.name then
325			sname = sname .. "." .. struct.name
326		end
327		if struct.type == "pointer" then
328			pstruct[poffset] = memory.newpointer(NULL, poffset, struct, sname)
329		else
330			pstruct[poffset] = memory.newvalue(NULL, poffset, struct, sname)
331		end
332	end
333
334	return setmetatable({
335		parent = addr ~= NULL and pointer or nil,
336		name = name,
337		address = addr,
338		offset = offset,
339		location = NULL,
340		struct = pstruct,
341	}, POINTER)
342end
343
344function POINTER:getAddress()
345	return ("0x%08X"):format(self.address + self.offset)
346end
347
348function POINTER:getPointerPath()
349	local parent = self
350	while parent do
351		local path = parent:getAddress()
352		path = parent:getAddress() .. " -> " .. path
353		parent = parent.parent
354	end
355	return path
356end
357
358do
359	local cast = ffi.cast
360	local GC_RAM_START = cast("uint32_t", 0x80000000)
361	local GC_RAM_END = cast("uint32_t", 0x81800000)
362	local WII_RAM_START = cast("uint32_t", 0x90000000)
363	local WII_RAM_END = cast("uint32_t", 0x94000000)
364
365	local function isValidPointer(ptr)
366		ptr = cast("uint32_t", ptr)
367		return ptr ~= NULL and ((ptr >= GC_RAM_START and ptr <= GC_RAM_END) or (ptr >= WII_RAM_START and ptr <= WII_RAM_END))
368	end
369
370	function POINTER:update()
371		local addr = self.address + self.offset
372		local ploc = memory.readUInt(addr)
373		local valid = isValidPointer(ploc)
374
375		if self.location ~= ploc then
376			self.location = ploc
377
378			if valid then
379				log.debug("[MEMORY] [0x%08X -> 0x%08X] %s -> 0x%08X", addr, ploc, self.name, ploc)
380			else
381				log.debug("[MEMORY] [0x%08X -> 0x0 (NULL)] %s -> 0x%08X", addr, self.name, ploc)
382			end
383		end
384
385		if valid then
386			for offset, struct in pairs(self.struct) do
387				-- Set the address space to be where the containing pointer is pointing to
388				struct.address = ploc
389				-- Update the value/pointer recursively
390				struct:update()
391			end
392		end
393	end
394end
395
396function memory.loadmap(map)
397	for address, struct in pairs(map) do
398		if struct.type == "pointer" then
399			memory.map[address] = memory.newpointer(address, NULL, struct)
400		else
401			memory.map[address] = memory.newvalue(address, NULL, struct)
402		end
403	end
404end
405
406function memory.hasPermissions()
407	return memory.permissions
408end
409
410function memory.isSupportedGame()
411	return memory.supportedgame
412end
413
414function memory.isInGame()
415	local gid = memory.gameid
416	local vcid = memory.vcid
417	return gid ~= GAME_NONE or vcid ~= VC_NONE
418end
419
420function memory.isMelee()
421	local gid = memory.gameid
422	local version = memory.version
423
424	-- Force the GAMEID and VERSION to be Melee 1.02, since Fizzi seems to be using the gameid address space for something..
425	if gid ~= GAME_NONE and PANEL_SETTINGS:IsSlippiNetplay() then
426		gid = "GALE01"
427		version = 0x02
428	end
429
430	-- See if this GameID is a clone of another
431	local clone = memory.clones[gid] and memory.clones[gid][version] or nil
432
433	if gid == "GTME01" then
434		version = 0x02
435		gid = "GALE01"
436	elseif clone then
437		version = clone.version
438		gid = clone.id
439	end
440
441	return gid == "GALE01" and version == 0x02
442end
443
444local timer = love.timer.getTime()
445
446function memory.loadGameScript(path)
447	-- Try to load the game table
448	local status, game = xpcall(require, debug.traceback, ("games.%s"):format(path))
449
450	if status then
451		memory.supportedgame = true
452		memory.game = game
453		log.info("[DOLPHIN] Loaded game config: %s", path)
454		notification.info(("Game %q detected"):format(path))
455		memory.init(game.memorymap)
456	else
457		memory.supportedgame = false
458		notification.error(("Unsupported game %s"):format(path))
459		notification.error("Playing slippi netplay? Press 'escape' and enable Rollback/Netplay mode")
460		log.error("[DOLPHIN] %s", game) -- game variable is an error string
461	end
462end
463
464function memory.findGame()
465	local gid = memory.readGameID()
466	local version = memory.readGameVersion()
467
468	local vcid = memory.readVirtualConsoleID()
469
470	-- Force the GAMEID and VERSION to be Melee 1.02, since Fizzi seems to be using the gameid address space for something..
471	if gid ~= GAME_NONE and PANEL_SETTINGS:IsSlippiNetplay() then
472		gid = "GALE01"
473		version = 0x02
474	end
475
476	-- When playing Slippi netplay.. the game ID can and will change..
477	-- This would normally break things, but if you enable Rollback/Netplay mode it will force the gameid to always be GALE01 v1.02
478	local meleeMode = (memory.isMelee() and memory.gameid ~= gid)
479
480	if not memory.ingame and gid == GAME_NONE and vcid ~= VC_NONE then
481		memory.reset()
482		memory.ingame = true
483		memory.vcid = vcid
484
485		log.info("[DOLPHIN] Game: %s", vcid)
486		love.updateTitle(("M'Overlay - Dolphin hooked (%s)"):format(vcid))
487
488		-- Check for VC clones
489		vcid = memory.vcclones[vcid] or vcid
490
491		memory.loadGameScript(vcid)
492		memory.runhook("OnGameOpen", vcid)
493	elseif (not memory.ingame or meleeMode) and gid ~= GAME_NONE then
494		memory.reset()
495		memory.ingame = true
496		memory.gameid = gid
497		memory.version = version
498
499		log.info("[DOLPHIN] Game: %s revision %i", gid, version)
500		love.updateTitle(("M'Overlay - Dolphin hooked (%s-%i)"):format(gid, version))
501
502		-- See if this GameID is a clone of another
503		local clone = memory.clones[gid] and memory.clones[gid][version] or nil
504
505		if gid == "GTME01" then
506			version = 0x02
507			gid = "GALE01"
508		elseif clone then
509			version = clone.version
510			gid = clone.id
511		end
512
513		memory.loadGameScript(("%s-%d"):format(gid, version))
514		memory.runhook("OnGameOpen", gid, version)
515	elseif (memory.ingame or meleeMode) and (gid == GAME_NONE and vcid == VC_NONE) then
516		memory.reset()
517		memory.ingame = false
518		memory.gameid = gid
519		memory.vcid = vcid
520		memory.version = version
521
522		love.updateTitle("M'Overlay - Dolphin hooked")
523		memory.runhook("OnGameClosed")
524		memory.process:clearGamecubeRAMOffset() -- Clear the memory address space location (When a new game is opened, we recheck this)
525		log.info("[DOLPHIN] Game closed..")
526	end
527end
528
529function memory.update()
530	if not memory.hasPermissions() then return end
531
532	if not process:isProcessActive() and process:hasProcess() then
533		process:close()
534		love.updateTitle("M'Overlay - Waiting for Dolphin..")
535		log.info("[DOLPHIN] Unhooked")
536		memory.hooked = false
537	end
538
539	local t = love.timer.getTime()
540
541	-- Only check for the dolphin process once per second to reduce CPU load
542	if not process:hasProcess() or not process:hasGamecubeRAMOffset() then
543		if timer <= t then
544			timer = t + 0.5
545			if process:findprocess() then
546				log.info("[DOLPHIN] Hooked")
547				love.updateTitle("M'Overlay - Dolphin hooked")
548				memory.hooked = true
549			elseif not process:hasGamecubeRAMOffset() and process:findGamecubeRAMOffset() then
550				log.debug("[DOLPHIN] Watching ram: %X [%X]", process:getGamecubeRAMOffset(), process:getGamecubeRAMSize())
551			end
552		end
553	else
554		memory.updatememory()
555
556		local frame = memory.frame or 0
557		if frame == 0 or memory.game_frame ~= frame then
558			memory.game_frame = frame
559			memory.runhooks()
560		end
561	end
562end
563
564function memory.init(map)
565	memory.initialized = true
566	memory.loadmap(map)
567	log.info("[MEMORY] Mapped game memory structure")
568end
569
570function memory.reset()
571	memory.initialized = false
572	memory.ingame = false
573	memory.map = {}
574	memory.values = {}
575	memory.gameid = GAME_NONE
576	memory.version = 0
577	memory.game = nil
578	setmetatable(memory, {__index = memory.values})
579end
580
581function memory.updatememory()
582	memory.findGame()
583
584	for addr, value in pairs(memory.map) do
585		value:update()
586	end
587end
588
589local function hookPattern(name)
590	-- Convert '*' into capture patterns
591	if string.find(name, "*", 1, true) then
592		return true, '^' .. name:escape():gsub("%%%*", "([^.]-)") .. '$'
593	end
594	return false, name
595end
596
597function memory.hook(name, desc, callback)
598	local wildcard, name = hookPattern(name)
599	if wildcard then
600		memory.wildcard_hooks[name] = memory.wildcard_hooks[name] or {}
601		memory.wildcard_hooks[name][desc] = callback
602	else
603		memory.hooks[name] = memory.hooks[name] or {}
604		memory.hooks[name][desc] = callback
605	end
606end
607
608function memory.unhook(name, desc)
609	memory.hook(name, desc, nil)
610end
611
612function memory.runhooks()
613	local pop
614	while true do
615		pop = table.remove(memory.hook_queue, 1)
616		if not pop then break end
617		memory.runhook(pop.name, pop.value)
618	end
619end
620
621do
622	local args = {}
623	local matches = {}
624
625	function memory.runhook(name, ...)
626		-- Normal hooks
627		if memory.hooks[name] then
628			for desc, callback in pairs(memory.hooks[name]) do
629				local succ, err
630				if type(desc) == "table" then
631					-- Assume a table is an object, so call it as so
632					succ, err = xpcall(callback, debug.traceback, desc, ...)
633				else
634					succ, err = xpcall(callback, debug.traceback, ...)
635				end
636				if not succ then
637					log.error("[MEMORY] hook error: %s (%s)", desc, err)
638				end
639			end
640		end
641
642		local varargs = {...}
643
644		-- Allow for wildcard hooks
645		for pattern, hooks in pairs(memory.wildcard_hooks) do
646			if string.find(name, pattern) then
647				args = {}
648				matches = {name:match(pattern)}
649
650				for k, match in ipairs(matches) do
651					table.insert(args, tonumber(match) or match)
652				end
653				for k, arg in ipairs(varargs) do
654					table.insert(args, arg)
655				end
656
657				for desc, callback in pairs(hooks) do
658					local succ, err
659					if type(desc) == "table" then
660						-- Assume a table is an object, so call it as so
661						succ, err = xpcall(callback, debug.traceback, desc, unpack(args))
662					else
663						succ, err = xpcall(callback, debug.traceback, unpack(args))
664					end
665					if not succ then
666						log.error("[MEMORY] wildcard hook error: %s (%s)", desc, err)
667					end
668				end
669			end
670		end
671	end
672end
673
674return memory