2
0

ClientCommandManager.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /*
  2. * ClientCommandManager.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "ClientCommandManager.h"
  12. #include "Client.h"
  13. #include "adventureMap/CInGameConsole.h"
  14. #include "adventureMap/CAdvMapInt.h"
  15. #include "CPlayerInterface.h"
  16. #include "CServerHandler.h"
  17. #include "gui/CGuiHandler.h"
  18. #include "../lib/NetPacks.h"
  19. #include "ClientNetPackVisitors.h"
  20. #include "../lib/CConfigHandler.h"
  21. #include "../lib/CGameState.h"
  22. #include "../lib/CPlayerState.h"
  23. #include "../lib/StringConstants.h"
  24. #include "windows/CCastleInterface.h"
  25. #include "render/CAnimation.h"
  26. #include "../CCallback.h"
  27. #include "../lib/CGeneralTextHandler.h"
  28. #include "../lib/CHeroHandler.h"
  29. #include "../lib/CModHandler.h"
  30. #include "../lib/VCMIDirs.h"
  31. #include "CMT.h"
  32. #ifdef SCRIPTING_ENABLED
  33. #include "../lib/ScriptHandler.h"
  34. #endif
  35. #include <SDL_surface.h>
  36. void ClientCommandManager::handleGoSolo()
  37. {
  38. Settings session = settings.write["session"];
  39. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  40. if(!CSH->client)
  41. {
  42. printCommandMessage("Game is not in playing state");
  43. return;
  44. }
  45. PlayerColor color;
  46. if(session["aiSolo"].Bool())
  47. {
  48. for(auto & elem : CSH->client->gameState()->players)
  49. {
  50. if(elem.second.human)
  51. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  52. }
  53. }
  54. else
  55. {
  56. color = LOCPLINT->playerID;
  57. CSH->client->removeGUI();
  58. for(auto & elem : CSH->client->gameState()->players)
  59. {
  60. if(elem.second.human)
  61. {
  62. auto AiToGive = CSH->client->aiNameForPlayer(*CSH->client->getPlayerSettings(elem.first), false);
  63. printCommandMessage("Player " + elem.first.getStr() + " will be lead by " + AiToGive, ELogLevel::INFO);
  64. CSH->client->installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), elem.first);
  65. }
  66. }
  67. GH.totalRedraw();
  68. giveTurn(color);
  69. }
  70. session["aiSolo"].Bool() = !session["aiSolo"].Bool();
  71. }
  72. void ClientCommandManager::handleControlAi(const std::string &colorName)
  73. {
  74. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  75. if(!CSH->client)
  76. {
  77. printCommandMessage("Game is not in playing state");
  78. return;
  79. }
  80. PlayerColor color;
  81. if(LOCPLINT)
  82. color = LOCPLINT->playerID;
  83. for(auto & elem : CSH->client->gameState()->players)
  84. {
  85. if(elem.second.human || (colorName.length() &&
  86. elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName)))
  87. {
  88. continue;
  89. }
  90. CSH->client->removeGUI();
  91. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  92. }
  93. GH.totalRedraw();
  94. if(color != PlayerColor::NEUTRAL)
  95. giveTurn(color);
  96. }
  97. void ClientCommandManager::processCommand(const std::string &message, bool calledFromIngameConsole)
  98. {
  99. std::istringstream singleWordBuffer;
  100. singleWordBuffer.str(message);
  101. std::string commandName;
  102. singleWordBuffer >> commandName;
  103. currentCallFromIngameConsole = calledFromIngameConsole;
  104. if(message==std::string("die, fool"))
  105. {
  106. exit(EXIT_SUCCESS);
  107. }
  108. else if(commandName == std::string("activate"))
  109. {
  110. int what;
  111. singleWordBuffer >> what;
  112. switch (what)
  113. {
  114. case 0:
  115. GH.topInt()->activate();
  116. break;
  117. case 1:
  118. adventureInt->activate();
  119. break;
  120. case 2:
  121. LOCPLINT->castleInt->activate();
  122. break;
  123. default:
  124. printCommandMessage("Wrong argument specified!", ELogLevel::ERROR);
  125. }
  126. }
  127. else if(commandName == "redraw")
  128. {
  129. GH.totalRedraw();
  130. }
  131. else if(commandName == "screen")
  132. {
  133. printCommandMessage("Screenbuf points to ");
  134. if(screenBuf == screen)
  135. printCommandMessage("screen", ELogLevel::ERROR);
  136. else if(screenBuf == screen2)
  137. printCommandMessage("screen2", ELogLevel::ERROR);
  138. else
  139. printCommandMessage("?!?", ELogLevel::ERROR);
  140. SDL_SaveBMP(screen, "Screen_c.bmp");
  141. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  142. }
  143. else if(commandName == "save")
  144. {
  145. if(!CSH->client)
  146. {
  147. printCommandMessage("Game is not in playing state");
  148. return;
  149. }
  150. std::string fname;
  151. singleWordBuffer >> fname;
  152. CSH->client->save(fname);
  153. }
  154. // else if(commandName=="load")
  155. // {
  156. // // TODO: this code should end the running game and manage to call startGame instead
  157. // std::string fname;
  158. // singleWordBuffer >> fname;
  159. // CSH->client->loadGame(fname);
  160. // }
  161. else if(message=="convert txt")
  162. {
  163. VLC->generaltexth->dumpAllTexts();
  164. }
  165. else if(message=="get config")
  166. {
  167. printCommandMessage("Command accepted.\t");
  168. const boost::filesystem::path outPath =
  169. VCMIDirs::get().userExtractedPath() / "configuration";
  170. boost::filesystem::create_directories(outPath);
  171. const std::vector<std::string> contentNames = {"heroClasses", "artifacts", "creatures", "factions", "objects", "heroes", "spells", "skills"};
  172. for(auto contentName : contentNames)
  173. {
  174. auto & content = (*VLC->modh->content)[contentName];
  175. auto contentOutPath = outPath / contentName;
  176. boost::filesystem::create_directories(contentOutPath);
  177. for(auto & iter : content.modData)
  178. {
  179. const JsonNode & modData = iter.second.modData;
  180. for(auto & nameAndObject : modData.Struct())
  181. {
  182. const JsonNode & object = nameAndObject.second;
  183. std::string name = CModHandler::makeFullIdentifier(object.meta, contentName, nameAndObject.first);
  184. boost::algorithm::replace_all(name,":","_");
  185. const boost::filesystem::path filePath = contentOutPath / (name + ".json");
  186. boost::filesystem::ofstream file(filePath);
  187. file << object.toJson();
  188. }
  189. }
  190. }
  191. printCommandMessage("\rExtracting done :)\n");
  192. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  193. }
  194. #if SCRIPTING_ENABLED
  195. else if(message=="get scripts")
  196. {
  197. printCommandMessage("Command accepted.\t");
  198. const boost::filesystem::path outPath =
  199. VCMIDirs::get().userExtractedPath() / "scripts";
  200. boost::filesystem::create_directories(outPath);
  201. for(auto & kv : VLC->scriptHandler->objects)
  202. {
  203. std::string name = kv.first;
  204. boost::algorithm::replace_all(name,":","_");
  205. const scripting::ScriptImpl * script = kv.second.get();
  206. boost::filesystem::path filePath = outPath / (name + ".lua");
  207. boost::filesystem::ofstream file(filePath);
  208. file << script->getSource();
  209. }
  210. printCommandMessage("\rExtracting done :)\n");
  211. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  212. }
  213. #endif
  214. else if(message=="get txt")
  215. {
  216. printCommandMessage("Command accepted.\t");
  217. const boost::filesystem::path outPath =
  218. VCMIDirs::get().userExtractedPath();
  219. auto list =
  220. CResourceHandler::get()->getFilteredFiles([](const ResourceID & ident)
  221. {
  222. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  223. });
  224. for (auto & filename : list)
  225. {
  226. const boost::filesystem::path filePath = outPath / (filename.getName() + ".TXT");
  227. boost::filesystem::create_directories(filePath.parent_path());
  228. boost::filesystem::ofstream file(filePath);
  229. auto text = CResourceHandler::get()->load(filename)->readAll();
  230. file.write((char*)text.first.get(), text.second);
  231. }
  232. printCommandMessage("\rExtracting done :)\n");
  233. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  234. }
  235. else if(commandName == "crash")
  236. {
  237. int *ptr = nullptr;
  238. *ptr = 666;
  239. //disaster!
  240. }
  241. else if(commandName == "mp" && adventureInt)
  242. {
  243. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  244. printCommandMessage(std::to_string(h->movement) + "; max: " + std::to_string(h->maxMovePoints(true)) + "/" + std::to_string(h->maxMovePoints(false)) + "\n");
  245. }
  246. else if(commandName == "bonuses")
  247. {
  248. bool jsonFormat = (message == "bonuses json");
  249. auto format = [jsonFormat](const BonusList & b) -> std::string
  250. {
  251. if(jsonFormat)
  252. return b.toJsonNode().toJson(true);
  253. std::ostringstream ss;
  254. ss << b;
  255. return ss.str();
  256. };
  257. printCommandMessage("Bonuses of " + adventureInt->selection->getObjectName() + "\n");
  258. printCommandMessage(format(adventureInt->selection->getBonusList()) + "\n");
  259. printCommandMessage("\nInherited bonuses:\n");
  260. TCNodes parents;
  261. adventureInt->selection->getParents(parents);
  262. for(const CBonusSystemNode *parent : parents)
  263. {
  264. printCommandMessage(std::string("\nBonuses from ") + typeid(*parent).name() + "\n" + format(*parent->getAllBonuses(Selector::all, Selector::all)) + "\n");
  265. }
  266. }
  267. else if(commandName == "not dialog")
  268. {
  269. LOCPLINT->showingDialog->setn(false);
  270. }
  271. else if(commandName == "gui")
  272. {
  273. for(auto & child : GH.listInt)
  274. {
  275. const auto childPtr = child.get();
  276. if(const CIntObject * obj = dynamic_cast<const CIntObject *>(childPtr))
  277. printInfoAboutInterfaceObject(obj, 0);
  278. else
  279. printCommandMessage(std::string(typeid(childPtr).name()) + "\n");
  280. }
  281. }
  282. else if(commandName == "tell")
  283. {
  284. std::string what;
  285. int id1, id2;
  286. singleWordBuffer >> what >> id1 >> id2;
  287. if(what == "hs")
  288. {
  289. for(const CGHeroInstance *h : LOCPLINT->cb->getHeroesInfo())
  290. if(h->type->getIndex() == id1)
  291. if(const CArtifactInstance *a = h->getArt(ArtifactPosition(id2)))
  292. printCommandMessage(a->nodeName());
  293. }
  294. }
  295. else if (commandName == "set")
  296. {
  297. std::string what, value;
  298. singleWordBuffer >> what;
  299. Settings config = settings.write["session"][what];
  300. singleWordBuffer >> value;
  301. if (value == "on")
  302. {
  303. config->Bool() = true;
  304. printCommandMessage("Option " + what + " enabled!", ELogLevel::INFO);
  305. }
  306. else if (value == "off")
  307. {
  308. config->Bool() = false;
  309. printCommandMessage("Option " + what + " disabled!", ELogLevel::INFO);
  310. }
  311. }
  312. else if(commandName == "unlock")
  313. {
  314. std::string mxname;
  315. singleWordBuffer >> mxname;
  316. if(mxname == "pim" && LOCPLINT)
  317. LOCPLINT->pim->unlock();
  318. }
  319. else if(commandName == "def2bmp")
  320. {
  321. std::string URI;
  322. singleWordBuffer >> URI;
  323. std::unique_ptr<CAnimation> anim = std::make_unique<CAnimation>(URI);
  324. anim->preload();
  325. anim->exportBitmaps(VCMIDirs::get().userExtractedPath());
  326. }
  327. else if(commandName == "extract")
  328. {
  329. std::string URI;
  330. singleWordBuffer >> URI;
  331. if (CResourceHandler::get()->existsResource(ResourceID(URI)))
  332. {
  333. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / URI;
  334. auto data = CResourceHandler::get()->load(ResourceID(URI))->readAll();
  335. boost::filesystem::create_directories(outPath.parent_path());
  336. boost::filesystem::ofstream outFile(outPath, boost::filesystem::ofstream::binary);
  337. outFile.write((char*)data.first.get(), data.second);
  338. }
  339. else
  340. printCommandMessage("File not found!", ELogLevel::ERROR);
  341. }
  342. else if(commandName == "setBattleAI")
  343. {
  344. std::string fname;
  345. singleWordBuffer >> fname;
  346. printCommandMessage("Will try loading that AI to see if it is correct name...\n");
  347. try
  348. {
  349. if(auto ai = CDynLibHandler::getNewBattleAI(fname)) //test that given AI is indeed available... heavy but it is easy to make a typo and break the game
  350. {
  351. Settings neutralAI = settings.write["server"]["neutralAI"];
  352. neutralAI->String() = fname;
  353. printCommandMessage("Setting changed, from now the battle ai will be " + fname + "!\n");
  354. }
  355. }
  356. catch(std::exception &e)
  357. {
  358. printCommandMessage("Failed opening " + fname + ": " + e.what(), ELogLevel::WARN);
  359. printCommandMessage("Setting not changed, AI not found or invalid!", ELogLevel::WARN);
  360. }
  361. }
  362. else if(commandName == "autoskip")
  363. {
  364. Settings session = settings.write["session"];
  365. session["autoSkip"].Bool() = !session["autoSkip"].Bool();
  366. }
  367. else if(commandName == "gosolo")
  368. {
  369. ClientCommandManager::handleGoSolo();
  370. }
  371. else if(commandName == "controlai")
  372. {
  373. std::string colorName;
  374. singleWordBuffer >> colorName;
  375. boost::to_lower(colorName);
  376. ClientCommandManager::handleControlAi(colorName);
  377. }
  378. else
  379. {
  380. printCommandMessage("Command not found :(", ELogLevel::ERROR);
  381. }
  382. }
  383. void ClientCommandManager::giveTurn(const PlayerColor &colorIdentifier)
  384. {
  385. YourTurn yt;
  386. yt.player = colorIdentifier;
  387. yt.daysWithoutCastle = CSH->client->getPlayerState(colorIdentifier)->daysWithoutCastle;
  388. ApplyClientNetPackVisitor visitor(*CSH->client, *CSH->client->gameState());
  389. yt.visit(visitor);
  390. }
  391. void ClientCommandManager::printInfoAboutInterfaceObject(const CIntObject *obj, int level)
  392. {
  393. std::stringstream sbuffer;
  394. sbuffer << std::string(level, '\t');
  395. sbuffer << typeid(*obj).name() << " *** ";
  396. if (obj->active)
  397. {
  398. #define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text
  399. PRINT(LCLICK, 'L');
  400. PRINT(RCLICK, 'R');
  401. PRINT(HOVER, 'H');
  402. PRINT(MOVE, 'M');
  403. PRINT(KEYBOARD, 'K');
  404. PRINT(TIME, 'T');
  405. PRINT(GENERAL, 'A');
  406. PRINT(WHEEL, 'W');
  407. PRINT(DOUBLECLICK, 'D');
  408. #undef PRINT
  409. }
  410. else
  411. sbuffer << "inactive";
  412. sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y;
  413. sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")";
  414. printCommandMessage(sbuffer.str(), ELogLevel::INFO);
  415. for(const CIntObject *child : obj->children)
  416. printInfoAboutInterfaceObject(child, level+1);
  417. }
  418. void ClientCommandManager::printCommandMessage(const std::string &commandMessage, ELogLevel::ELogLevel messageType)
  419. {
  420. switch(messageType)
  421. {
  422. case ELogLevel::NOT_SET:
  423. std::cout << commandMessage;
  424. break;
  425. case ELogLevel::TRACE:
  426. logGlobal->trace(commandMessage);
  427. break;
  428. case ELogLevel::DEBUG:
  429. logGlobal->debug(commandMessage);
  430. break;
  431. case ELogLevel::INFO:
  432. logGlobal->info(commandMessage);
  433. break;
  434. case ELogLevel::WARN:
  435. logGlobal->warn(commandMessage);
  436. break;
  437. case ELogLevel::ERROR:
  438. logGlobal->error(commandMessage);
  439. break;
  440. default:
  441. std::cout << commandMessage;
  442. break;
  443. }
  444. if(currentCallFromIngameConsole)
  445. {
  446. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  447. if(LOCPLINT && LOCPLINT->cingconsole)
  448. {
  449. LOCPLINT->cingconsole->print(commandMessage);
  450. }
  451. }
  452. }