FieldCodeGenerator.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #pragma once
  16. #include <deque>
  17. #include <set>
  18. #include <unordered_map>
  19. #include <boost/algorithm/string.hpp>
  20. #include "FieldScriptFormatter.h"
  21. #include "installer/decompiler/CodeGenerator.h"
  22. /**
  23. * Parses an stores function metadata.
  24. *
  25. * Function metadata can indicate the entity and character of a function, and
  26. * if the function is the first or last in a class.
  27. */
  28. class FunctionMetaData{
  29. public:
  30. /**
  31. * Constructor. Parses function metadata.
  32. *
  33. * Meta data format can be:
  34. * - start_end_entityname
  35. * - start_entityname
  36. * - end_entity_name
  37. *
  38. * @param[in] meta_data Metadata to parse.
  39. */
  40. FunctionMetaData(std::string meta_data);
  41. /**
  42. * Checks if the function is the first of a class.
  43. *
  44. * @return True if the metadata is the first of a class, false
  45. * otherwise.
  46. */
  47. bool IsStart() const;
  48. /**
  49. * Checks if the function is the last of a class.
  50. *
  51. * @return True if the metadata is the last of a class, false
  52. * otherwise.
  53. */
  54. bool IsEnd() const;
  55. /**
  56. * Retrieves the entity name.
  57. *
  58. * @return The entity name.
  59. */
  60. std::string GetEntityName();
  61. /**
  62. * Retrieves the character ID.
  63. *
  64. * @return The character ID.
  65. */
  66. int GetCharacterId();
  67. private:
  68. /**
  69. * Delimiter for metadata tokens.
  70. */
  71. static const std::string DELIMITER;
  72. /**
  73. * Start tag for metadata.
  74. */
  75. static const std::string START;
  76. /**
  77. * End tag for metadata.
  78. */
  79. static const std::string END;
  80. /**
  81. * Parses metadata.
  82. *
  83. * @param[in] meta_data Metadata to parse.
  84. */
  85. void Parse(std::string meta_data);
  86. /**
  87. * Parses a metadata item, looking for a start mark.
  88. *
  89. * If it finds it, marks the metadata as the first function of a
  90. * class. It also * calls {@see ParseEnd} with the next token.
  91. *
  92. * @param[in] item The item to check for a start mark.
  93. * @param[in] strs All the metadata tokens.
  94. */
  95. void ParseStart(const std::string& item, std::deque<std::string>& strs);
  96. /**
  97. * Parses a metadata item, looking for an end mark.
  98. *
  99. * If it finds it, marks the metadata as the last function of a class.
  100. * It also calls {@see ParseCharId}.
  101. *
  102. * @param[in] item The item to check for a start mark.
  103. * @param[in] strs Metadata tokens, first removed.
  104. */
  105. void ParseEnd(const std::string& item, std::deque<std::string>& strs);
  106. /**
  107. * Parses a metadata item, looking for a character ID.
  108. *
  109. * If it finds it, sets the character ID. It also calls
  110. * {@see ParseEntity}.
  111. *
  112. * @param[in] item The item to check for a start mark.
  113. * @param[in] strs Metadata tokens, first two removed.
  114. */
  115. void ParseCharId(const std::string& item, std::deque<std::string>& strs);
  116. /**
  117. * Parses a metadata item, looking for an entity name.
  118. *
  119. * It sets the entity name.
  120. *
  121. * @param[in] item The item to check for a start mark.
  122. * @param[in] strs Metadata tokens, first three removed.
  123. */
  124. void ParseEntity(const std::string& item, std::deque<std::string>& strs);
  125. /**
  126. * Indicates if the function is the last of a class.
  127. */
  128. bool end_ = false;
  129. /**
  130. * Indicates if the function is the first of a class.
  131. */
  132. bool start_ = false;
  133. /**
  134. * The entity name.
  135. */
  136. std::string entity_name_;
  137. /**
  138. * The character ID.
  139. */
  140. int character_id_ = -1;
  141. };
  142. /**
  143. * The code generator.
  144. *
  145. * Generates code for a field map function.
  146. */
  147. class FieldCodeGenerator : public CodeGenerator{
  148. public:
  149. /**
  150. * Lua condition that tells an on_update script has already reached its end.
  151. *
  152. * The engine runs on_update again every time it finishes, but in the original game a
  153. * script that returns is over for good.
  154. */
  155. static const std::string ON_UPDATE_FINISHED_CONDITION;
  156. /**
  157. * Lua statement that marks an on_update script as finished.
  158. */
  159. static const std::string ON_UPDATE_FINISHED_STATEMENT;
  160. /**
  161. * Type of data.
  162. */
  163. enum struct ValueType : int{
  164. /**
  165. * Integer.
  166. */
  167. Integer = 0,
  168. /**
  169. * Float.
  170. */
  171. Float = 1
  172. };
  173. /**
  174. * Generates code for an unimplemented instruction.
  175. *
  176. * The code will actually be a comment, indicating where the function
  177. * call must have been.
  178. *
  179. * @param[in] entity The entity name.
  180. * @param[in] address The address of the instruction.
  181. * @param[in] opcode The opcode not implemented.
  182. */
  183. static const std::string FormatInstructionNotImplemented(
  184. const std::string& entity, uint32 address, uint32 opcode
  185. );
  186. /**
  187. * Generates code for an unimplemented instruction.
  188. *
  189. * The code will actually be a comment, indicating where the function
  190. * call must have been.
  191. *
  192. * @param[in] entity The entity name.
  193. * @param[in] address The address of the instruction.
  194. * @param[in] instruction The unimplemented instruction.
  195. */
  196. static const std::string FormatInstructionNotImplemented(
  197. const std::string& entity, uint32 address, const Instruction& instruction
  198. );
  199. /**
  200. * Formats a value as a boolean.
  201. *
  202. * @param[in] value The value to format.
  203. * @return "false" if the value is 0, "true" otherwise.
  204. */
  205. static const std::string FormatBool(uint32 value);
  206. /**
  207. * Formats a value as a boolean.
  208. *
  209. * @param[in] value The value to format.
  210. * @return "true" if the value is 0, "false" otherwise.
  211. */
  212. static const std::string FormatInvertedBool(uint32 value);
  213. /**
  214. * Formats a data access for a map script.
  215. *
  216. * If possible, it will look for friendly names for variables.
  217. *
  218. * @param[in] formatter Formatter to look up variable friendly names.
  219. * @param[in] bank The memory bank to use.
  220. * @param[in] value_or_address The value or memory address to use.
  221. * When bank is 0, it will be considered as a value. When bank is non
  222. * 0, it will be considered an address of the bank.
  223. * @param[in] type Data type to use. Used only when getting a
  224. * value, not a bank address.
  225. * @param[in] scale Scale to scale values to. Used only when using
  226. * float values, unused when type is integer or when using a bank
  227. * address.
  228. * @return String with the friendly variable name, value, or bank
  229. * address.
  230. */
  231. template<typename TValue>static const std::string FormatValueOrVariable(
  232. FieldScriptFormatter& formatter, uint32 bank, TValue value_or_address,
  233. ValueType type = ValueType::Integer, float scale = 1.0f
  234. ){
  235. switch (bank){
  236. case 0:
  237. switch (type){
  238. // TODO: check for zero
  239. case ValueType::Float: return std::to_string(value_or_address / scale);
  240. case ValueType::Integer: return std::to_string(value_or_address);
  241. default: return std::to_string(value_or_address);
  242. }
  243. case 1:
  244. case 2:
  245. case 3:
  246. case 13:
  247. case 15:
  248. {
  249. const auto address = static_cast<uint32>(value_or_address) & 0xFF;
  250. const auto friendly_name = formatter.GetFriendlyVarName(
  251. bank, value_or_address
  252. );
  253. if (friendly_name.empty())
  254. return (boost::format("Banks[%1%][%2%]") % bank % address).str();
  255. return (
  256. boost::format("Banks[%1%][%2%]--[[%3%]]") % bank % address % friendly_name
  257. ).str();
  258. }
  259. case 5:
  260. case 6:
  261. {
  262. const auto address = static_cast<uint32>(value_or_address)& 0xFF;
  263. const auto friendly_name = formatter.GetFriendlyVarName(bank, address);
  264. if (friendly_name.empty())
  265. return (boost::format("Banks[%1%][%2%]") % bank % address).str();
  266. return (
  267. boost::format("Banks[%1%][%2%]--[[%3%]]") % bank % address % friendly_name
  268. ).str();
  269. }
  270. default:
  271. return (
  272. boost::format(
  273. "Banks[%1%][%2%]"
  274. ) % bank % (static_cast<uint32>(value_or_address) & 0xFF)
  275. ).str();
  276. }
  277. }
  278. /**
  279. * Constructor.
  280. *
  281. * @param[in] engine The engine.
  282. * @param[in] insts The list of instructions to parse.
  283. * @param[out] output The generated script.
  284. * @param[in] formatter The code formatter.
  285. */
  286. FieldCodeGenerator(
  287. Engine *engine, const InstVec& insts, std::ostream &output,
  288. FieldScriptFormatter& formatter
  289. ) :
  290. CodeGenerator(engine, output, FIFO_ARGUMENT_ORDER, LIFO_ARGUMENT_ORDER),
  291. insts_(insts), formatter_(formatter)
  292. {target_lang_ = std::make_unique<LuaLanguage>();}
  293. /**
  294. * Generates the script from the instructions.
  295. *
  296. * @param[in] insts The list of instructions.
  297. * @param[in] graph Code graph, unused.
  298. */
  299. virtual void Generate(InstVec& insts, const Graph &graph) override;
  300. /**
  301. * Adds a line to the script.
  302. *
  303. * @param[in] line The line to add.
  304. * @param[in] unindent_before If true, the current script indentation
  305. * will be moved back one position before the line.
  306. * @param[in] indent_after If true, the current script indentation
  307. * will be moved forward one position after the line.
  308. */
  309. virtual void AddOutputLine(
  310. std::string line, bool unindent_before = false, bool indent_after = false
  311. ) override;
  312. /**
  313. * Retrieves the engine scale factor.
  314. *
  315. * @return The scale factor
  316. */
  317. float GetScaleFactor() const;
  318. /**
  319. * Retrieves the formatter.
  320. */
  321. FieldScriptFormatter& GetFormatter();
  322. /**
  323. * Checks if any script of the field defines a dialog window.
  324. *
  325. * A window is defined with the WINDOW or WSIZW opcodes. Fields can show messages in
  326. * windows that are never defined.
  327. *
  328. * @param[in] window_id Window ID.
  329. * @return True if the field defines the window.
  330. */
  331. bool IsWindowDefined(uint32 window_id) const;
  332. /**
  333. * Position and size of the window for messages shown in a window that is never defined.
  334. *
  335. * These are the same values the engine uses for its own script messages.
  336. */
  337. static const int DEFAULT_WINDOW_X;
  338. static const int DEFAULT_WINDOW_Y;
  339. static const int DEFAULT_WINDOW_WIDTH;
  340. static const int DEFAULT_WINDOW_HEIGHT;
  341. protected:
  342. /**
  343. * Constructs the function signature.
  344. *
  345. * The function signature is the LUA function declaration, and it
  346. * looks like this:
  347. *
  348. * function_name = function(self)
  349. *
  350. * @param[in] function The function to construct the signature for.
  351. * @return The function signature.
  352. */
  353. virtual std::string ConstructFuncSignature(const Function &function) override;
  354. /**
  355. * Finalizes a function.
  356. *
  357. * It appends an "end" to finalize the function. If the function is
  358. * the last of a class, it also closes the class braces.
  359. *
  360. * @param[in] function The function to end.
  361. */
  362. virtual void OnEndFunction(const Function& function) override;
  363. /**
  364. * Adds lines to the script before a function.
  365. *
  366. * If the function is the first in a class, it initializes the class
  367. * and, if the function belongs to a character, creates the class
  368. * variable for the character. If the function has a comment
  369. * associated, it will also be added before the function.
  370. *
  371. * @param[in] function The function about to start.
  372. */
  373. virtual void OnBeforeStartFunction(const Function& function) override;
  374. /**
  375. * Initializes a function.
  376. *
  377. * It adds a comment with the function opcodes.
  378. *
  379. * @param[in] function The function to start.
  380. */
  381. virtual void OnStartFunction(const Function& function) override;
  382. /**
  383. * Checks if only required labels are to be written.
  384. *
  385. * @return Always true.
  386. */
  387. virtual bool OutputOnlyRequiredLabels() const override;
  388. private:
  389. /**
  390. * The list of instructions in the function to generate.
  391. */
  392. const InstVec& insts_;
  393. /**
  394. * Generated lines.
  395. */
  396. std::vector<CodeLine> lines_;
  397. /**
  398. * The formatter.
  399. */
  400. FieldScriptFormatter& formatter_;
  401. /**
  402. * IDs of the dialog windows defined by the field. Filled the first time it is needed.
  403. */
  404. mutable std::set<uint32> defined_windows_;
  405. /**
  406. * Whether defined_windows_ has been filled.
  407. */
  408. mutable bool defined_windows_collected_ = false;
  409. };