-- Like drive.lua but with working savestates and per-port input. Env: -- TBG_POKES="frame:wramaddr=val[+wramaddr=val],..." (hex addr/val, applied at end of frame), -- TBG_WATCHB="addr,addr" (hex WRAM bytes logged every frame to /watch.txt), -- TBG_LIB, TBG_OUT, TBG_PLAN, TBG_SHOTS (frames), TBG_DUMPS (frames: wram dump), TBG_END, TBG_SAVE_AT, TBG_LOAD local L = dofile(os.getenv("TBG_LIB")) local out = os.getenv("TBG_OUT") local plan = L.inputPlan(os.getenv("TBG_PLAN")) local shots, dumps = {}, {} for f in (os.getenv("TBG_SHOTS") or ""):gmatch("%d+") do shots[tonumber(f)] = true end for f in (os.getenv("TBG_DUMPS") or ""):gmatch("%d+") do dumps[tonumber(f)] = true end local last = tonumber(os.getenv("TBG_END") or "600") local saveAt = tonumber(os.getenv("TBG_SAVE_AT") or "-1") local frame = 0 local pokes = {} for f, list in (os.getenv("TBG_POKES") or ""):gmatch("(%d+):([%x=+]+)") do pokes[tonumber(f)] = list end local watchb = {} for a in (os.getenv("TBG_WATCHB") or ""):gmatch("%x+") do watchb[#watchb + 1] = tonumber(a, 16) end local wh = #watchb > 0 and io.open(out .. "/watch.txt", "w") or nil if os.getenv("TBG_LOAD") then L.load(os.getenv("TBG_LOAD")) end emu.addEventCallback(function() local pressed = {[0] = {}, [1] = {}} for _, e in ipairs(plan) do if frame >= e.f and frame < e.f + e.hold then for b in e.b:gmatch("[^+]+") do pressed[e.port][b] = true end end end emu.setInput(pressed[0], 0); emu.setInput(pressed[1], 1) end, emu.eventType.inputPolled) emu.addEventCallback(function() frame = frame + 1 if pokes[frame] then for a, v in pokes[frame]:gmatch("(%x+)=(%x+)") do emu.write(tonumber(a, 16), tonumber(v, 16), emu.memType.snesWorkRam) end end if wh then local t = {} for i, a in ipairs(watchb) do t[i] = string.format("%02X", emu.read(a, emu.memType.snesWorkRam)) end wh:write(frame .. " " .. table.concat(t, " ") .. "\n") end if frame == saveAt then L.save(out .. "/state.mss") end if shots[frame] then L.shot(string.format("%s/f%05d.png", out, frame)) end if dumps[frame] then L.dumpWram(string.format("%s/f%05d.wram", out, frame)) end if frame >= last then if wh then wh:close() end emu.stop(0) end end, emu.eventType.endFrame)