-- From TBG_LOAD savestate, apply TBG_PLAN input and log every write (frame, value, PC) to TBG_WATCH ranges. local out, last = os.getenv("TBG_OUT"), tonumber(os.getenv("TBG_END") or "300") local plan, shots = {}, {} for f, b in (os.getenv("TBG_PLAN") or ""):gmatch("(%d+):([%w+]+)") do plan[tonumber(f)] = b end for f in (os.getenv("TBG_SHOTS") or ""):gmatch("%d+") do shots[tonumber(f)] = true end local hold = tonumber(os.getenv("TBG_HOLD") or "4") local frame, held, holdLeft, loaded = 0, nil, 0, false local log = io.open(out .. "/watch.txt", "w") emu.addMemoryCallback(function() if not loaded then local h = io.open(os.getenv("TBG_LOAD"), "rb"); emu.loadSavestate(h:read("a")); h:close(); loaded = true end end, emu.callbackType.exec, 0x0081B6) for r in (os.getenv("TBG_WATCH") or ""):gmatch("[%x%-]+") do local a, b = r:match("(%x+)%-(%x+)") a = tonumber(a or r, 16); b = tonumber(b or r, 16) -- low WRAM is mirrored in banks 00-3F/80-BF; the game writes through DBR=$80-$88, so watch every mirror used for _, bank in ipairs({0x00, 0x7E, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88}) do local lo, hi = a, b if bank ~= 0x7E and hi > 0x1FFF then hi = 0x1FFF end if lo <= hi then emu.addMemoryCallback(function(addr, value) if not loaded then return end local s = emu.getState() log:write(string.format("f%05d %04X=%02X PC %02X:%04X\n", frame, addr & 0xFFFF, value, s["cpu.k"], s["cpu.pc"])) end, emu.callbackType.write, bank * 65536 + lo, bank * 65536 + hi) end end end emu.addEventCallback(function() if held and holdLeft > 0 then local t = {} for b in held:gmatch("[^+]+") do t[b] = true end emu.setInput(t, 0) end end, emu.eventType.inputPolled) emu.addEventCallback(function() if not loaded then return end frame = frame + 1 holdLeft = holdLeft - 1 if plan[frame] then held, holdLeft = plan[frame], hold end if shots[frame] then local h = io.open(string.format("%s/f%05d.png", out, frame), "wb"); h:write(emu.takeScreenshot()); h:close() end if frame >= last then log:close(); emu.stop(0) end end, emu.eventType.endFrame)