battle_ai_vm.lua 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. --- Interpreter of the enemy AI scripts of the original game.
  2. --
  3. -- The scripts are bytecode for a stack machine (see the opcode list below). Memory is addressed by
  4. -- bit: addresses below 0x2000 are variables of the actor that owns the script, 0x2000 to 0x3FFF
  5. -- are values of the battle shared by every actor and 0x4000 to 0x433F are values of each actor
  6. -- (HP, MP, level, statuses...), selected with an actor mask.
  7. --
  8. -- The interpreter doesn't know about the battle: it asks a host for every global and actor value,
  9. -- and notifies it of actions and texts. The host must have the functions:
  10. --
  11. -- host:read_global(address, size) Value of a global address.
  12. -- host:write_global(address, size, value)
  13. -- host:read_actor(actor, field, size) Value of an actor field (address minus 0x4000).
  14. -- host:write_actor(actor, field, size, value)
  15. -- host:action(owner, type, id) An action was requested, see BattleAI.ACTION. The targets
  16. -- are the last value written to the global 0x2070.
  17. -- host.owner Actor running the script (set by the interpreter).
  18. -- host:text(owner, bytes) A text has to be shown (FF7 encoded text).
  19. -- host:mp_cost(id) MP cost of an attack.
  20. -- host:memory_bank(write, offset, value) Access to the game memory banks (1 and 2).
  21. --
  22. -- Value sizes are 0 (bit), 1 (byte), 2 (word) and 3 (dword).
  23. BattleAI = {}
  24. --- Types of actions requested with the action opcode.
  25. BattleAI.ACTION = {
  26. ENEMY_ATTACK = 0x20,
  27. RUN_SCRIPT = 0x22,
  28. SHOW_TEXT = 0x24,
  29. }
  30. --- Slots of the scripts of an enemy.
  31. BattleAI.SLOT = {
  32. INIT = 0, MAIN = 1, COUNTER_GENERAL = 2, COUNTER_DEATH = 3, COUNTER_PHYSICAL = 4,
  33. COUNTER_MAGIC = 5, BATTLE_END = 6, PRE_TURN = 7, EVENT_1 = 8,
  34. }
  35. --- Bytes used to store each value size.
  36. BattleAI.SIZE_BYTES = {[0] = 1, 1, 2, 4}
  37. --- Maximum number of instructions in a script run, to stop endless loops.
  38. BattleAI.MAX_STEPS = 20000
  39. --- Persistent variables (addresses 0x0000 to 0x03FF) of every actor, by actor index. They keep
  40. -- their values between scripts.
  41. BattleAI.variables = {}
  42. --- Clears the persistent variables, at the beginning of a battle.
  43. function BattleAI.reset()
  44. BattleAI.variables = {}
  45. end
  46. --- Gets the table of bytes with the variables of an actor.
  47. local function variables_of(actor)
  48. local vars = BattleAI.variables[actor]
  49. if vars == nil then
  50. vars = {}
  51. BattleAI.variables[actor] = vars
  52. end
  53. return vars
  54. end
  55. --- Reads a value of memory with the byte array of the variables of an actor.
  56. local function read_bytes(bytes, address, size)
  57. local byte_index = math.floor(address / 8)
  58. if size == 0 then
  59. return math.floor((bytes[byte_index] or 0) / 2 ^ (address % 8)) % 2
  60. end
  61. local value = 0
  62. for i = BattleAI.SIZE_BYTES[size] - 1, 0, -1 do
  63. value = value * 256 + (bytes[byte_index + i] or 0)
  64. end
  65. return value
  66. end
  67. --- Writes a value to the byte array of the variables of an actor.
  68. local function write_bytes(bytes, address, size, value)
  69. local byte_index = math.floor(address / 8)
  70. if size == 0 then
  71. local bit = 2 ^ (address % 8)
  72. local current = bytes[byte_index] or 0
  73. local has = math.floor(current / bit) % 2
  74. if (value ~= 0) and has == 0 then current = current + bit
  75. elseif (value == 0) and has == 1 then current = current - bit
  76. end
  77. bytes[byte_index] = current
  78. return
  79. end
  80. value = math.floor(value)
  81. if value < 0 then value = value + 2 ^ 32 end
  82. for i = 0, BattleAI.SIZE_BYTES[size] - 1 do
  83. bytes[byte_index + i] = value % 256
  84. value = math.floor(value / 256)
  85. end
  86. end
  87. --- Counts the actors of a mask in order, calling a function with their indexes.
  88. local function each_actor(mask, fn)
  89. mask = math.floor(mask)
  90. for actor = 0, 31 do
  91. if math.floor(mask / 2 ^ actor) % 2 == 1 then fn(actor) end
  92. end
  93. end
  94. --- Bitwise operations on non negative integers (Lua 5.1 has none).
  95. local function band(a, b)
  96. local result, bit = 0, 1
  97. a, b = math.floor(a), math.floor(b)
  98. while a > 0 and b > 0 do
  99. if a % 2 == 1 and b % 2 == 1 then result = result + bit end
  100. a, b, bit = math.floor(a / 2), math.floor(b / 2), bit * 2
  101. end
  102. return result
  103. end
  104. local function bor(a, b)
  105. local result, bit = 0, 1
  106. a, b = math.floor(a), math.floor(b)
  107. while a > 0 or b > 0 do
  108. if a % 2 == 1 or b % 2 == 1 then result = result + bit end
  109. a, b, bit = math.floor(a / 2), math.floor(b / 2), bit * 2
  110. end
  111. return result
  112. end
  113. local function bnot(a, bits)
  114. return 2 ^ bits - 1 - math.floor(a)
  115. end
  116. BattleAI.band = band
  117. BattleAI.bor = bor
  118. --- The context of a script run: the owner, the host and the stack.
  119. local Context = {}
  120. Context.__index = Context
  121. --- Reads the value of a memory address for an owner or an actor.
  122. --
  123. -- @param actor Actor whose actor fields or variables are read.
  124. function Context:read(address, size, actor)
  125. if address < 0x2000 then
  126. return read_bytes(variables_of(actor), address, size)
  127. elseif address < 0x4000 then
  128. return self.host:read_global(address, size)
  129. end
  130. return self.host:read_actor(actor, address - 0x4000, size)
  131. end
  132. --- Writes a value to a memory address, of an actor or its variables.
  133. function Context:write(address, size, value, actor)
  134. if address < 0x2000 then
  135. write_bytes(variables_of(actor), address, size, value)
  136. elseif address < 0x4000 then
  137. self.host:write_global(address, size, value)
  138. else
  139. self.host:write_actor(actor, address - 0x4000, size, value)
  140. end
  141. end
  142. --- Gets the number a stack entry stands for.
  143. --
  144. -- Addresses give their value, and entries that stand for several actors the value of the first.
  145. function Context:value_of(entry)
  146. if entry.kind == "value" then return entry.v end
  147. if entry.kind == "address" then
  148. if entry.mask ~= nil then return self:first_value(entry) end
  149. return self:read(entry.address, entry.size, self.owner)
  150. end
  151. return self:first_value(entry)
  152. end
  153. --- Gets the value of the first actor of a masked entry.
  154. function Context:first_value(entry)
  155. local result = 0
  156. for actor = 0, 31 do
  157. if math.floor(entry.mask / 2 ^ actor) % 2 == 1 then
  158. return self:read(entry.address, entry.size, actor)
  159. end
  160. end
  161. return result
  162. end
  163. --- Pushes a value.
  164. function Context:push(entry)
  165. self.top = self.top + 1
  166. self.stack[self.top] = entry
  167. end
  168. --- Pops an entry from the stack.
  169. function Context:pop()
  170. local entry = self.stack[self.top]
  171. if entry == nil then error("AI script: the stack is empty") end
  172. self.stack[self.top] = nil
  173. self.top = self.top - 1
  174. return entry
  175. end
  176. --- Pushes a plain number.
  177. function Context:push_value(size, value)
  178. self:push({kind = "value", size = size, v = value})
  179. end
  180. --- Gets the actor mask an entry stands for (values are masks, addresses give their value).
  181. function Context:mask_of(entry)
  182. return math.floor(self:value_of(entry))
  183. end
  184. --- Compares two entries with an operator, for the comparison opcodes.
  185. --
  186. -- If one of them has an actor mask, the result is the mask of the actors that pass the comparison.
  187. -- Otherwise it's 1 or 0.
  188. local function compare(op, a, b)
  189. if op == 0x40 then return a == b
  190. elseif op == 0x41 then return a ~= b
  191. elseif op == 0x42 then return a >= b
  192. elseif op == 0x43 then return a <= b
  193. elseif op == 0x44 then return a > b
  194. elseif op == 0x45 then return a < b
  195. end
  196. return false
  197. end
  198. function Context:compare(op, second, first)
  199. -- "first" is the first pop (the right operand), "second" the second pop.
  200. local left_masked = second.mask ~= nil and (second.kind == "multi" or second.kind == "address")
  201. local right_masked = first.mask ~= nil and (first.kind == "multi" or first.kind == "address")
  202. if not left_masked and not right_masked then
  203. return {kind = "value", size = 0, v = compare(op, self:value_of(second), self:value_of(first)) and 1 or 0}
  204. end
  205. local mask = left_masked and second.mask or first.mask
  206. if left_masked and right_masked then mask = band(second.mask, first.mask) end
  207. local passed = 0
  208. each_actor(mask, function(actor)
  209. local a = left_masked and self:read(second.address, second.size, actor) or self:value_of(second)
  210. local b = right_masked and self:read(first.address, first.size, actor) or self:value_of(first)
  211. if compare(op, a, b) then passed = passed + 2 ^ actor end
  212. end)
  213. return {kind = "value", size = 2, v = passed}
  214. end
  215. --- Runs a script.
  216. --
  217. -- @param code The bytecode, as a string.
  218. -- @param owner Index of the actor that owns the script.
  219. -- @param host The host of the interpreter.
  220. -- @return True if it finished, false if it was stopped (error or too many instructions).
  221. function BattleAI.run(code, owner, host)
  222. -- The host needs to know who is running the script to answer about "self".
  223. host.owner = owner
  224. local ctx = setmetatable({owner = owner, host = host, stack = {}, top = 0}, Context)
  225. local pc = 0
  226. local steps = 0
  227. local length = #code
  228. local function byte(i) return code:byte(i + 1) end
  229. local function word(i) return byte(i) + byte(i + 1) * 256 end
  230. while pc < length do
  231. steps = steps + 1
  232. if steps > BattleAI.MAX_STEPS then return false, "too many instructions" end
  233. local op = byte(pc)
  234. local hi, lo = math.floor(op / 16), op % 16
  235. if hi == 0 and lo <= 3 then
  236. -- Push the value at an address. Actor fields remember their address, so they can be
  237. -- masked with actors later.
  238. local address = word(pc + 1)
  239. ctx:push({kind = "value", size = lo, v = ctx:read(address, lo, owner), address = address})
  240. pc = pc + 3
  241. elseif hi == 1 and lo <= 3 then
  242. ctx:push({kind = "address", size = lo, address = word(pc + 1)})
  243. pc = pc + 3
  244. elseif op >= 0x60 and op <= 0x62 then
  245. local size = op - 0x5F
  246. local value = 0
  247. for i = size - 1, 0, -1 do value = value * 256 + byte(pc + 1 + i) end
  248. ctx:push_value(size, value)
  249. pc = pc + 1 + size
  250. elseif op >= 0x30 and op <= 0x37 then
  251. if op == 0x37 then
  252. local a = ctx:pop()
  253. ctx:push_value(2, bnot(ctx:value_of(a), 16))
  254. else
  255. local b = ctx:pop()
  256. local a = ctx:pop()
  257. local x, y = ctx:value_of(a), ctx:value_of(b)
  258. local r
  259. if op == 0x30 then r = x + y
  260. elseif op == 0x31 then r = x - y
  261. elseif op == 0x32 then r = x * y
  262. elseif op == 0x33 then r = y ~= 0 and math.floor(x / y) or 0
  263. elseif op == 0x34 then r = y ~= 0 and x % y or 0
  264. elseif op == 0x35 then r = band(x, y)
  265. else r = bor(x, y)
  266. end
  267. ctx:push_value(math.max(a.size or 2, b.size or 2, 2), r)
  268. end
  269. pc = pc + 1
  270. elseif op >= 0x40 and op <= 0x45 then
  271. local first = ctx:pop()
  272. local second = ctx:pop()
  273. ctx:push(ctx:compare(op, second, first))
  274. pc = pc + 1
  275. elseif op >= 0x50 and op <= 0x52 then
  276. if op == 0x52 then
  277. local a = ctx:pop()
  278. ctx:push_value(0, ctx:value_of(a) == 0 and 1 or 0)
  279. else
  280. local b = ctx:pop()
  281. local a = ctx:pop()
  282. local x, y = ctx:value_of(a) ~= 0, ctx:value_of(b) ~= 0
  283. local r
  284. if op == 0x50 then r = x and y else r = x or y end
  285. ctx:push_value(0, r and 1 or 0)
  286. end
  287. pc = pc + 1
  288. elseif op == 0x70 then
  289. -- Jump if the value is zero.
  290. local a = ctx:pop()
  291. if ctx:value_of(a) == 0 then pc = word(pc + 1) else pc = pc + 3 end
  292. elseif op == 0x71 then
  293. -- Jump if the value is different from the top of the stack (switch cases).
  294. local a = ctx:pop()
  295. local top = ctx.stack[ctx.top]
  296. if top == nil or ctx:value_of(a) ~= ctx:value_of(top) then pc = word(pc + 1) else pc = pc + 3 end
  297. elseif op == 0x72 then
  298. pc = word(pc + 1)
  299. elseif op == 0x73 then
  300. return true
  301. elseif op == 0x74 or op == 0x75 then
  302. ctx:pop()
  303. pc = pc + 1
  304. elseif op >= 0x80 and op <= 0x87 then
  305. if op == 0x80 then
  306. -- The first pop is masked by the second: an address or a value of an actor field
  307. -- is for those actors, two plain values are ANDed.
  308. local first = ctx:pop()
  309. local second = ctx:pop()
  310. local mask = ctx:mask_of(second)
  311. if first.kind == "address" then
  312. ctx:push({kind = "address", size = first.size, address = first.address, mask = mask})
  313. elseif first.address ~= nil and (first.address >= 0x4000 or first.address < 0x2000) then
  314. ctx:push({kind = "multi", size = first.size, address = first.address, mask = mask})
  315. else
  316. ctx:push_value(math.max(first.size or 2, 2), band(ctx:value_of(first), mask))
  317. end
  318. elseif op == 0x81 then
  319. ctx:push_value(2, host:random(65536))
  320. elseif op == 0x82 then
  321. -- A random one of the bits that are on.
  322. local mask = ctx:mask_of(ctx:pop())
  323. local bits = {}
  324. each_actor(mask, function(actor) table.insert(bits, actor) end)
  325. if #bits == 0 then ctx:push_value(2, 0)
  326. else ctx:push_value(2, 2 ^ bits[host:random(#bits) + 1])
  327. end
  328. elseif op == 0x83 then
  329. local a = ctx:pop()
  330. local value = math.floor(ctx:value_of(a))
  331. if a.size == 1 or a.size == 0 then
  332. local count = 0
  333. each_actor(value, function() count = count + 1 end)
  334. ctx:push_value(1, count)
  335. else
  336. -- The first bit that is on, as a value with only that bit.
  337. local result = 0
  338. for bit = 0, 31 do
  339. if math.floor(value / 2 ^ bit) % 2 == 1 then result = 2 ^ bit break end
  340. end
  341. ctx:push_value(2, result)
  342. end
  343. elseif op == 0x84 or op == 0x85 then
  344. -- The actors with the highest (or lowest) value of a masked entry.
  345. local a = ctx:pop()
  346. local best, mask = nil, 0
  347. if a.mask ~= nil then
  348. each_actor(a.mask, function(actor)
  349. local value = ctx:read(a.address, a.size, actor)
  350. if best == nil or (op == 0x84 and value > best) or (op == 0x85 and value < best) then
  351. best, mask = value, 2 ^ actor
  352. elseif value == best then
  353. mask = mask + 2 ^ actor
  354. end
  355. end)
  356. end
  357. ctx:push_value(2, mask)
  358. elseif op == 0x86 then
  359. local a = ctx:pop()
  360. ctx:push_value(2, host:mp_cost(math.floor(ctx:value_of(a))))
  361. else
  362. local a = ctx:pop()
  363. ctx:push_value(2, 2 ^ math.floor(ctx:value_of(a)))
  364. end
  365. pc = pc + 1
  366. elseif op == 0x90 then
  367. -- Store the value on top of the address below it. Entries with an actor mask store
  368. -- the value in every actor of the mask.
  369. local value = ctx:pop()
  370. local target = ctx:pop()
  371. if target.kind ~= "address" then
  372. -- Some scripts push the value first: swap if so.
  373. if value.kind == "address" then value, target = target, value end
  374. end
  375. if target.kind == "address" then
  376. local v = ctx:value_of(value)
  377. if target.mask ~= nil then
  378. each_actor(target.mask, function(actor) ctx:write(target.address, target.size, v, actor) end)
  379. else
  380. ctx:write(target.address, target.size, v, owner)
  381. end
  382. end
  383. pc = pc + 1
  384. elseif op == 0x91 then
  385. ctx:pop()
  386. pc = pc + 1
  387. elseif op == 0x92 then
  388. local id = ctx:pop()
  389. local kind = ctx:pop()
  390. host:action(owner, math.floor(ctx:value_of(kind)), math.floor(ctx:value_of(id)))
  391. pc = pc + 1
  392. elseif op == 0x93 then
  393. -- A text, in the FF7 encoding, finished with 0xFF.
  394. local stop = pc + 1
  395. while stop < length and byte(stop) ~= 0xFF do stop = stop + 1 end
  396. host:text(owner, code:sub(pc + 2, stop))
  397. pc = stop + 1
  398. elseif op == 0x94 then
  399. -- Copy the state of some actors to others. Not used by the battle yet.
  400. ctx:pop()
  401. ctx:pop()
  402. pc = pc + 1
  403. elseif op == 0x95 then
  404. -- Access to the memory banks 1 and 2 of the game: read or write, at an offset.
  405. local offset = ctx:pop()
  406. local write = ctx:pop()
  407. host:memory_bank(ctx:value_of(write) == 1, ctx:value_of(offset))
  408. pc = pc + 1
  409. elseif op == 0x96 then
  410. ctx:pop()
  411. ctx:pop()
  412. ctx:push_value(2, 0)
  413. pc = pc + 1
  414. elseif op == 0xA0 then
  415. -- Debug text, with one value for each "%d". Skipped.
  416. local stop = pc + 2
  417. while stop < length and byte(stop) ~= 0 do stop = stop + 1 end
  418. local text = code:sub(pc + 3, stop)
  419. for _ in text:gmatch("%%d") do ctx:pop() end
  420. pc = stop + 1
  421. elseif op == 0xA1 then
  422. ctx:pop()
  423. ctx:pop()
  424. pc = pc + 1
  425. else
  426. -- Anything else does nothing.
  427. pc = pc + 1
  428. end
  429. end
  430. return true
  431. end
  432. --- Runs a script protected from errors.
  433. --
  434. -- @return True if it finished correctly.
  435. function BattleAI.run_safe(code, owner, host)
  436. local ok, result, reason = pcall(BattleAI.run, code, owner, host)
  437. if not ok then
  438. print("AI script error: " .. tostring(result))
  439. return false
  440. end
  441. if result == false then print("AI script stopped: " .. tostring(reason)) end
  442. return result
  443. end