ScriptManager.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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. #include <algorithm>
  16. #include "engine/config/ConfigVar.h"
  17. #include "engine/graphics/DebugDraw.h"
  18. #include "common/Logger.h"
  19. #include "engine/script/ScriptManager.h"
  20. #include "engine/script/ScriptManagerBinds.h"
  21. #include "engine/script/ScriptManagerCommands.h"
  22. #include "engine/Timer.h"
  23. #include "common/Utilities.h"
  24. #include "engine/xml/XmlScriptsFile.h"
  25. #include "LuaIncludes.h"
  26. ConfigVar cv_debug_script(
  27. "debug_script", "Debug script flags. 0x01 - System, 0x02 - Entity, 0x04 - Ui.", "0"
  28. );
  29. /**
  30. * Script manager singleton.
  31. */
  32. template<>ScriptManager *Ogre::Singleton<ScriptManager>::msSingleton = nullptr;
  33. Ogre::String script_entity_type[] = {"SYSTEM", "ENTITY", "UI", "BATTLE"};
  34. /**
  35. * Compares the priority of two scripts.
  36. *
  37. * @param[in] a The first script to compare.
  38. * @param[in] b The second script to compare.
  39. * @return True if the script a has a lower priority number than b, false if a has a higher or
  40. * equal priority than b.
  41. */
  42. bool priority_queue_compare(QueueScript a, QueueScript b){return a.priority < b.priority;}
  43. ScriptManager::ScriptManager(const std::vector<ModuleBinder>& module_binders):
  44. system_table_name_("System"), entity_table_name_("EntityContainer"), ui_table_name_("UiContainer")
  45. {
  46. lua_state_ = lua_open();
  47. sol::register_main_thread(lua_state_);
  48. luaopen_base(lua_state_);
  49. luaopen_string(lua_state_);
  50. luaopen_table(lua_state_);
  51. luaopen_math(lua_state_);
  52. luaopen_io(lua_state_);
  53. InitBinds();
  54. for (ModuleBinder bind : module_binders) bind(lua_state_);
  55. InitCmd();
  56. // TODO: Use the one in data/ ?
  57. RunFile("system/system.lua");
  58. XmlScriptsFile scripts("./data/scripts/_scripts.xml");
  59. scripts.LoadScripts();
  60. }
  61. ScriptManager::~ScriptManager(){lua_close(lua_state_);}
  62. void ScriptManager::Input(const VGears::Event& event){
  63. if (
  64. event.event != ""
  65. && (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
  66. ){
  67. Ogre::String argument2 = "";
  68. if (event.type == VGears::ET_KEY_PRESS) argument2 = "Press";
  69. else if (event.type == VGears::ET_KEY_REPEAT_WAIT) argument2 = "Repeat";
  70. const Ogre::String source_key = KeyToString(
  71. static_cast<OIS::KeyCode>(event.param1)
  72. );
  73. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  74. ScriptRequest(
  75. &script_entity_[i], "on_button", 100,
  76. event.event, argument2, false, false, source_key, true
  77. );
  78. }
  79. return;
  80. }
  81. if (
  82. (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
  83. && (
  84. // Only the keys that scripts read by themselves reach them as raw keys: the letters and the
  85. // space bar, to type in the name menu and for the debug keys of the battle. Everything else
  86. // goes through the game events of config.cfg, so it can be remapped.
  87. // TODO: Do this the other way: block keys NOT TO pass to scripts.
  88. event.param1 == OIS::KC_SPACE
  89. || event.param1 == OIS::KC_A || event.param1 == OIS::KC_B || event.param1 == OIS::KC_C
  90. || event.param1 == OIS::KC_D || event.param1 == OIS::KC_E || event.param1 == OIS::KC_F
  91. || event.param1 == OIS::KC_G || event.param1 == OIS::KC_H || event.param1 == OIS::KC_I
  92. || event.param1 == OIS::KC_J || event.param1 == OIS::KC_K || event.param1 == OIS::KC_L
  93. || event.param1 == OIS::KC_M || event.param1 == OIS::KC_N || event.param1 == OIS::KC_O
  94. || event.param1 == OIS::KC_P || event.param1 == OIS::KC_Q || event.param1 == OIS::KC_R
  95. || event.param1 == OIS::KC_S || event.param1 == OIS::KC_T || event.param1 == OIS::KC_U
  96. || event.param1 == OIS::KC_V || event.param1 == OIS::KC_W || event.param1 == OIS::KC_X
  97. || event.param1 == OIS::KC_Y || event.param1 == OIS::KC_Z || event.param1 == OIS::KC_X
  98. )
  99. ){
  100. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  101. Ogre::String argument2 = "";
  102. if (event.type == VGears::ET_KEY_PRESS) argument2 = "Press";
  103. else if (event.type == VGears::ET_KEY_REPEAT_WAIT) argument2 = "Repeat";
  104. ScriptRequest(
  105. &script_entity_[i], "on_button", 100,
  106. KeyToString((OIS::KeyCode) ((int) event.param1)), argument2, false, false
  107. );
  108. }
  109. }
  110. }
  111. void ScriptManager::Update(const ScriptManager::Type type){
  112. // Remove the scripts that a request has replaced.
  113. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  114. if (script_entity_[i].type != type) continue;
  115. for (size_t k = script_entity_[i].queue.size(); k --;){
  116. if (script_entity_[i].queue[k].replaced) RemoveEntityScript(script_entity_[i], k);
  117. }
  118. }
  119. // Resort all queue. This will give correct info for debug draw.
  120. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  121. if (script_entity_[i].type == type){
  122. if (script_entity_[i].queue.size() > 0){
  123. if (script_entity_[i].resort == true){
  124. std::stable_sort(
  125. script_entity_[i].queue.begin(),
  126. script_entity_[i].queue.end(), priority_queue_compare
  127. );
  128. script_entity_[i].resort = false;
  129. }
  130. }
  131. }
  132. }
  133. // Draw debug before update. This way it will be possible to see
  134. // scripts that run once
  135. int debug = cv_debug_script.GetI();
  136. if (debug != 0){
  137. DEBUG_DRAW.SetTextAlignment(DEBUG_DRAW.LEFT);
  138. DEBUG_DRAW.SetScreenSpace(true);
  139. int y = 34;
  140. for (unsigned int i = 0; i < 3; ++ i){
  141. if ((debug & (1 << i)) != 0){
  142. DEBUG_DRAW.SetColour(Ogre::ColourValue(0.8f, 0.8f, 0.0f, 1.0f));
  143. DEBUG_DRAW.Text(
  144. 10.0f, static_cast<float>(y), "Script \"" + script_entity_type[i] + "\" entity:"
  145. );
  146. y += 16;
  147. for (unsigned int j = 0; j < script_entity_.size(); ++ j){
  148. if (script_entity_[j].type == i){
  149. Ogre::String text = script_entity_[j].name;
  150. unsigned int queue_size = script_entity_[j].queue.size();
  151. if (queue_size > 0){
  152. text += ": ";
  153. DEBUG_DRAW.SetColour(Ogre::ColourValue(0.8f, 0.8f, 0.0f, 1.0f));
  154. }
  155. else DEBUG_DRAW.SetColour(Ogre::ColourValue(0.5, 0.5, 0.5, 1));
  156. for (unsigned int k = 0; k < queue_size; ++ k){
  157. if (k > 0) text += ", ";
  158. text +=
  159. "("
  160. + Ogre::StringConverter::toString(script_entity_[j].queue[k].priority)
  161. + ")" + script_entity_[j].queue[k].function;
  162. if (script_entity_[j].queue[k].wait == true){
  163. if (script_entity_[j].queue[k].seconds_to_wait != 0){
  164. text +=
  165. ":wait("+ Ogre::StringConverter::toString(
  166. script_entity_[j].queue[k].seconds_to_wait
  167. ) + ")";
  168. }
  169. }
  170. }
  171. DEBUG_DRAW.Text(20.0f, static_cast<float>(y), text);
  172. y += 16;
  173. }
  174. }
  175. }
  176. }
  177. }
  178. // Before updating entities, call on_update on the system timer.
  179. RunString("Timer.update()");
  180. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  181. if (script_entity_[i].type == type){
  182. // One script of an entity is run each cycle, the first in the queue. If it yields
  183. // without waiting for anything, as the ones that loop for ever, or until a flag
  184. // changes, do, it doesn't take the cycle of the rest: the next one is run too. In the
  185. // original game the scripts of an entity that have different priorities all run.
  186. for (size_t script_index = 0; script_index < script_entity_[i].queue.size(); ++ script_index){
  187. bool yielded = false;
  188. current_script_id_.entity = script_entity_[i].name;
  189. current_script_id_.function = script_entity_[i].queue[script_index].function;
  190. if (script_entity_[i].queue[script_index].wait == false){
  191. if (script_entity_[i].queue[script_index].yield == false){
  192. LOG_TRIVIAL(
  193. "[SCRIPT] Start script \"" + current_script_id_.function
  194. + "\" for entity \"" + current_script_id_.entity + "\"."
  195. );
  196. for (const ScriptId& waiting : script_entity_[i].queue[script_index].paused_scripts_start)
  197. ContinueScriptExecution(waiting);
  198. script_entity_[i].queue[script_index].paused_scripts_start.clear();
  199. sol::object table = GetTableByEntityName(
  200. type, current_script_id_.entity,
  201. script_entity_[i].queue[script_index].state
  202. );
  203. sol::object function;
  204. if (table.get_type() == sol::type::table)
  205. function = table.as<sol::table>()[current_script_id_.function];
  206. if (
  207. table.get_type() == sol::type::table
  208. && function.get_type() == sol::type::function
  209. ){
  210. int ret = 0;
  211. lua_State* thread = script_entity_[i].queue[script_index].state;
  212. sol::coroutine coroutine(thread, sol::function(function));
  213. auto result = coroutine(
  214. table, script_entity_[i].queue[script_index].argument1,
  215. script_entity_[i].queue[script_index].argument2,
  216. script_entity_[i].queue[script_index].argument3
  217. );
  218. if (result.valid()){
  219. // The coroutine yields with the bound function
  220. // return value on top of the thread stack; a
  221. // completed script leaves its return value there.
  222. if (lua_gettop(thread) > 0 && lua_isnumber(thread, -1))
  223. ret = static_cast<int>(lua_tointeger(thread, -1));
  224. lua_settop(thread, 0);
  225. }
  226. else{
  227. sol::error error = result;
  228. std::string msg = "LUA error in entity " + script_entity_[i].name
  229. + " (" + current_script_id_.entity + ") " + " in function "
  230. + script_entity_[i].queue[script_index].function + " ("
  231. + current_script_id_.function + ")";
  232. if (lua_tostring(thread, -1) != nullptr){
  233. msg = msg + ". Details: " + std::string(
  234. lua_tostring(thread, -1)
  235. );
  236. }
  237. msg = msg + ". Exception: " + error.what();
  238. LOG_ERROR(msg);
  239. lua_settop(thread, 0);
  240. }
  241. if (ret == 0){
  242. LOG_TRIVIAL(
  243. "[SCRIPT] Script \"" + current_script_id_.function
  244. + "\" for entity \"" + current_script_id_.entity + "\" finished."
  245. );
  246. if (script_entity_[i].queue[script_index].function != "on_update")
  247. RemoveEntityScript(script_entity_[i], script_index);
  248. }
  249. else if (ret == 1){
  250. LOG_TRIVIAL(
  251. "[SCRIPT] Script \"" + current_script_id_.function
  252. + "\" for entity \"" + current_script_id_.entity
  253. + "\" not paused and will be continued next cycle."
  254. );
  255. script_entity_[i].queue[script_index].yield = true;
  256. yielded = true;
  257. }
  258. else{
  259. LOG_TRIVIAL(
  260. "[SCRIPT] Script \"" + current_script_id_.function
  261. + "\" for entity \"" + current_script_id_.entity
  262. + "\" not finished yet."
  263. );
  264. script_entity_[i].queue[script_index].yield = true;
  265. script_entity_[i].queue[script_index].wait = true;
  266. }
  267. }
  268. else{
  269. LOG_WARNING(
  270. "Script \"" + current_script_id_.function + "\" for entity \""
  271. + current_script_id_.entity + "\" doesn't exist."
  272. );
  273. RemoveEntityScript(script_entity_[i], script_index);
  274. }
  275. }
  276. else{
  277. LOG_TRIVIAL(
  278. "[SCRIPT] Continue function \"" + current_script_id_.function
  279. + "\" for entity \"" + current_script_id_.entity + "\"."
  280. );
  281. int ret = 0;
  282. lua_State* thread = script_entity_[i].queue[script_index].state;
  283. // sol.hpp bundles a compat53 shim: on LuaJIT this maps
  284. // to the native 2-argument lua_resume.
  285. int status = lua_resume(thread, nullptr, 0);
  286. if (status == LUA_YIELD || status == 0){
  287. if (lua_gettop(thread) > 0 && lua_isnumber(thread, -1))
  288. ret = static_cast<int>(lua_tointeger(thread, -1));
  289. lua_settop(thread, 0);
  290. }
  291. else{
  292. const char* error = lua_tostring(thread, -1);
  293. LOG_WARNING(
  294. Ogre::String(error != nullptr ? error : "unknown lua error")
  295. );
  296. lua_settop(thread, 0);
  297. }
  298. if (ret == 0){ // Finished.
  299. LOG_TRIVIAL(
  300. "[SCRIPT] Script \"" + current_script_id_.function
  301. + "\" for entity \"" + current_script_id_.entity + "\" finished."
  302. );
  303. // Stop yield for on_update.
  304. script_entity_[i].queue[script_index].yield = false;
  305. if (script_entity_[i].queue[script_index].function != "on_update")
  306. RemoveEntityScript(script_entity_[i], script_index);
  307. }
  308. else if (ret == 1){
  309. LOG_TRIVIAL(
  310. "[SCRIPT] Script \"" + current_script_id_.function
  311. + "\" for entity \"" + current_script_id_.entity
  312. + "\" not paused and will be continued next cycle."
  313. );
  314. yielded = true;
  315. }
  316. else{
  317. LOG_TRIVIAL(
  318. "[SCRIPT] Script \"" + current_script_id_.function
  319. + "\" for entity \"" + current_script_id_.entity
  320. + "\" not finished yet."
  321. );
  322. script_entity_[i].queue[script_index].wait = true;
  323. }
  324. }
  325. }
  326. else if (script_entity_[i].queue[script_index].seconds_to_wait > 0){
  327. script_entity_[i].queue[script_index].seconds_to_wait
  328. -= Timer::getSingleton().GetGameTimeDelta();
  329. script_entity_[i].queue[script_index].seconds_to_wait
  330. = (script_entity_[i].queue[script_index].seconds_to_wait < 0)
  331. ? 0 : script_entity_[i].queue[script_index].seconds_to_wait;
  332. if (script_entity_[i].queue[script_index].seconds_to_wait == 0)
  333. script_entity_[i].queue[script_index].wait = false;
  334. }
  335. if (!yielded){
  336. // The scripts of an entity don't wait for each other in the original game. If
  337. // the first one is waiting (for another script to end, for example) and a
  338. // script that someone waits to start (request_start_sync) is queued behind
  339. // it, that script has to start, or the two would wait for each other forever
  340. // (the lines of mrkt3 do this with Aerith).
  341. bool start_waited_script = false;
  342. for (size_t next = script_index + 1; next < script_entity_[i].queue.size(); ++ next){
  343. const QueueScript& queued = script_entity_[i].queue[next];
  344. if (!queued.yield && !queued.wait && !queued.paused_scripts_start.empty()){
  345. script_index = next - 1;
  346. start_waited_script = true;
  347. break;
  348. }
  349. }
  350. if (!start_waited_script) break;
  351. }
  352. }
  353. }
  354. }
  355. }
  356. void ScriptManager::UpdateDebug(){}
  357. void ScriptManager::OnResize(){}
  358. void ScriptManager::ClearField(){}
  359. void ScriptManager::ClearBattle(){
  360. // Remove all battle script entities.
  361. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  362. if (script_entity_[i].type == BATTLE){
  363. while(script_entity_[i].queue.size() > 0)
  364. ScriptManager::RemoveEntityTopScript(script_entity_[i]);
  365. script_entity_.erase(script_entity_.begin() + i);
  366. i --;
  367. }
  368. }
  369. }
  370. void ScriptManager::ClearWorld(){}
  371. void ScriptManager::RunString(const Ogre::String& lua){
  372. int pre_eval_index = lua_gettop(lua_state_);
  373. if (luaL_dostring(lua_state_, lua.c_str()) == 1)
  374. LOG_ERROR("ScriptManager::RunString error: " + Ogre::String(lua_tostring(lua_state_, -1)));
  375. else{
  376. int index = lua_gettop(lua_state_);
  377. if (index > 0 && index != pre_eval_index){
  378. auto str = lua_tostring(lua_state_, index);
  379. LOG_CONSOLE(
  380. str != nullptr ? str : "ScriptManager::RunString: (nullptr; try tostring(...)?)"
  381. );
  382. lua_pop(lua_state_, 1);
  383. }
  384. }
  385. }
  386. float ScriptManager::EvaluateNumber(const Ogre::String& expression, const float default_value){
  387. const int pre_eval_index = lua_gettop(lua_state_);
  388. float result = default_value;
  389. if (luaL_dostring(lua_state_, ("return " + expression).c_str()) != 0){
  390. LOG_ERROR("ScriptManager::EvaluateNumber error: " + Ogre::String(lua_tostring(lua_state_, -1)));
  391. }
  392. else if (lua_gettop(lua_state_) > pre_eval_index && lua_isnumber(lua_state_, -1)){
  393. result = static_cast<float>(lua_tonumber(lua_state_, -1));
  394. }
  395. lua_settop(lua_state_, pre_eval_index);
  396. return result;
  397. }
  398. void ScriptManager::RunFile(const Ogre::String& file){
  399. if (luaL_dofile(lua_state_, ("./data/" + file).c_str()) == 1)
  400. LOG_ERROR(Ogre::String(lua_tostring(lua_state_, -1)));
  401. }
  402. void ScriptManager::AddEntity(
  403. const ScriptManager::Type type, const Ogre::String& entity_name, Entity* entity
  404. ){
  405. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  406. if (script_entity_[i].type == type && script_entity_[i].name == entity_name){
  407. LOG_ERROR(
  408. "Script \"" + script_entity_type[type] + "\" entity \""
  409. + entity_name + "\" already exist in script manager."
  410. );
  411. return;
  412. }
  413. }
  414. sol::object table = GetTableByEntityName(type, entity_name, lua_state_);
  415. if (table.get_type() == sol::type::table){
  416. ScriptEntity script_entity;
  417. script_entity.name = entity_name;
  418. script_entity.type = type;
  419. // Initialize entity field for model entity.
  420. if (entity != nullptr) table.as<sol::table>()["entity"] = entity;
  421. // Check the "on_start" script
  422. sol::object on_start = table.as<sol::table>()["on_start"];
  423. if (on_start.get_type() == sol::type::function){
  424. QueueScript script;
  425. script.function = "on_start";
  426. script.priority = 1;
  427. script.state = lua_newthread(lua_state_);
  428. // The thread must not be garbage collected,
  429. // so it need to be stored.
  430. script.state_id = luaL_ref(lua_state_, LUA_REGISTRYINDEX);
  431. script.seconds_to_wait = 0;
  432. script.wait = false;
  433. script.yield = false;
  434. script_entity.queue.push_back(script);
  435. }
  436. // Check the "on_update" script.
  437. sol::object on_update = table.as<sol::table>()["on_update"];
  438. if (on_update.get_type() == sol::type::function){
  439. QueueScript script;
  440. script.function = "on_update";
  441. script.priority = 999;
  442. script.state = lua_newthread(lua_state_);
  443. // The thread must not be garbage collected,
  444. // so it need to be stored.
  445. script.state_id = luaL_ref(lua_state_, LUA_REGISTRYINDEX);
  446. script.seconds_to_wait = 0;
  447. script.wait = false;
  448. script.yield = false;
  449. script_entity.queue.push_back(script);
  450. }
  451. script_entity_.push_back(script_entity);
  452. }
  453. }
  454. void ScriptManager::RemoveEntity(const ScriptManager::Type type, const Ogre::String& entity_name){
  455. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  456. if (script_entity_[i].type == type && script_entity_[i].name == entity_name){
  457. while(script_entity_[i].queue.size() > 0)
  458. ScriptManager::RemoveEntityTopScript(script_entity_[i]);
  459. script_entity_.erase(script_entity_.begin() + i);
  460. return;
  461. }
  462. }
  463. }
  464. void ScriptManager::RemoveEntityScript(ScriptEntity& entity, const size_t index){
  465. if (entity.queue.size() > index){
  466. // Delete the thread.
  467. luaL_unref(lua_state_, LUA_REGISTRYINDEX, entity.queue[index].state_id);
  468. for (const ScriptId& waiting : entity.queue[index].paused_scripts_end)
  469. ContinueScriptExecution(waiting);
  470. entity.queue[index].paused_scripts_end.clear();
  471. entity.queue.erase(entity.queue.begin() + index);
  472. }
  473. }
  474. void ScriptManager::RemoveEntityTopScript(ScriptEntity& entity){RemoveEntityScript(entity, 0);}
  475. sol::object ScriptManager::GetTableByEntityName(
  476. const ScriptManager::Type type, const Ogre::String& name, lua_State* state
  477. ) const{
  478. // Get the real table by name
  479. Ogre::StringVector table_path = StringTokenise(name, ".");
  480. sol::state_view lua(state);
  481. sol::object table = lua.globals();
  482. switch(type){
  483. case ScriptManager::SYSTEM:
  484. table = table.as<sol::table>()[system_table_name_]; break;
  485. case ScriptManager::ENTITY:
  486. table = table.as<sol::table>()[entity_table_name_]; break;
  487. case ScriptManager::UI:
  488. table = table.as<sol::table>()[ui_table_name_]; break;
  489. case ScriptManager::BATTLE:
  490. table = table.as<sol::table>()[battle_table_name_]; break;
  491. }
  492. if (table.get_type() != sol::type::table) return sol::make_object(state, sol::nil);
  493. for (unsigned int i = 0; i < table_path.size(); ++ i){
  494. table = table.as<sol::table>()[table_path[i]];
  495. if (table.get_type() != sol::type::table) return sol::make_object(state, sol::nil);
  496. }
  497. return table;
  498. }
  499. QueueScript* ScriptManager::GetScriptByScriptId(const ScriptId& script) const{
  500. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  501. if (script.entity == script_entity_[i].name){
  502. for (unsigned int j = 0; j < script_entity_[i].queue.size(); ++ j){
  503. if (script.function == script_entity_[i].queue[j].function)
  504. return (QueueScript*) &(script_entity_[i].queue[j]);
  505. }
  506. return nullptr;
  507. }
  508. }
  509. return nullptr;
  510. }
  511. ScriptEntity* ScriptManager::GetScriptEntityByName(
  512. const Type type, const Ogre::String& entity_name
  513. ) const{
  514. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  515. if (script_entity_[i].type == type && script_entity_[i].name == entity_name)
  516. return (ScriptEntity*) &(script_entity_[i]);
  517. }
  518. return nullptr;
  519. }
  520. const ScriptId ScriptManager::GetCurrentScriptId() const{return current_script_id_;}
  521. void ScriptManager::ContinueScriptExecution(const ScriptId& script){
  522. QueueScript* script_pointer = GetScriptByScriptId(script);
  523. if (script_pointer == nullptr){
  524. // The script that waited for this is already gone, for example because the field changed
  525. // or the script was cancelled, so there is nothing to continue.
  526. LOG_TRIVIAL(
  527. "There is no script \"" + script.function + "\" for entity \""
  528. + script.entity + "\" to continue. It has already ended."
  529. );
  530. return;
  531. }
  532. script_pointer->wait = false;
  533. }
  534. int ScriptManager::ScriptWait(const float seconds){
  535. LOG_TRIVIAL(
  536. "script:wait: We set script wait for "
  537. + Ogre::StringConverter::toString(seconds) + " seconds."
  538. );
  539. QueueScript* script = GetScriptByScriptId(current_script_id_);
  540. if (script == nullptr){
  541. LOG_ERROR("script:wait: Currently no any script running.");
  542. return 1;
  543. }
  544. if (seconds == 0) return 1;
  545. script->seconds_to_wait = seconds;
  546. return -1;
  547. }
  548. void ScriptManager::ScriptRequest(
  549. const Type type, const char* entity, const char* function, const int priority
  550. ){
  551. LOG_TRIVIAL(
  552. "[SCRIPT] script:request: Request function \"" + Ogre::String(function) + "\" for entity \""
  553. + Ogre::String(entity) + "\" with priority " + Ogre::StringConverter::toString(priority) + "."
  554. );
  555. ScriptEntity* script_entity = GetScriptEntityByName(type, Ogre::String(entity));
  556. if (script_entity == nullptr){
  557. LOG_WARNING(
  558. "[SCRIPT] script:request: Entity \"" + Ogre::String(entity) + "\" doesn't exist."
  559. );
  560. return;
  561. }
  562. bool added = ScriptRequest(script_entity, function, priority, "", "", false, false);
  563. if (added == false){
  564. LOG_WARNING(
  565. "Script '" + Ogre::String(function) + "' for entity '"
  566. + Ogre::String(entity) + "' doesn't exist."
  567. );
  568. }
  569. }
  570. int ScriptManager::ScriptRequestStartSync(
  571. const Type type, const char* entity, const char* function, const int priority
  572. ){
  573. LOG_TRIVIAL(
  574. "[SCRIPT] script:request_start_sync: Request function \""
  575. + Ogre::String(function) + "\" for entity \"" + Ogre::String(entity)
  576. + "\" with priority " + Ogre::StringConverter::toString(priority) + "."
  577. );
  578. ScriptEntity* script_entity = GetScriptEntityByName(type, Ogre::String(entity));
  579. if (script_entity == nullptr){
  580. LOG_ERROR(
  581. "[SCRIPT] script:request_start_sync: Entity \"" + Ogre::String(entity)
  582. + "\" doesn't exist.");
  583. return 1;
  584. }
  585. // A script that already started can't be waited for to start: nothing would resume the caller.
  586. for (const QueueScript& queued : script_entity->queue){
  587. if (queued.function == function && queued.yield){
  588. LOG_TRIVIAL(
  589. "[SCRIPT] script:request_start_sync: Function \"" + Ogre::String(function)
  590. + "\" for entity \"" + Ogre::String(entity) + "\" already started."
  591. );
  592. return 1;
  593. }
  594. }
  595. bool added = ScriptRequest(script_entity, function, priority, "", "", true, false);
  596. if (added == false){
  597. LOG_WARNING(
  598. "Script '" + Ogre::String(function) + "' for entity '"
  599. + Ogre::String(entity) + "' doesn't exist."
  600. );
  601. return 1;
  602. }
  603. return -1;
  604. }
  605. int ScriptManager::ScriptRequestEndSync(
  606. const Type type, const char* entity, const char* function, const int priority
  607. ){
  608. LOG_TRIVIAL(
  609. "[SCRIPT] script:request_end_sync: Request function \""
  610. + Ogre::String(function) + "\" for entity \"" + Ogre::String(entity)
  611. + "\" with priority " + Ogre::StringConverter::toString(priority) + "."
  612. );
  613. ScriptEntity* script_entity = GetScriptEntityByName(type, Ogre::String(entity));
  614. if (script_entity == nullptr){
  615. LOG_ERROR(
  616. "[SCRIPT] script:request_end_sync: Entity \"" + Ogre::String(entity)
  617. + "\" doesn't exist."
  618. );
  619. return 1;
  620. }
  621. bool added = ScriptRequest(script_entity, function, priority, "", "", false, true);
  622. if (added == false){
  623. LOG_WARNING(
  624. "Script '" + Ogre::String(function) + "' for entity '"
  625. + Ogre::String(entity) + "' doesn't exist."
  626. );
  627. return 1;
  628. }
  629. return -1;
  630. }
  631. bool ScriptManager::ScriptRequest(
  632. ScriptEntity* script_entity, const Ogre::String& function, const int priority,
  633. const Ogre::String& argument1, const Ogre::String& argument2, bool start_sync,
  634. bool end_sync, const Ogre::String& argument3, bool allow_duplicate
  635. ){
  636. if (script_entity == nullptr) return false;
  637. sol::object table
  638. = GetTableByEntityName(script_entity->type, script_entity->name, lua_state_);
  639. sol::object table_function;
  640. if (table.get_type() == sol::type::table)
  641. table_function = table.as<sol::table>()[function];
  642. if (table_function.get_type() == sol::type::function){
  643. QueueScript script;
  644. script.function = function;
  645. script.argument1 = argument1;
  646. script.argument2 = argument2;
  647. script.argument3 = argument3;
  648. script.priority = priority;
  649. script.state = lua_newthread(lua_state_);
  650. // The thread must not be garbage collected,
  651. // so it need to be stored.
  652. script.state_id = luaL_ref(lua_state_, LUA_REGISTRYINDEX);
  653. script.seconds_to_wait = 0;
  654. script.wait = false;
  655. script.yield = false;
  656. if (start_sync == true) script.paused_scripts_start.push_back(GetCurrentScriptId());
  657. if (end_sync == true) script.paused_scripts_end.push_back(GetCurrentScriptId());
  658. // If the script is already queued or running, don't queue it again. Whoever waits for the
  659. // request must wait for the existing script, because nothing else would resume it.
  660. if (allow_duplicate == false){
  661. for (int i = 0; i < script_entity->queue.size(); i ++){
  662. if (script_entity->queue[i].function == function){
  663. script_entity->resort = true;
  664. QueueScript& existing = script_entity->queue[i];
  665. for (const ScriptId& waiting : script.paused_scripts_end)
  666. existing.paused_scripts_end.push_back(waiting);
  667. // A script that already started isn't waited for. See ScriptRequestStartSync.
  668. if (!existing.yield){
  669. for (const ScriptId& waiting : script.paused_scripts_start)
  670. existing.paused_scripts_start.push_back(waiting);
  671. }
  672. luaL_unref(lua_state_, LUA_REGISTRYINDEX, script.state_id);
  673. return true;
  674. }
  675. }
  676. }
  677. // A script that is only polling (a loop that waits for a key or a flag, with no pause)
  678. // is replaced by the request of one with a higher priority, as the scenes do to stop the
  679. // loops of the keys (the mimic of the parade of junin1a).
  680. if (function != "on_update" && function != "on_start" && function != "on_button"){
  681. for (QueueScript& other : script_entity->queue){
  682. if (
  683. other.priority > priority && other.yield && !other.wait
  684. && other.function != "on_update" && other.function != "on_start"
  685. && other.function != "on_button"
  686. ) other.replaced = true;
  687. }
  688. }
  689. script_entity->queue.push_back(script);
  690. script_entity->resort = true;
  691. return true;
  692. }
  693. return false;
  694. }
  695. void ScriptManager::UpdateField(){}
  696. void ScriptManager::UpdateBattle(){}
  697. void ScriptManager::UpdateWorld(){}