FieldCodeGenerator.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. // The variables hold the values in the units of the original game, like the values
  236. // written in the opcodes, so a float one has to be scaled the same way.
  237. if (bank != 0 && type == ValueType::Float && scale != 1.0f){
  238. return (
  239. boost::format("(%1% / %2%)")
  240. % FormatValueOrVariable(formatter, bank, value_or_address, ValueType::Integer)
  241. % scale
  242. ).str();
  243. }
  244. switch (bank){
  245. case 0:
  246. switch (type){
  247. // TODO: check for zero
  248. case ValueType::Float: return std::to_string(value_or_address / scale);
  249. case ValueType::Integer: return std::to_string(value_or_address);
  250. default: return std::to_string(value_or_address);
  251. }
  252. case 1:
  253. case 2:
  254. case 3:
  255. case 13:
  256. case 15:
  257. {
  258. const auto address = static_cast<uint32>(value_or_address) & 0xFF;
  259. const auto friendly_name = formatter.GetFriendlyVarName(
  260. bank, value_or_address
  261. );
  262. if (friendly_name.empty())
  263. return (boost::format("Banks[%1%][%2%]") % bank % address).str();
  264. return (
  265. boost::format("Banks[%1%][%2%]--[[%3%]]") % bank % address % friendly_name
  266. ).str();
  267. }
  268. case 5:
  269. case 6:
  270. {
  271. const auto address = static_cast<uint32>(value_or_address)& 0xFF;
  272. const auto friendly_name = formatter.GetFriendlyVarName(bank, address);
  273. if (friendly_name.empty())
  274. return (boost::format("Banks[%1%][%2%]") % bank % address).str();
  275. return (
  276. boost::format("Banks[%1%][%2%]--[[%3%]]") % bank % address % friendly_name
  277. ).str();
  278. }
  279. default:
  280. return (
  281. boost::format(
  282. "Banks[%1%][%2%]"
  283. ) % bank % (static_cast<uint32>(value_or_address) & 0xFF)
  284. ).str();
  285. }
  286. }
  287. /**
  288. * Constructor.
  289. *
  290. * @param[in] engine The engine.
  291. * @param[in] insts The list of instructions to parse.
  292. * @param[out] output The generated script.
  293. * @param[in] formatter The code formatter.
  294. */
  295. FieldCodeGenerator(
  296. Engine *engine, const InstVec& insts, std::ostream &output,
  297. FieldScriptFormatter& formatter
  298. ) :
  299. CodeGenerator(engine, output, FIFO_ARGUMENT_ORDER, LIFO_ARGUMENT_ORDER),
  300. insts_(insts), formatter_(formatter)
  301. {target_lang_ = std::make_unique<LuaLanguage>();}
  302. /**
  303. * Generates the script from the instructions.
  304. *
  305. * @param[in] insts The list of instructions.
  306. * @param[in] graph Code graph, unused.
  307. */
  308. virtual void Generate(InstVec& insts, const Graph &graph) override;
  309. /**
  310. * Adds a line to the script.
  311. *
  312. * @param[in] line The line to add.
  313. * @param[in] unindent_before If true, the current script indentation
  314. * will be moved back one position before the line.
  315. * @param[in] indent_after If true, the current script indentation
  316. * will be moved forward one position after the line.
  317. */
  318. virtual void AddOutputLine(
  319. std::string line, bool unindent_before = false, bool indent_after = false
  320. ) override;
  321. /**
  322. * Retrieves the engine scale factor.
  323. *
  324. * @return The scale factor
  325. */
  326. float GetScaleFactor() const;
  327. /**
  328. * Retrieves the formatter.
  329. */
  330. FieldScriptFormatter& GetFormatter();
  331. /**
  332. * Checks if any script of the field defines a dialog window.
  333. *
  334. * A window is defined with the WINDOW or WSIZW opcodes. Fields can show messages in
  335. * windows that are never defined.
  336. *
  337. * @param[in] window_id Window ID.
  338. * @return True if the field defines the window.
  339. */
  340. bool IsWindowDefined(uint32 window_id) const;
  341. /**
  342. * Position and size of the window for messages shown in a window that is never defined.
  343. *
  344. * These are the same values the engine uses for its own script messages.
  345. */
  346. static const int DEFAULT_WINDOW_X;
  347. static const int DEFAULT_WINDOW_Y;
  348. static const int DEFAULT_WINDOW_WIDTH;
  349. static const int DEFAULT_WINDOW_HEIGHT;
  350. protected:
  351. /**
  352. * Constructs the function signature.
  353. *
  354. * The function signature is the LUA function declaration, and it
  355. * looks like this:
  356. *
  357. * function_name = function(self)
  358. *
  359. * @param[in] function The function to construct the signature for.
  360. * @return The function signature.
  361. */
  362. virtual std::string ConstructFuncSignature(const Function &function) override;
  363. /**
  364. * Finalizes a function.
  365. *
  366. * It appends an "end" to finalize the function. If the function is
  367. * the last of a class, it also closes the class braces.
  368. *
  369. * @param[in] function The function to end.
  370. */
  371. virtual void OnEndFunction(const Function& function) override;
  372. /**
  373. * Adds lines to the script before a function.
  374. *
  375. * If the function is the first in a class, it initializes the class
  376. * and, if the function belongs to a character, creates the class
  377. * variable for the character. If the function has a comment
  378. * associated, it will also be added before the function.
  379. *
  380. * @param[in] function The function about to start.
  381. */
  382. virtual void OnBeforeStartFunction(const Function& function) override;
  383. /**
  384. * Initializes a function.
  385. *
  386. * It adds a comment with the function opcodes.
  387. *
  388. * @param[in] function The function to start.
  389. */
  390. virtual void OnStartFunction(const Function& function) override;
  391. /**
  392. * Checks if only required labels are to be written.
  393. *
  394. * @return Always true.
  395. */
  396. virtual bool OutputOnlyRequiredLabels() const override;
  397. private:
  398. /**
  399. * The list of instructions in the function to generate.
  400. */
  401. const InstVec& insts_;
  402. /**
  403. * Generated lines.
  404. */
  405. std::vector<CodeLine> lines_;
  406. /**
  407. * The formatter.
  408. */
  409. FieldScriptFormatter& formatter_;
  410. /**
  411. * IDs of the dialog windows defined by the field. Filled the first time it is needed.
  412. */
  413. mutable std::set<uint32> defined_windows_;
  414. /**
  415. * Whether defined_windows_ has been filled.
  416. */
  417. mutable bool defined_windows_collected_ = false;
  418. };