ClientCommandManager.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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 "CPlayerInterface.h"
  14. #include "CServerHandler.h"
  15. #include "gui/CGuiHandler.h"
  16. #include "../lib/NetPacks.h"
  17. #include "../lib/CConfigHandler.h"
  18. #include "../lib/CGameState.h"
  19. #include "../lib/CPlayerState.h"
  20. #include "../lib/StringConstants.h"
  21. #include "gui/CAnimation.h"
  22. #include "windows/CAdvmapInterface.h"
  23. #include "windows/CCastleInterface.h"
  24. #include "../CCallback.h"
  25. #include "../lib/CGeneralTextHandler.h"
  26. #include "../lib/CHeroHandler.h"
  27. #include "../lib/CModHandler.h"
  28. #include "../lib/VCMIDirs.h"
  29. #ifdef SCRIPTING_ENABLED
  30. #include "../lib/ScriptHandler.h"
  31. #endif
  32. bool ClientCommandManager::currentCallFromIngameConsole;
  33. void ClientCommandManager::handleGoSolo()
  34. {
  35. Settings session = settings.write["session"];
  36. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  37. if(!CSH->client)
  38. {
  39. printCommandMessage("Game is not in playing state");
  40. return;
  41. }
  42. PlayerColor color;
  43. if(session["aiSolo"].Bool())
  44. {
  45. for(auto & elem : CSH->client->gameState()->players)
  46. {
  47. if(elem.second.human)
  48. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  49. }
  50. }
  51. else
  52. {
  53. color = LOCPLINT->playerID;
  54. removeGUI();
  55. for(auto & elem : CSH->client->gameState()->players)
  56. {
  57. if(elem.second.human)
  58. {
  59. auto AiToGive = CSH->client->aiNameForPlayer(*CSH->client->getPlayerSettings(elem.first), false);
  60. printCommandMessage("Player " + elem.first.getStr() + " will be lead by " + AiToGive, ELogLevel::INFO);
  61. CSH->client->installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), elem.first);
  62. }
  63. }
  64. GH.totalRedraw();
  65. giveTurn(color);
  66. }
  67. session["aiSolo"].Bool() = !session["aiSolo"].Bool();
  68. }
  69. void ClientCommandManager::handleControlAi(const std::string &colorName)
  70. {
  71. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  72. if(!CSH->client)
  73. {
  74. printCommandMessage("Game is not in playing state");
  75. return;
  76. }
  77. PlayerColor color;
  78. if(LOCPLINT)
  79. color = LOCPLINT->playerID;
  80. for(auto & elem : CSH->client->gameState()->players)
  81. {
  82. if(elem.second.human || (colorName.length() &&
  83. elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName)))
  84. {
  85. continue;
  86. }
  87. removeGUI();
  88. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  89. }
  90. GH.totalRedraw();
  91. if(color != PlayerColor::NEUTRAL)
  92. giveTurn(color);
  93. }
  94. void ClientCommandManager::processCommand(const std::string &message, bool calledFromIngameConsole)
  95. {
  96. std::istringstream readed;
  97. readed.str(message);
  98. std::string commandName;
  99. readed >> commandName;
  100. currentCallFromIngameConsole = calledFromIngameConsole;
  101. // Check mantis issue 2292 for details
  102. // if(LOCPLINT && LOCPLINT->cingconsole)
  103. // LOCPLINT->cingconsole->print(message);
  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. readed >> 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. readed >> 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. // readed >> fname;
  159. // CSH->client->loadGame(fname);
  160. // }
  161. else if(message=="convert txt")
  162. {
  163. //TODO: to be replaced with "VLC->generaltexth->dumpAllTexts();" due to https://github.com/vcmi/vcmi/pull/1329 merge:
  164. printCommandMessage("Command accepted.\t");
  165. const boost::filesystem::path outPath =
  166. VCMIDirs::get().userExtractedPath();
  167. boost::filesystem::create_directories(outPath);
  168. auto extractVector = [=](const std::vector<std::string> & source, const std::string & name)
  169. {
  170. JsonNode data(JsonNode::JsonType::DATA_VECTOR);
  171. int64_t index = 0;
  172. for(auto & line : source)
  173. {
  174. JsonNode lineNode(JsonNode::JsonType::DATA_STRUCT);
  175. lineNode["text"].String() = line;
  176. lineNode["index"].Integer() = index++;
  177. data.Vector().push_back(lineNode);
  178. }
  179. const boost::filesystem::path filePath = outPath / (name + ".json");
  180. boost::filesystem::ofstream file(filePath);
  181. file << data.toJson();
  182. };
  183. extractVector(VLC->generaltexth->allTexts, "generalTexts");
  184. extractVector(VLC->generaltexth->jktexts, "jkTexts");
  185. extractVector(VLC->generaltexth->arraytxt, "arrayTexts");
  186. printCommandMessage("\rExtracting done :)\n");
  187. printCommandMessage("Extracted files can be found in" + outPath.string() + " directory\n");
  188. }
  189. else if(message=="get config")
  190. {
  191. printCommandMessage("Command accepted.\t");
  192. const boost::filesystem::path outPath =
  193. VCMIDirs::get().userExtractedPath() / "configuration";
  194. boost::filesystem::create_directories(outPath);
  195. const std::vector<std::string> contentNames = {"heroClasses", "artifacts", "creatures", "factions", "objects", "heroes", "spells", "skills"};
  196. for(auto contentName : contentNames)
  197. {
  198. auto & content = (*VLC->modh->content)[contentName];
  199. auto contentOutPath = outPath / contentName;
  200. boost::filesystem::create_directories(contentOutPath);
  201. for(auto & iter : content.modData)
  202. {
  203. const JsonNode & modData = iter.second.modData;
  204. for(auto & nameAndObject : modData.Struct())
  205. {
  206. const JsonNode & object = nameAndObject.second;
  207. std::string name = CModHandler::normalizeIdentifier(object.meta, CModHandler::scopeBuiltin(), nameAndObject.first);
  208. boost::algorithm::replace_all(name,":","_");
  209. const boost::filesystem::path filePath = contentOutPath / (name + ".json");
  210. boost::filesystem::ofstream file(filePath);
  211. file << object.toJson();
  212. }
  213. }
  214. }
  215. printCommandMessage("\rExtracting done :)\n");
  216. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  217. }
  218. #if SCRIPTING_ENABLED
  219. else if(message=="get scripts")
  220. {
  221. printCommandMessage("Command accepted.\t");
  222. const boost::filesystem::path outPath =
  223. VCMIDirs::get().userExtractedPath() / "scripts";
  224. boost::filesystem::create_directories(outPath);
  225. for(auto & kv : VLC->scriptHandler->objects)
  226. {
  227. std::string name = kv.first;
  228. boost::algorithm::replace_all(name,":","_");
  229. const scripting::ScriptImpl * script = kv.second.get();
  230. boost::filesystem::path filePath = outPath / (name + ".lua");
  231. boost::filesystem::ofstream file(filePath);
  232. file << script->getSource();
  233. }
  234. printCommandMessage("\rExtracting done :)\n");
  235. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  236. }
  237. #endif
  238. else if(message=="get txt")
  239. {
  240. printCommandMessage("Command accepted.\t");
  241. const boost::filesystem::path outPath =
  242. VCMIDirs::get().userExtractedPath();
  243. auto list =
  244. CResourceHandler::get()->getFilteredFiles([](const ResourceID & ident)
  245. {
  246. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  247. });
  248. for (auto & filename : list)
  249. {
  250. const boost::filesystem::path filePath = outPath / (filename.getName() + ".TXT");
  251. boost::filesystem::create_directories(filePath.parent_path());
  252. boost::filesystem::ofstream file(filePath);
  253. auto text = CResourceHandler::get()->load(filename)->readAll();
  254. file.write((char*)text.first.get(), text.second);
  255. }
  256. printCommandMessage("\rExtracting done :)\n");
  257. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  258. }
  259. else if(commandName == "crash")
  260. {
  261. int *ptr = nullptr;
  262. *ptr = 666;
  263. //disaster!
  264. }
  265. else if(commandName == "mp" && adventureInt)
  266. {
  267. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  268. printCommandMessage(std::to_string(h->movement) + "; max: " + std::to_string(h->maxMovePoints(true)) + "/" + std::to_string(h->maxMovePoints(false)) + "\n");
  269. }
  270. else if(commandName == "bonuses")
  271. {
  272. bool jsonFormat = (message == "bonuses json");
  273. auto format = [jsonFormat](const BonusList & b) -> std::string
  274. {
  275. if(jsonFormat)
  276. return b.toJsonNode().toJson(true);
  277. std::ostringstream ss;
  278. ss << b;
  279. return ss.str();
  280. };
  281. printCommandMessage("Bonuses of " + adventureInt->selection->getObjectName() + "\n");
  282. printCommandMessage(format(adventureInt->selection->getBonusList()) + "\n");
  283. printCommandMessage("\nInherited bonuses:\n");
  284. TCNodes parents;
  285. adventureInt->selection->getParents(parents);
  286. for(const CBonusSystemNode *parent : parents)
  287. {
  288. printCommandMessage(std::string("\nBonuses from ") + typeid(*parent).name() + "\n" + format(*parent->getAllBonuses(Selector::all, Selector::all)) + "\n");
  289. }
  290. }
  291. else if(commandName == "not dialog")
  292. {
  293. LOCPLINT->showingDialog->setn(false);
  294. }
  295. else if(commandName == "gui")
  296. {
  297. for(auto & child : GH.listInt)
  298. {
  299. const auto childPtr = child.get();
  300. if(const CIntObject * obj = dynamic_cast<const CIntObject *>(childPtr))
  301. printInfoAboutInterfaceObject(obj, 0);
  302. else
  303. printCommandMessage(std::string(typeid(childPtr).name()) + "\n");
  304. }
  305. }
  306. else if(commandName == "tell")
  307. {
  308. std::string what;
  309. int id1, id2;
  310. readed >> what >> id1 >> id2;
  311. if(what == "hs")
  312. {
  313. for(const CGHeroInstance *h : LOCPLINT->cb->getHeroesInfo())
  314. if(h->type->ID.getNum() == id1)
  315. if(const CArtifactInstance *a = h->getArt(ArtifactPosition(id2)))
  316. printCommandMessage(a->nodeName());
  317. }
  318. }
  319. else if (commandName == "set")
  320. {
  321. std::string what, value;
  322. readed >> what;
  323. Settings config = settings.write["session"][what];
  324. readed >> value;
  325. if (value == "on")
  326. {
  327. config->Bool() = true;
  328. printCommandMessage("Option " + what + " enabled!", ELogLevel::INFO);
  329. }
  330. else if (value == "off")
  331. {
  332. config->Bool() = false;
  333. printCommandMessage("Option " + what + " disabled!", ELogLevel::INFO);
  334. }
  335. }
  336. else if(commandName == "unlock")
  337. {
  338. std::string mxname;
  339. readed >> mxname;
  340. if(mxname == "pim" && LOCPLINT)
  341. LOCPLINT->pim->unlock();
  342. }
  343. else if(commandName == "def2bmp")
  344. {
  345. std::string URI;
  346. readed >> URI;
  347. std::unique_ptr<CAnimation> anim = std::make_unique<CAnimation>(URI);
  348. anim->preload();
  349. anim->exportBitmaps(VCMIDirs::get().userExtractedPath());
  350. }
  351. else if(commandName == "extract")
  352. {
  353. std::string URI;
  354. readed >> URI;
  355. if (CResourceHandler::get()->existsResource(ResourceID(URI)))
  356. {
  357. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / URI;
  358. auto data = CResourceHandler::get()->load(ResourceID(URI))->readAll();
  359. boost::filesystem::create_directories(outPath.parent_path());
  360. boost::filesystem::ofstream outFile(outPath, boost::filesystem::ofstream::binary);
  361. outFile.write((char*)data.first.get(), data.second);
  362. }
  363. else
  364. printCommandMessage("File not found!", ELogLevel::ERROR);
  365. }
  366. else if(commandName == "setBattleAI")
  367. {
  368. std::string fname;
  369. readed >> fname;
  370. printCommandMessage("Will try loading that AI to see if it is correct name...\n");
  371. try
  372. {
  373. 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
  374. {
  375. Settings neutralAI = settings.write["server"]["neutralAI"];
  376. neutralAI->String() = fname;
  377. printCommandMessage("Setting changed, from now the battle ai will be " + fname + "!\n");
  378. }
  379. }
  380. catch(std::exception &e)
  381. {
  382. printCommandMessage("Failed opening " + fname + ": " + e.what(), ELogLevel::WARN);
  383. printCommandMessage("Setting not changed, AI not found or invalid!", ELogLevel::WARN);
  384. }
  385. }
  386. Settings session = settings.write["session"];
  387. if(commandName == "autoskip")
  388. {
  389. session["autoSkip"].Bool() = !session["autoSkip"].Bool();
  390. }
  391. else if(commandName == "gosolo")
  392. {
  393. ClientCommandManager::handleGoSolo();
  394. }
  395. else if(commandName == "controlai")
  396. {
  397. std::string colorName;
  398. readed >> colorName;
  399. boost::to_lower(colorName);
  400. ClientCommandManager::handleControlAi(colorName);
  401. }
  402. // Check mantis issue 2292 for details
  403. /* else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
  404. {
  405. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  406. LOCPLINT->cb->sendMessage(message);
  407. }*/
  408. }
  409. void ClientCommandManager::giveTurn(const PlayerColor &colorIdentifier)
  410. {
  411. YourTurn yt;
  412. yt.player = colorIdentifier;
  413. yt.daysWithoutCastle = CSH->client->getPlayerState(colorIdentifier)->daysWithoutCastle;
  414. yt.applyCl(CSH->client);
  415. }
  416. void ClientCommandManager::removeGUI()
  417. {
  418. // CClient::endGame
  419. GH.curInt = nullptr;
  420. if(GH.topInt())
  421. GH.topInt()->deactivate();
  422. GH.listInt.clear();
  423. GH.objsToBlit.clear();
  424. GH.statusbar = nullptr;
  425. printCommandMessage("Removed GUI.", ELogLevel::INFO);
  426. LOCPLINT = nullptr;
  427. }
  428. void ClientCommandManager::printInfoAboutInterfaceObject(const CIntObject *obj, int level)
  429. {
  430. std::stringstream sbuffer;
  431. sbuffer << std::string(level, '\t');
  432. sbuffer << typeid(*obj).name() << " *** ";
  433. if (obj->active)
  434. {
  435. #define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text
  436. PRINT(LCLICK, 'L');
  437. PRINT(RCLICK, 'R');
  438. PRINT(HOVER, 'H');
  439. PRINT(MOVE, 'M');
  440. PRINT(KEYBOARD, 'K');
  441. PRINT(TIME, 'T');
  442. PRINT(GENERAL, 'A');
  443. PRINT(WHEEL, 'W');
  444. PRINT(DOUBLECLICK, 'D');
  445. #undef PRINT
  446. }
  447. else
  448. sbuffer << "inactive";
  449. sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y;
  450. sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")";
  451. printCommandMessage(sbuffer.str(), ELogLevel::INFO);
  452. for(const CIntObject *child : obj->children)
  453. printInfoAboutInterfaceObject(child, level+1);
  454. }
  455. void ClientCommandManager::printCommandMessage(const std::string &commandMessage, ELogLevel::ELogLevel messageType)
  456. {
  457. switch(messageType)
  458. {
  459. case ELogLevel::NOT_SET:
  460. std::cout << commandMessage;
  461. break;
  462. case ELogLevel::TRACE:
  463. logGlobal->trace(commandMessage);
  464. break;
  465. case ELogLevel::DEBUG:
  466. logGlobal->debug(commandMessage);
  467. break;
  468. case ELogLevel::INFO:
  469. logGlobal->info(commandMessage);
  470. break;
  471. case ELogLevel::WARN:
  472. logGlobal->warn(commandMessage);
  473. break;
  474. case ELogLevel::ERROR:
  475. logGlobal->error(commandMessage);
  476. break;
  477. default:
  478. std::cout << commandMessage;
  479. break;
  480. }
  481. if(currentCallFromIngameConsole)
  482. {
  483. if(LOCPLINT && LOCPLINT->cingconsole)
  484. {
  485. LOCPLINT->cingconsole->print(commandMessage);
  486. }
  487. }
  488. }