PlayerMessageProcessor.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. /*
  2. * CGameHandler.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 "PlayerMessageProcessor.h"
  12. #include "TurnOrderProcessor.h"
  13. #include "../CGameHandler.h"
  14. #include "../CVCMIServer.h"
  15. #include "../TurnTimerHandler.h"
  16. #include "../../lib/CPlayerState.h"
  17. #include "../../lib/CSkillHandler.h"
  18. #include "../../lib/StartInfo.h"
  19. #include "../../lib/constants/Enumerations.h"
  20. #include "../../lib/entities/artifact/CArtHandler.h"
  21. #include "../../lib/entities/building/CBuilding.h"
  22. #include "../../lib/entities/hero/CHeroHandler.h"
  23. #include "../../lib/entities/ResourceTypeHandler.h"
  24. #include "../../lib/gameState/CGameState.h"
  25. #include "../../lib/mapObjects/CGTownInstance.h"
  26. #include "../../lib/mapObjects/CGHeroInstance.h"
  27. #include "../../lib/mapObjects/MiscObjects.h"
  28. #include "../../lib/modding/IdentifierStorage.h"
  29. #include "../../lib/modding/ModScope.h"
  30. #include "../../lib/mapping/CMap.h"
  31. #include "../../lib/networkPacks/PacksForClient.h"
  32. #include "../../lib/networkPacks/StackLocation.h"
  33. #include "../../lib/spells/CSpellHandler.h"
  34. #include "../../lib/json/JsonUtils.h"
  35. #include "../lib/VCMIDirs.h"
  36. PlayerMessageProcessor::PlayerMessageProcessor(CGameHandler * gameHandler)
  37. : gameHandler(gameHandler)
  38. , cheatConfig(JsonUtils::assembleFromFiles("config/cheats.json"))
  39. {
  40. }
  41. void PlayerMessageProcessor::playerMessage(PlayerColor player, const std::string & message, ObjectInstanceID currObj)
  42. {
  43. if(!message.empty() && message[0] == '!')
  44. {
  45. broadcastMessage(player, message);
  46. handleCommand(player, message);
  47. return;
  48. }
  49. if(handleCheatCode(message, player, currObj))
  50. {
  51. if(!gameHandler->gameInfo().getPlayerSettings(player)->isControlledByAI())
  52. {
  53. MetaString txt;
  54. txt.appendLocalString(EMetaText::GENERAL_TXT, 260);
  55. broadcastSystemMessage(txt);
  56. }
  57. if(!player.isSpectator())
  58. gameHandler->checkVictoryLossConditionsForPlayer(player); //Player enter win code or got required art\creature
  59. return;
  60. }
  61. broadcastMessage(player, message);
  62. }
  63. void PlayerMessageProcessor::commandExit(PlayerColor player, const std::vector<std::string> & words)
  64. {
  65. bool isHost = gameHandler->gameServer().isPlayerHost(player);
  66. if(!isHost)
  67. return;
  68. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.gameTerminated"));
  69. gameHandler->gameServer().setState(EServerState::SHUTDOWN);
  70. }
  71. void PlayerMessageProcessor::commandKick(PlayerColor player, const std::vector<std::string> & words)
  72. {
  73. bool isHost = gameHandler->gameServer().isPlayerHost(player);
  74. if(!isHost)
  75. return;
  76. if(words.size() == 2)
  77. {
  78. auto playername = words[1];
  79. PlayerColor playerToKick(PlayerColor::CANNOT_DETERMINE);
  80. if(std::all_of(playername.begin(), playername.end(), ::isdigit))
  81. playerToKick = PlayerColor(std::stoi(playername));
  82. else
  83. {
  84. for (PlayerColor color : PlayerColor::ALL_PLAYERS())
  85. {
  86. if(color.toString() == playername)
  87. playerToKick = color;
  88. }
  89. }
  90. if(playerToKick != PlayerColor::CANNOT_DETERMINE)
  91. {
  92. PlayerCheated pc;
  93. pc.player = playerToKick;
  94. pc.losingCheatCode = true;
  95. gameHandler->sendAndApply(pc);
  96. gameHandler->checkVictoryLossConditionsForPlayer(playerToKick);
  97. }
  98. }
  99. }
  100. void PlayerMessageProcessor::commandSave(PlayerColor player, const std::vector<std::string> & words)
  101. {
  102. bool isHost = gameHandler->gameServer().isPlayerHost(player);
  103. if(!isHost)
  104. return;
  105. if(words.size() == 2)
  106. {
  107. gameHandler->save("Saves/" + words[1]);
  108. MetaString str;
  109. str.appendTextID("vcmi.broadcast.gameSavedAs");
  110. str.appendRawString(" ");
  111. str.appendRawString(words[1]);
  112. broadcastSystemMessage(str);
  113. }
  114. }
  115. void PlayerMessageProcessor::commandCheaters(PlayerColor player, const std::vector<std::string> & words)
  116. {
  117. int playersCheated = 0;
  118. for(const auto & playerState : gameHandler->gameState().players)
  119. {
  120. if(playerState.second.cheated)
  121. {
  122. auto str = MetaString::createFromTextID("vcmi.broadcast.playerCheater");
  123. str.replaceName(playerState.first);
  124. broadcastSystemMessage(str);
  125. playersCheated++;
  126. }
  127. }
  128. if(!playersCheated)
  129. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.noCheater"));
  130. }
  131. void PlayerMessageProcessor::commandStatistic(PlayerColor player, const std::vector<std::string> & words)
  132. {
  133. bool isHost = gameHandler->gameServer().isPlayerHost(player);
  134. if(!isHost)
  135. return;
  136. std::string path = gameHandler->statistics->writeCsv();
  137. auto str = MetaString::createFromTextID("vcmi.broadcast.statisticFile");
  138. str.replaceRawString(path);
  139. broadcastSystemMessage(str);
  140. }
  141. void PlayerMessageProcessor::commandHelp(PlayerColor player, const std::vector<std::string> & words)
  142. {
  143. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.help.commands"));
  144. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.help.exit"));
  145. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.help.kick"));
  146. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.help.save"));
  147. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.help.statistic"));
  148. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.help.commandsAll"));
  149. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.help.help"));
  150. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.help.cheaters"));
  151. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.help.vote"));
  152. }
  153. void PlayerMessageProcessor::commandVote(PlayerColor player, const std::vector<std::string> & words)
  154. {
  155. if(words.size() < 2)
  156. {
  157. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.vote.allow"));
  158. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.vote.force"));
  159. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.vote.abort"));
  160. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.vote.timer"));
  161. return;
  162. }
  163. if(words[1] == "yes" || words[1] == "no" || words[1] == MetaString::createFromTextID("vcmi.broadcast.vote.yes").toString() || words[1] == MetaString::createFromTextID("vcmi.broadcast.vote.no").toString())
  164. {
  165. if(currentVote == ECurrentChatVote::NONE)
  166. {
  167. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.vote.noActive"));
  168. return;
  169. }
  170. if(words[1] == "yes" || words[1] == MetaString::createFromTextID("vcmi.broadcast.vote.yes").toString())
  171. {
  172. awaitingPlayers.erase(player);
  173. if(awaitingPlayers.empty())
  174. finishVoting();
  175. return;
  176. }
  177. if(words[1] == "no" || words[1] == MetaString::createFromTextID("vcmi.broadcast.vote.no").toString())
  178. {
  179. abortVoting();
  180. return;
  181. }
  182. }
  183. const auto & parseNumber = [](const std::string & input) -> std::optional<int>
  184. {
  185. try
  186. {
  187. return std::stol(input);
  188. }
  189. catch(std::logic_error &)
  190. {
  191. return std::nullopt;
  192. }
  193. };
  194. if(words[1] == "simturns" && words.size() > 2)
  195. {
  196. if(words[2] == "allow" && words.size() > 3)
  197. {
  198. auto daysCount = parseNumber(words[3]);
  199. if(daysCount && daysCount.value() > 0)
  200. startVoting(player, ECurrentChatVote::SIMTURNS_ALLOW, daysCount.value());
  201. return;
  202. }
  203. if(words[2] == "force" && words.size() > 3)
  204. {
  205. auto daysCount = parseNumber(words[3]);
  206. if(daysCount && daysCount.value() > 0)
  207. startVoting(player, ECurrentChatVote::SIMTURNS_FORCE, daysCount.value());
  208. return;
  209. }
  210. if(words[2] == "abort")
  211. {
  212. startVoting(player, ECurrentChatVote::SIMTURNS_ABORT, 0);
  213. return;
  214. }
  215. }
  216. if(words[1] == "timer" && words.size() > 2)
  217. {
  218. if(words[2] == "prolong" && words.size() > 3)
  219. {
  220. auto secondsCount = parseNumber(words[3]);
  221. if(secondsCount && secondsCount.value() > 0)
  222. startVoting(player, ECurrentChatVote::TIMER_PROLONG, secondsCount.value());
  223. return;
  224. }
  225. }
  226. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.vote.notRecognized"));
  227. }
  228. void PlayerMessageProcessor::finishVoting()
  229. {
  230. MetaString msg;
  231. switch(currentVote)
  232. {
  233. case ECurrentChatVote::SIMTURNS_ALLOW:
  234. msg.appendTextID("vcmi.broadcast.vote.success.untilContacts");
  235. msg.replaceRawString(std::to_string(currentVoteParameter));
  236. broadcastSystemMessage(msg);
  237. gameHandler->turnOrder->setMaxSimturnsDuration(currentVoteParameter);
  238. break;
  239. case ECurrentChatVote::SIMTURNS_FORCE:
  240. msg.appendTextID("vcmi.broadcast.vote.success.contactsBlocked");
  241. msg.replaceRawString(std::to_string(currentVoteParameter));
  242. broadcastSystemMessage(msg);
  243. gameHandler->turnOrder->setMinSimturnsDuration(currentVoteParameter);
  244. break;
  245. case ECurrentChatVote::SIMTURNS_ABORT:
  246. msg.appendTextID("vcmi.broadcast.vote.success.nextDay");
  247. broadcastSystemMessage(msg);
  248. gameHandler->turnOrder->setMinSimturnsDuration(0);
  249. gameHandler->turnOrder->setMaxSimturnsDuration(0);
  250. break;
  251. case ECurrentChatVote::TIMER_PROLONG:
  252. msg.appendTextID("vcmi.broadcast.vote.success.timer");
  253. msg.replaceRawString(std::to_string(currentVoteParameter));
  254. broadcastSystemMessage(msg);
  255. gameHandler->turnTimerHandler->prolongTimers(currentVoteParameter * 1000);
  256. break;
  257. }
  258. currentVote = ECurrentChatVote::NONE;
  259. currentVoteParameter = -1;
  260. }
  261. void PlayerMessageProcessor::abortVoting()
  262. {
  263. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.vote.aborted"));
  264. currentVote = ECurrentChatVote::NONE;
  265. }
  266. void PlayerMessageProcessor::startVoting(PlayerColor initiator, ECurrentChatVote what, int parameter)
  267. {
  268. currentVote = what;
  269. currentVoteParameter = parameter;
  270. MetaString msg;
  271. switch(currentVote)
  272. {
  273. case ECurrentChatVote::SIMTURNS_ALLOW:
  274. msg.appendTextID("vcmi.broadcast.vote.start.untilContacts");
  275. msg.replaceRawString(std::to_string(parameter));
  276. broadcastSystemMessage(msg);
  277. break;
  278. case ECurrentChatVote::SIMTURNS_FORCE:
  279. msg.appendTextID("vcmi.broadcast.vote.start.contactsBlocked");
  280. msg.replaceRawString(std::to_string(parameter));
  281. broadcastSystemMessage(msg);
  282. break;
  283. case ECurrentChatVote::SIMTURNS_ABORT:
  284. msg.appendTextID("vcmi.broadcast.vote.start.nextDay");
  285. broadcastSystemMessage(msg);
  286. break;
  287. case ECurrentChatVote::TIMER_PROLONG:
  288. msg.appendTextID("vcmi.broadcast.vote.start.timer");
  289. msg.replaceRawString(std::to_string(parameter));
  290. broadcastSystemMessage(msg);
  291. break;
  292. default:
  293. return;
  294. }
  295. broadcastSystemMessage(MetaString::createFromTextID("vcmi.broadcast.vote.hint"));
  296. awaitingPlayers.clear();
  297. for(PlayerColor player(0); player < PlayerColor::PLAYER_LIMIT; ++player)
  298. {
  299. auto state = gameHandler->gameInfo().getPlayerState(player, false);
  300. if(state && state->isHuman() && initiator != player)
  301. awaitingPlayers.insert(player);
  302. }
  303. if(awaitingPlayers.empty())
  304. finishVoting();
  305. }
  306. void PlayerMessageProcessor::handleCommand(PlayerColor player, const std::string & message)
  307. {
  308. if(message.empty() || message[0] != '!')
  309. return;
  310. std::vector<std::string> words;
  311. boost::split(words, message, boost::is_any_of(" "));
  312. if(words[0] == "!exit" || words[0] == "!quit")
  313. commandExit(player, words);
  314. if(words[0] == "!help")
  315. commandHelp(player, words);
  316. if(words[0] == "!vote")
  317. commandVote(player, words);
  318. if(words[0] == "!kick")
  319. commandKick(player, words);
  320. if(words[0] == "!save")
  321. commandSave(player, words);
  322. if(words[0] == "!cheaters")
  323. commandCheaters(player, words);
  324. if(words[0] == "!statistic")
  325. commandStatistic(player, words);
  326. }
  327. void PlayerMessageProcessor::cheatGiveSpells(PlayerColor player, const CGHeroInstance * hero)
  328. {
  329. if (!hero)
  330. return;
  331. ///Give hero spellbook
  332. if (!hero->hasSpellbook())
  333. gameHandler->giveHeroNewArtifact(hero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
  334. ///Give all spells with bonus (to allow banned spells)
  335. GiveBonus giveBonus(GiveBonus::ETarget::OBJECT);
  336. giveBonus.id = hero->id;
  337. giveBonus.bonus = Bonus(BonusDuration::PERMANENT, BonusType::SPELLS_OF_LEVEL, BonusSource::OTHER, 0, BonusSourceID());
  338. //start with level 0 to skip abilities
  339. for (int level = 1; level <= GameConstants::SPELL_LEVELS; level++)
  340. {
  341. giveBonus.bonus.subtype = BonusCustomSubtype::spellLevel(level);
  342. gameHandler->sendAndApply(giveBonus);
  343. }
  344. giveBonus.bonus = Bonus(BonusDuration::PERMANENT, BonusType::HERO_SPELL_CASTS_PER_COMBAT_TURN, BonusSource::OTHER, 99, BonusSourceID());
  345. gameHandler->sendAndApply(giveBonus);
  346. ///Give mana
  347. SetMana sm;
  348. sm.hid = hero->id;
  349. sm.val = 999;
  350. sm.mode = ChangeValueMode::ABSOLUTE;
  351. gameHandler->sendAndApply(sm);
  352. }
  353. void PlayerMessageProcessor::cheatBuildTown(PlayerColor player, const CGTownInstance * town)
  354. {
  355. if (!town)
  356. return;
  357. for (auto & build : town->getTown()->buildings)
  358. {
  359. if (!town->hasBuilt(build.first)
  360. && !build.second->getNameTranslated().empty()
  361. && build.first != BuildingID::SHIP)
  362. {
  363. gameHandler->buildStructure(town->id, build.first, true);
  364. }
  365. }
  366. }
  367. void PlayerMessageProcessor::cheatGiveArmy(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  368. {
  369. if (!hero)
  370. return;
  371. std::string creatureIdentifier = words.empty() ? "archangel" : words[0];
  372. std::optional<int> amountPerSlot;
  373. try
  374. {
  375. amountPerSlot = std::stol(words.at(1));
  376. }
  377. catch(std::logic_error&)
  378. {
  379. }
  380. std::optional<int32_t> creatureId = LIBRARY->identifiers()->getIdentifierCaseInsensitive(ModScope::scopeGame(), "creature", creatureIdentifier, false);
  381. if(creatureId.has_value())
  382. {
  383. const auto * creature = CreatureID(creatureId.value()).toCreature();
  384. for (int i = 0; i < GameConstants::ARMY_SIZE; i++)
  385. {
  386. if (!hero->hasStackAtSlot(SlotID(i)))
  387. {
  388. if (amountPerSlot.has_value())
  389. gameHandler->insertNewStack(StackLocation(hero->id, SlotID(i)), creature, *amountPerSlot);
  390. else
  391. gameHandler->insertNewStack(StackLocation(hero->id, SlotID(i)), creature, 5 * std::pow(10, i));
  392. }
  393. }
  394. }
  395. }
  396. void PlayerMessageProcessor::cheatGiveMachines(PlayerColor player, const CGHeroInstance * hero)
  397. {
  398. if (!hero)
  399. return;
  400. if (!hero->getArt(ArtifactPosition::MACH1))
  401. gameHandler->giveHeroNewArtifact(hero, ArtifactID::BALLISTA, ArtifactPosition::MACH1);
  402. if (!hero->getArt(ArtifactPosition::MACH2))
  403. gameHandler->giveHeroNewArtifact(hero, ArtifactID::AMMO_CART, ArtifactPosition::MACH2);
  404. if (!hero->getArt(ArtifactPosition::MACH3))
  405. gameHandler->giveHeroNewArtifact(hero, ArtifactID::FIRST_AID_TENT, ArtifactPosition::MACH3);
  406. }
  407. void PlayerMessageProcessor::cheatGiveArtifacts(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  408. {
  409. if (!hero)
  410. return;
  411. if (!words.empty())
  412. {
  413. for (auto const & word : words)
  414. {
  415. auto artID = LIBRARY->identifiers()->getIdentifierCaseInsensitive(ModScope::scopeGame(), "artifact", word, false);
  416. if(artID && LIBRARY->arth->objects[*artID])
  417. gameHandler->giveHeroNewArtifact(hero, ArtifactID(*artID), ArtifactPosition::FIRST_AVAILABLE);
  418. }
  419. }
  420. else
  421. {
  422. for(int g = 7; g < LIBRARY->arth->objects.size(); ++g) //including artifacts from mods
  423. {
  424. if(LIBRARY->arth->objects[g]->canBePutAt(hero))
  425. gameHandler->giveHeroNewArtifact(hero, ArtifactID(g), ArtifactPosition::FIRST_AVAILABLE);
  426. }
  427. }
  428. }
  429. void PlayerMessageProcessor::cheatGiveScrolls(PlayerColor player, const CGHeroInstance * hero)
  430. {
  431. if(!hero)
  432. return;
  433. for(const auto & spell : LIBRARY->spellh->objects)
  434. if(gameHandler->gameState().isAllowed(spell->getId()) && !spell->isSpecial())
  435. {
  436. gameHandler->giveHeroNewScroll(hero, spell->getId(), ArtifactPosition::FIRST_AVAILABLE);
  437. }
  438. }
  439. void PlayerMessageProcessor::cheatColorSchemeChange(PlayerColor player, ColorScheme scheme)
  440. {
  441. PlayerCheated pc;
  442. pc.player = player;
  443. pc.colorScheme = scheme;
  444. pc.localOnlyCheat = true;
  445. gameHandler->sendAndApply(pc);
  446. }
  447. void PlayerMessageProcessor::cheatLevelup(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  448. {
  449. if (!hero)
  450. return;
  451. int levelsToGain;
  452. try
  453. {
  454. levelsToGain = std::stol(words.at(0));
  455. }
  456. catch(std::logic_error&)
  457. {
  458. levelsToGain = 1;
  459. }
  460. gameHandler->giveExperience(hero, LIBRARY->heroh->reqExp(hero->level + levelsToGain) - LIBRARY->heroh->reqExp(hero->level));
  461. }
  462. void PlayerMessageProcessor::cheatExperience(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  463. {
  464. if (!hero)
  465. return;
  466. int expAmountProcessed;
  467. try
  468. {
  469. expAmountProcessed = std::stol(words.at(0));
  470. }
  471. catch(std::logic_error&)
  472. {
  473. expAmountProcessed = 10000;
  474. }
  475. gameHandler->giveExperience(hero, expAmountProcessed);
  476. }
  477. void PlayerMessageProcessor::cheatMovement(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  478. {
  479. if (!hero)
  480. return;
  481. SetMovePoints smp;
  482. smp.hid = hero->id;
  483. bool unlimited = false;
  484. try
  485. {
  486. smp.val = std::stol(words.at(0));
  487. }
  488. catch(std::logic_error&)
  489. {
  490. smp.val = 1000000;
  491. unlimited = true;
  492. }
  493. gameHandler->sendAndApply(smp);
  494. GiveBonus gb(GiveBonus::ETarget::OBJECT);
  495. gb.bonus.type = BonusType::FREE_SHIP_BOARDING;
  496. gb.bonus.duration = unlimited ? BonusDuration::PERMANENT : BonusDuration::ONE_DAY;
  497. gb.bonus.source = BonusSource::OTHER;
  498. gb.id = hero->id;
  499. gameHandler->giveHeroBonus(&gb);
  500. if(unlimited)
  501. {
  502. GiveBonus gb(GiveBonus::ETarget::OBJECT);
  503. gb.bonus.type = BonusType::UNLIMITED_MOVEMENT;
  504. gb.bonus.duration = BonusDuration::PERMANENT;
  505. gb.bonus.source = BonusSource::OTHER;
  506. gb.id = hero->id;
  507. gameHandler->giveHeroBonus(&gb);
  508. }
  509. }
  510. void PlayerMessageProcessor::cheatResources(PlayerColor player, std::vector<std::string> words)
  511. {
  512. int baseResourceAmount;
  513. try
  514. {
  515. baseResourceAmount = std::stol(words.at(0));
  516. }
  517. catch(std::logic_error&)
  518. {
  519. baseResourceAmount = 100;
  520. }
  521. TResources resources;
  522. for (auto & i : LIBRARY->resourceTypeHandler->getAllObjects())
  523. resources[i] = baseResourceAmount;
  524. resources[EGameResID::GOLD] = baseResourceAmount * 1000;
  525. gameHandler->giveResources(player, resources);
  526. }
  527. void PlayerMessageProcessor::cheatVictory(PlayerColor player)
  528. {
  529. PlayerCheated pc;
  530. pc.player = player;
  531. pc.winningCheatCode = true;
  532. gameHandler->sendAndApply(pc);
  533. }
  534. void PlayerMessageProcessor::cheatDefeat(PlayerColor player)
  535. {
  536. PlayerCheated pc;
  537. pc.player = player;
  538. pc.losingCheatCode = true;
  539. gameHandler->sendAndApply(pc);
  540. }
  541. void PlayerMessageProcessor::cheatMapReveal(PlayerColor player, bool reveal)
  542. {
  543. FoWChange fc;
  544. fc.mode = reveal ? ETileVisibility::REVEALED : ETileVisibility::HIDDEN;
  545. fc.player = player;
  546. const auto & fowMap = gameHandler->gameState().getPlayerTeam(player)->fogOfWarMap;
  547. const auto & mapSize = gameHandler->gameState().getMapSize();
  548. auto hlp_tab = new int3[mapSize.x * mapSize.y * mapSize.z];
  549. int lastUnc = 0;
  550. for(int z = 0; z < mapSize.z; z++)
  551. for(int x = 0; x < mapSize.x; x++)
  552. for(int y = 0; y < mapSize.y; y++)
  553. if(!fowMap[z][x][y] || fc.mode == ETileVisibility::HIDDEN)
  554. hlp_tab[lastUnc++] = int3(x, y, z);
  555. fc.tiles.insert(hlp_tab, hlp_tab + lastUnc);
  556. delete [] hlp_tab;
  557. if (!fc.tiles.empty())
  558. gameHandler->sendAndApply(fc);
  559. }
  560. void PlayerMessageProcessor::cheatPuzzleReveal(PlayerColor player)
  561. {
  562. const TeamState * t = gameHandler->gameState().getPlayerTeam(player);
  563. for(auto & obj : gameHandler->gameState().getMap().getObjects<CGObelisk>())
  564. {
  565. if(!obj->wasVisited(player))
  566. {
  567. gameHandler->setObjPropertyID(obj->id, ObjProperty::OBELISK_VISITED, t->id);
  568. for(const auto & color : t->players)
  569. {
  570. gameHandler->setObjPropertyID(obj->id, ObjProperty::VISITED, color);
  571. PlayerCheated pc;
  572. pc.player = color;
  573. gameHandler->sendAndApply(pc);
  574. }
  575. }
  576. }
  577. }
  578. void PlayerMessageProcessor::cheatMaxLuck(PlayerColor player, const CGHeroInstance * hero)
  579. {
  580. if (!hero)
  581. return;
  582. GiveBonus gb;
  583. gb.bonus = Bonus(BonusDuration::PERMANENT, BonusType::MAX_LUCK, BonusSource::OTHER, 0, BonusSourceID(Obj(Obj::NO_OBJ)));
  584. gb.id = hero->id;
  585. gameHandler->giveHeroBonus(&gb);
  586. }
  587. void PlayerMessageProcessor::cheatFly(PlayerColor player, const CGHeroInstance * hero)
  588. {
  589. if (!hero)
  590. return;
  591. GiveBonus gb;
  592. gb.bonus = Bonus(BonusDuration::PERMANENT, BonusType::FLYING_MOVEMENT, BonusSource::OTHER, 0, BonusSourceID(Obj(Obj::NO_OBJ)));
  593. gb.id = hero->id;
  594. gameHandler->giveHeroBonus(&gb);
  595. }
  596. void PlayerMessageProcessor::cheatMaxMorale(PlayerColor player, const CGHeroInstance * hero)
  597. {
  598. if (!hero)
  599. return;
  600. GiveBonus gb;
  601. gb.bonus = Bonus(BonusDuration::PERMANENT, BonusType::MAX_MORALE, BonusSource::OTHER, 0, BonusSourceID(Obj(Obj::NO_OBJ)));
  602. gb.id = hero->id;
  603. gameHandler->giveHeroBonus(&gb);
  604. }
  605. void PlayerMessageProcessor::cheatSkill(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  606. {
  607. if (!hero)
  608. return;
  609. std::string identifier;
  610. try
  611. {
  612. identifier = words.at(0);
  613. }
  614. catch(std::logic_error&)
  615. {
  616. return;
  617. }
  618. MasteryLevel::Type mastery;
  619. try
  620. {
  621. mastery = static_cast<MasteryLevel::Type>(std::stoi(words.at(1)));
  622. }
  623. catch(std::logic_error&)
  624. {
  625. mastery = MasteryLevel::Type::EXPERT;
  626. }
  627. if(identifier == "every")
  628. {
  629. for(const auto & skill : LIBRARY->skillh->objects)
  630. gameHandler->changeSecSkill(hero, SecondarySkill(skill->getId()), mastery, ChangeValueMode::ABSOLUTE);
  631. return;
  632. }
  633. std::optional<int32_t> skillId = LIBRARY->identifiers()->getIdentifierCaseInsensitive(ModScope::scopeGame(), "skill", identifier, false);
  634. if(!skillId.has_value())
  635. return;
  636. auto skill = SecondarySkill(skillId.value());
  637. gameHandler->changeSecSkill(hero, skill, mastery, ChangeValueMode::ABSOLUTE);
  638. }
  639. void PlayerMessageProcessor::cheatTeleport(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  640. {
  641. if (!hero)
  642. return;
  643. int3 pos;
  644. try
  645. {
  646. pos.x = std::stoi(words.at(0));
  647. pos.y = std::stoi(words.at(1));
  648. pos.z = words.size() > 2 ? std::stoi(words.at(2)) : hero->pos.z;
  649. }
  650. catch(std::logic_error&)
  651. {
  652. return;
  653. }
  654. if(!gameHandler->gameState().getMap().isInTheMap(pos))
  655. return;
  656. auto destTile = gameHandler->gameState().getMap().getTile(pos);
  657. auto heroTile = gameHandler->gameState().getMap().getTile(hero->pos);
  658. if(!destTile.isClear(&heroTile))
  659. return;
  660. gameHandler->moveHero(hero->id, pos, EMovementMode::DIMENSION_DOOR);
  661. }
  662. bool PlayerMessageProcessor::handleCheatCode(const std::string & cheat, PlayerColor player, ObjectInstanceID currObj)
  663. {
  664. std::vector<std::string> words;
  665. boost::split(words, boost::trim_copy(cheat), boost::is_any_of("\t\r\n "));
  666. if (words.empty() || !gameHandler->gameInfo().getStartInfo()->extraOptionsInfo.cheatsAllowed)
  667. return false;
  668. //Make cheat name case-insensitive, but keep words/parameters (e.g. creature name) as it
  669. std::string cheatName = boost::to_lower_copy(words[0]);
  670. words.erase(words.begin());
  671. auto getCheats = [this](const std::string& category)
  672. {
  673. std::vector<std::string> tmpCheats;
  674. for (auto& item : cheatConfig[category].Struct())
  675. {
  676. const auto& vec = item.second.Vector();
  677. std::transform(vec.begin(), vec.end(), std::back_inserter(tmpCheats), [](const auto& v){ return boost::to_lower_copy(v.String()); });
  678. }
  679. return tmpCheats;
  680. };
  681. auto localCheats = getCheats("localCheats");
  682. auto townTargetedCheats = getCheats("townTargetedCheats");
  683. auto playerTargetedCheats = getCheats("playerTargetedCheats");
  684. auto heroTargetedCheats = getCheats("heroTargetedCheats");
  685. if(vstd::contains(localCheats, cheatName))
  686. {
  687. executeCheatCode(cheatName, player, currObj, words);
  688. return true;
  689. }
  690. if (!vstd::contains(townTargetedCheats, cheatName) && !vstd::contains(playerTargetedCheats, cheatName) && !vstd::contains(heroTargetedCheats, cheatName))
  691. return false;
  692. bool playerTargetedCheat = false;
  693. for (const auto & i : gameHandler->gameState().players)
  694. {
  695. if (words.empty())
  696. break;
  697. if (i.first == PlayerColor::NEUTRAL)
  698. continue;
  699. if (words.front() == "ai" && i.second.human)
  700. continue;
  701. if (words.front() != "all" && words.front() != i.first.toString())
  702. continue;
  703. std::vector<std::string> parameters = words;
  704. PlayerCheated pc;
  705. pc.player = i.first;
  706. gameHandler->sendAndApply(pc);
  707. playerTargetedCheat = true;
  708. parameters.erase(parameters.begin());
  709. if (vstd::contains(playerTargetedCheats, cheatName))
  710. executeCheatCode(cheatName, i.first, ObjectInstanceID::NONE, parameters);
  711. if (vstd::contains(townTargetedCheats, cheatName))
  712. for (const auto & t : i.second.getTowns())
  713. executeCheatCode(cheatName, i.first, t->id, parameters);
  714. if (vstd::contains(heroTargetedCheats, cheatName))
  715. for (const auto & h : i.second.getHeroes())
  716. executeCheatCode(cheatName, i.first, h->id, parameters);
  717. }
  718. PlayerCheated pc;
  719. pc.player = player;
  720. gameHandler->sendAndApply(pc);
  721. if (!playerTargetedCheat)
  722. executeCheatCode(cheatName, player, currObj, words);
  723. return true;
  724. }
  725. void PlayerMessageProcessor::executeCheatCode(const std::string & cheatName, PlayerColor player, ObjectInstanceID currObj, const std::vector<std::string> & words)
  726. {
  727. const CGHeroInstance * hero = gameHandler->gameInfo().getHero(currObj);
  728. const CGTownInstance * town = gameHandler->gameInfo().getTown(currObj);
  729. if (!town && hero)
  730. town = hero->getVisitedTown();
  731. const auto & doCheatGiveSpells = [&]() { cheatGiveSpells(player, hero); };
  732. const auto & doCheatBuildTown = [&]() { cheatBuildTown(player, town); };
  733. const auto & doCheatGiveArmyCustom = [&]() { cheatGiveArmy(player, hero, words); };
  734. const auto & doCheatGiveArmyFixed = [&](std::vector<std::string> customWords) { cheatGiveArmy(player, hero, customWords); };
  735. const auto & doCheatGiveMachines = [&]() { cheatGiveMachines(player, hero); };
  736. const auto & doCheatGiveArtifacts = [&]() { cheatGiveArtifacts(player, hero, words); };
  737. const auto & doCheatLevelup = [&]() { cheatLevelup(player, hero, words); };
  738. const auto & doCheatExperience = [&]() { cheatExperience(player, hero, words); };
  739. const auto & doCheatMovement = [&]() { cheatMovement(player, hero, words); };
  740. const auto & doCheatResources = [&]() { cheatResources(player, words); };
  741. const auto & doCheatVictory = [&]() { cheatVictory(player); };
  742. const auto & doCheatDefeat = [&]() { cheatDefeat(player); };
  743. const auto & doCheatMapReveal = [&]() { cheatMapReveal(player, true); };
  744. const auto & doCheatMapHide = [&]() { cheatMapReveal(player, false); };
  745. const auto & doCheatRevealPuzzle = [&]() { cheatPuzzleReveal(player); };
  746. const auto & doCheatMaxLuck = [&]() { cheatMaxLuck(player, hero); };
  747. const auto & doCheatMaxMorale = [&]() { cheatMaxMorale(player, hero); };
  748. const auto & doCheatGiveScrolls = [&]() { cheatGiveScrolls(player, hero); };
  749. const auto & doCheatTheOne = [&]()
  750. {
  751. if(!hero)
  752. return;
  753. cheatMapReveal(player, true);
  754. cheatGiveArmy(player, hero, { "archangel", "5" });
  755. cheatMovement(player, hero, { });
  756. cheatFly(player, hero);
  757. };
  758. const auto & doCheatColorSchemeChange = [&](ColorScheme filter) { cheatColorSchemeChange(player, filter); };
  759. const auto & doCheatSkill = [&]() { cheatSkill(player, hero, words); };
  760. const auto & doCheatTeleport = [&]() { cheatTeleport(player, hero, words); };
  761. auto getCheatKey = [this](const std::string& cheat) {
  762. for (const auto& [category, structNode] : cheatConfig.Struct())
  763. {
  764. for (const auto& [key, node] : structNode.Struct())
  765. {
  766. for (const auto& v : node.Vector())
  767. {
  768. if (boost::to_lower_copy(v.String()) == cheat)
  769. return key;
  770. }
  771. }
  772. }
  773. return std::string("");
  774. };
  775. auto key = getCheatKey(cheatName);
  776. std::map<std::string, std::function<void()>> callbacks = {
  777. {"giveArchangel", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  778. {"giveBlackKnight", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  779. {"giveCrystalDragon", [&] () {doCheatGiveArmyFixed({ "crystalDragon", "5000" });} },
  780. {"giveAzureDragon", [&] () {doCheatGiveArmyFixed({ "azureDragon", "5000" });} },
  781. {"giveFairieDragon", [&] () {doCheatGiveArmyFixed({ "fairieDragon", "5000" });} },
  782. {"giveArmy", doCheatGiveArmyCustom },
  783. {"giveSpells", doCheatGiveSpells },
  784. {"buildTown", doCheatBuildTown },
  785. {"giveMachines", doCheatGiveMachines },
  786. {"giveArtifacts", doCheatGiveArtifacts },
  787. {"levelup", doCheatLevelup },
  788. {"experience", doCheatExperience },
  789. {"movement", doCheatMovement },
  790. {"resources", doCheatResources },
  791. {"defeat", doCheatDefeat },
  792. {"victory", doCheatVictory },
  793. {"mapReveal", doCheatMapReveal },
  794. {"mapHide", doCheatMapHide },
  795. {"revealPuzzle", doCheatRevealPuzzle },
  796. {"maxLuck", doCheatMaxLuck },
  797. {"maxMorale", doCheatMaxMorale },
  798. {"god", doCheatTheOne },
  799. {"giveScrolls", doCheatGiveScrolls },
  800. {"color", [&] () {doCheatColorSchemeChange(ColorScheme::H2_SCHEME);} },
  801. {"gray", [&] () {doCheatColorSchemeChange(ColorScheme::GRAYSCALE);} },
  802. {"skill", doCheatSkill },
  803. {"teleport", doCheatTeleport },
  804. };
  805. assert(callbacks.count(key));
  806. if (callbacks.count(key))
  807. callbacks.at(key)();
  808. }
  809. void PlayerMessageProcessor::sendSystemMessage(GameConnectionID connectionID, const MetaString & message)
  810. {
  811. SystemMessage sm;
  812. sm.text = message;
  813. gameHandler->gameServer().sendPack(sm, connectionID);
  814. }
  815. void PlayerMessageProcessor::sendSystemMessage(GameConnectionID connectionID, const std::string & message)
  816. {
  817. MetaString str;
  818. str.appendRawString(message);
  819. sendSystemMessage(connectionID, str);
  820. }
  821. void PlayerMessageProcessor::broadcastSystemMessage(MetaString message)
  822. {
  823. SystemMessage sm;
  824. sm.text = message;
  825. gameHandler->gameServer().applyPack(sm);
  826. }
  827. void PlayerMessageProcessor::broadcastSystemMessage(const std::string & message)
  828. {
  829. MetaString str;
  830. str.appendRawString(message);
  831. broadcastSystemMessage(str);
  832. }
  833. void PlayerMessageProcessor::broadcastMessage(PlayerColor playerSender, const std::string & message)
  834. {
  835. PlayerMessageClient temp_message(playerSender, message);
  836. gameHandler->sendAndApply(temp_message);
  837. }