CCallback.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. /*
  2. * CCallback.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 "CCallback.h"
  12. #include "lib/CCreatureHandler.h"
  13. #include "lib/gameState/CGameState.h"
  14. #include "client/CPlayerInterface.h"
  15. #include "client/Client.h"
  16. #include "lib/mapping/CMap.h"
  17. #include "lib/mapObjects/CGHeroInstance.h"
  18. #include "lib/mapObjects/CGTownInstance.h"
  19. #include "lib/texts/CGeneralTextHandler.h"
  20. #include "lib/CArtHandler.h"
  21. #include "lib/GameConstants.h"
  22. #include "lib/CPlayerState.h"
  23. #include "lib/UnlockGuard.h"
  24. #include "lib/battle/BattleInfo.h"
  25. #include "lib/networkPacks/PacksForServer.h"
  26. #include "lib/networkPacks/SaveLocalState.h"
  27. bool CCallback::teleportHero(const CGHeroInstance *who, const CGTownInstance *where)
  28. {
  29. CastleTeleportHero pack(who->id, where->id, 1);
  30. sendRequest(pack);
  31. return true;
  32. }
  33. void CCallback::moveHero(const CGHeroInstance *h, const int3 & destination, bool transit)
  34. {
  35. MoveHero pack({destination}, h->id, transit);
  36. sendRequest(pack);
  37. }
  38. void CCallback::moveHero(const CGHeroInstance *h, const std::vector<int3> & path, bool transit)
  39. {
  40. MoveHero pack(path, h->id, transit);
  41. sendRequest(pack);
  42. }
  43. int CCallback::selectionMade(int selection, QueryID queryID)
  44. {
  45. return sendQueryReply(selection, queryID);
  46. }
  47. int CCallback::sendQueryReply(std::optional<int32_t> reply, QueryID queryID)
  48. {
  49. ASSERT_IF_CALLED_WITH_PLAYER
  50. if(queryID == QueryID(-1))
  51. {
  52. logGlobal->error("Cannot answer the query -1!");
  53. return -1;
  54. }
  55. QueryReply pack(queryID, reply);
  56. pack.player = *player;
  57. return sendRequest(pack);
  58. }
  59. void CCallback::recruitCreatures(const CGDwelling * obj, const CArmedInstance * dst, CreatureID ID, ui32 amount, si32 level)
  60. {
  61. // TODO exception for neutral dwellings shouldn't be hardcoded
  62. if(player != obj->tempOwner && obj->ID != Obj::WAR_MACHINE_FACTORY && obj->ID != Obj::REFUGEE_CAMP)
  63. return;
  64. RecruitCreatures pack(obj->id, dst->id, ID, amount, level);
  65. sendRequest(pack);
  66. }
  67. bool CCallback::dismissCreature(const CArmedInstance *obj, SlotID stackPos)
  68. {
  69. if((player && obj->tempOwner != player) || (obj->stacksCount()<2 && obj->needsLastStack()))
  70. return false;
  71. DisbandCreature pack(stackPos,obj->id);
  72. sendRequest(pack);
  73. return true;
  74. }
  75. bool CCallback::upgradeCreature(const CArmedInstance *obj, SlotID stackPos, CreatureID newID)
  76. {
  77. UpgradeCreature pack(stackPos,obj->id,newID);
  78. sendRequest(pack);
  79. return false;
  80. }
  81. void CCallback::endTurn()
  82. {
  83. logGlobal->trace("Player %d ended his turn.", player->getNum());
  84. EndTurn pack;
  85. sendRequest(pack);
  86. }
  87. int CCallback::swapCreatures(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  88. {
  89. ArrangeStacks pack(1,p1,p2,s1->id,s2->id,0);
  90. sendRequest(pack);
  91. return 0;
  92. }
  93. int CCallback::mergeStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  94. {
  95. ArrangeStacks pack(2,p1,p2,s1->id,s2->id,0);
  96. sendRequest(pack);
  97. return 0;
  98. }
  99. int CCallback::splitStack(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2, int val)
  100. {
  101. ArrangeStacks pack(3,p1,p2,s1->id,s2->id,val);
  102. sendRequest(pack);
  103. return 0;
  104. }
  105. int CCallback::bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot)
  106. {
  107. BulkMoveArmy pack(srcArmy, destArmy, srcSlot);
  108. sendRequest(pack);
  109. return 0;
  110. }
  111. int CCallback::bulkSplitStack(ObjectInstanceID armyId, SlotID srcSlot, int howMany)
  112. {
  113. BulkSplitStack pack(armyId, srcSlot, howMany);
  114. sendRequest(pack);
  115. return 0;
  116. }
  117. int CCallback::bulkSmartSplitStack(ObjectInstanceID armyId, SlotID srcSlot)
  118. {
  119. BulkSmartSplitStack pack(armyId, srcSlot);
  120. sendRequest(pack);
  121. return 0;
  122. }
  123. int CCallback::bulkMergeStacks(ObjectInstanceID armyId, SlotID srcSlot)
  124. {
  125. BulkMergeStacks pack(armyId, srcSlot);
  126. sendRequest(pack);
  127. return 0;
  128. }
  129. bool CCallback::dismissHero(const CGHeroInstance *hero)
  130. {
  131. if(player!=hero->tempOwner) return false;
  132. DismissHero pack(hero->id);
  133. sendRequest(pack);
  134. return true;
  135. }
  136. bool CCallback::swapArtifacts(const ArtifactLocation &l1, const ArtifactLocation &l2)
  137. {
  138. ExchangeArtifacts ea;
  139. ea.src = l1;
  140. ea.dst = l2;
  141. sendRequest(ea);
  142. return true;
  143. }
  144. /**
  145. * Assembles or disassembles a combination artifact.
  146. * @param hero Hero holding the artifact(s).
  147. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  148. * @param assemble True for assembly operation, false for disassembly.
  149. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  150. * artifact to assemble to. Otherwise it's not used.
  151. */
  152. void CCallback::assembleArtifacts(const ObjectInstanceID & heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  153. {
  154. AssembleArtifacts aa(heroID, artifactSlot, assemble, assembleTo);
  155. sendRequest(aa);
  156. }
  157. void CCallback::bulkMoveArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap, bool equipped, bool backpack)
  158. {
  159. BulkExchangeArtifacts bma(srcHero, dstHero, swap, equipped, backpack);
  160. sendRequest(bma);
  161. }
  162. void CCallback::scrollBackpackArtifacts(ObjectInstanceID hero, bool left)
  163. {
  164. ManageBackpackArtifacts mba(hero, ManageBackpackArtifacts::ManageCmd::SCROLL_RIGHT);
  165. if(left)
  166. mba.cmd = ManageBackpackArtifacts::ManageCmd::SCROLL_LEFT;
  167. sendRequest(mba);
  168. }
  169. void CCallback::sortBackpackArtifactsBySlot(const ObjectInstanceID hero)
  170. {
  171. ManageBackpackArtifacts mba(hero, ManageBackpackArtifacts::ManageCmd::SORT_BY_SLOT);
  172. sendRequest(mba);
  173. }
  174. void CCallback::sortBackpackArtifactsByCost(const ObjectInstanceID hero)
  175. {
  176. ManageBackpackArtifacts mba(hero, ManageBackpackArtifacts::ManageCmd::SORT_BY_COST);
  177. sendRequest(mba);
  178. }
  179. void CCallback::sortBackpackArtifactsByClass(const ObjectInstanceID hero)
  180. {
  181. ManageBackpackArtifacts mba(hero, ManageBackpackArtifacts::ManageCmd::SORT_BY_CLASS);
  182. sendRequest(mba);
  183. }
  184. void CCallback::manageHeroCostume(ObjectInstanceID hero, size_t costumeIndex, bool saveCostume)
  185. {
  186. ManageEquippedArtifacts mea(hero, costumeIndex, saveCostume);
  187. sendRequest(mea);
  188. }
  189. void CCallback::eraseArtifactByClient(const ArtifactLocation & al)
  190. {
  191. EraseArtifactByClient ea(al);
  192. sendRequest(ea);
  193. }
  194. bool CCallback::buildBuilding(const CGTownInstance *town, BuildingID buildingID)
  195. {
  196. if(town->tempOwner!=player)
  197. return false;
  198. if(canBuildStructure(town, buildingID) != EBuildingState::ALLOWED)
  199. return false;
  200. BuildStructure pack(town->id,buildingID);
  201. sendRequest(pack);
  202. return true;
  203. }
  204. bool CCallback::visitTownBuilding(const CGTownInstance *town, BuildingID buildingID)
  205. {
  206. if(town->tempOwner!=player)
  207. return false;
  208. VisitTownBuilding pack(town->id, buildingID);
  209. sendRequest(pack);
  210. return true;
  211. }
  212. void CBattleCallback::battleMakeSpellAction(const BattleID & battleID, const BattleAction & action)
  213. {
  214. assert(action.actionType == EActionType::HERO_SPELL);
  215. MakeAction mca(action);
  216. mca.battleID = battleID;
  217. sendRequest(mca);
  218. }
  219. int CBattleCallback::sendRequest(const CPackForServer & request)
  220. {
  221. int requestID = cl->sendRequest(request, *getPlayerID());
  222. if(waitTillRealize)
  223. {
  224. logGlobal->trace("We'll wait till request %d is answered.\n", requestID);
  225. auto gsUnlocker = vstd::makeUnlockSharedGuardIf(CGameState::mutex, unlockGsWhenWaiting);
  226. CClient::waitingRequest.waitWhileContains(requestID);
  227. }
  228. boost::this_thread::interruption_point();
  229. return requestID;
  230. }
  231. void CCallback::spellResearch( const CGTownInstance *town, SpellID spellAtSlot, bool accepted )
  232. {
  233. SpellResearch pack(town->id, spellAtSlot, accepted);
  234. sendRequest(pack);
  235. }
  236. void CCallback::swapGarrisonHero( const CGTownInstance *town )
  237. {
  238. if(town->tempOwner == *player || (town->garrisonHero && town->garrisonHero->tempOwner == *player ))
  239. {
  240. GarrisonHeroSwap pack(town->id);
  241. sendRequest(pack);
  242. }
  243. }
  244. void CCallback::buyArtifact(const CGHeroInstance *hero, ArtifactID aid)
  245. {
  246. if(hero->tempOwner != *player) return;
  247. BuyArtifact pack(hero->id,aid);
  248. sendRequest(pack);
  249. }
  250. void CCallback::trade(const ObjectInstanceID marketId, EMarketMode mode, TradeItemSell id1, TradeItemBuy id2, ui32 val1, const CGHeroInstance * hero)
  251. {
  252. trade(marketId, mode, std::vector(1, id1), std::vector(1, id2), std::vector(1, val1), hero);
  253. }
  254. void CCallback::trade(const ObjectInstanceID marketId, EMarketMode mode, const std::vector<TradeItemSell> & id1, const std::vector<TradeItemBuy> & id2, const std::vector<ui32> & val1, const CGHeroInstance * hero)
  255. {
  256. TradeOnMarketplace pack;
  257. pack.marketId = marketId;
  258. pack.heroId = hero ? hero->id : ObjectInstanceID();
  259. pack.mode = mode;
  260. pack.r1 = id1;
  261. pack.r2 = id2;
  262. pack.val = val1;
  263. sendRequest(pack);
  264. }
  265. void CCallback::setFormation(const CGHeroInstance * hero, EArmyFormation mode)
  266. {
  267. SetFormation pack(hero->id, mode);
  268. sendRequest(pack);
  269. }
  270. void CCallback::recruitHero(const CGObjectInstance *townOrTavern, const CGHeroInstance *hero, const HeroTypeID & nextHero)
  271. {
  272. assert(townOrTavern);
  273. assert(hero);
  274. HireHero pack(hero->getHeroTypeID(), townOrTavern->id, nextHero);
  275. pack.player = *player;
  276. sendRequest(pack);
  277. }
  278. void CCallback::saveLocalState(const JsonNode & data)
  279. {
  280. SaveLocalState state;
  281. state.data = data;
  282. state.player = *player;
  283. sendRequest(state);
  284. }
  285. void CCallback::save( const std::string &fname )
  286. {
  287. cl->save(fname);
  288. }
  289. void CCallback::gamePause(bool pause)
  290. {
  291. if(pause)
  292. {
  293. GamePause pack;
  294. pack.player = *player;
  295. sendRequest(pack);
  296. }
  297. else
  298. {
  299. sendQueryReply(0, QueryID::CLIENT);
  300. }
  301. }
  302. void CCallback::sendMessage(const std::string &mess, const CGObjectInstance * currentObject)
  303. {
  304. ASSERT_IF_CALLED_WITH_PLAYER
  305. PlayerMessage pm(mess, currentObject? currentObject->id : ObjectInstanceID(-1));
  306. if(player)
  307. pm.player = *player;
  308. sendRequest(pm);
  309. }
  310. void CCallback::buildBoat( const IShipyard *obj )
  311. {
  312. BuildBoat bb;
  313. bb.objid = dynamic_cast<const CGObjectInstance*>(obj)->id;
  314. sendRequest(bb);
  315. }
  316. CCallback::CCallback(CGameState * GS, std::optional<PlayerColor> Player, CClient * C)
  317. : CBattleCallback(Player, C)
  318. {
  319. gs = GS;
  320. waitTillRealize = false;
  321. unlockGsWhenWaiting = false;
  322. }
  323. CCallback::~CCallback() = default;
  324. bool CCallback::canMoveBetween(const int3 &a, const int3 &b)
  325. {
  326. //bidirectional
  327. return gs->map->canMoveBetween(a, b);
  328. }
  329. std::optional<PlayerColor> CCallback::getPlayerID() const
  330. {
  331. return CBattleCallback::getPlayerID();
  332. }
  333. int3 CCallback::getGuardingCreaturePosition(int3 tile)
  334. {
  335. if (!gs->map->isInTheMap(tile))
  336. return int3(-1,-1,-1);
  337. return gs->map->guardingCreaturePositions[tile.z][tile.x][tile.y];
  338. }
  339. void CCallback::dig( const CGObjectInstance *hero )
  340. {
  341. DigWithHero dwh;
  342. dwh.id = hero->id;
  343. sendRequest(dwh);
  344. }
  345. void CCallback::castSpell(const CGHeroInstance *hero, SpellID spellID, const int3 &pos)
  346. {
  347. CastAdvSpell cas;
  348. cas.hid = hero->id;
  349. cas.sid = spellID;
  350. cas.pos = pos;
  351. sendRequest(cas);
  352. }
  353. int CCallback::mergeOrSwapStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  354. {
  355. if(s1->getCreature(p1) == s2->getCreature(p2))
  356. return mergeStacks(s1, s2, p1, p2);
  357. else
  358. return swapCreatures(s1, s2, p1, p2);
  359. }
  360. void CCallback::registerBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents)
  361. {
  362. cl->additionalBattleInts[*player].push_back(battleEvents);
  363. }
  364. void CCallback::unregisterBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents)
  365. {
  366. cl->additionalBattleInts[*player] -= battleEvents;
  367. }
  368. CBattleCallback::CBattleCallback(std::optional<PlayerColor> player, CClient * C):
  369. cl(C),
  370. player(player)
  371. {
  372. }
  373. void CBattleCallback::battleMakeUnitAction(const BattleID & battleID, const BattleAction & action)
  374. {
  375. assert(!cl->gs->getBattle(battleID)->tacticDistance);
  376. MakeAction ma;
  377. ma.ba = action;
  378. ma.battleID = battleID;
  379. sendRequest(ma);
  380. }
  381. void CBattleCallback::battleMakeTacticAction(const BattleID & battleID, const BattleAction & action )
  382. {
  383. assert(cl->gs->getBattle(battleID)->tacticDistance);
  384. MakeAction ma;
  385. ma.ba = action;
  386. ma.battleID = battleID;
  387. sendRequest(ma);
  388. }
  389. std::optional<BattleAction> CBattleCallback::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  390. {
  391. return cl->playerint[getPlayerID().value()]->makeSurrenderRetreatDecision(battleID, battleState);
  392. }
  393. std::shared_ptr<CPlayerBattleCallback> CBattleCallback::getBattle(const BattleID & battleID)
  394. {
  395. if (activeBattles.count(battleID))
  396. return activeBattles.at(battleID);
  397. throw std::runtime_error("Failed to find battle " + std::to_string(battleID.getNum()) + " of player " + player->toString() + ". Number of ongoing battles: " + std::to_string(activeBattles.size()));
  398. }
  399. std::optional<PlayerColor> CBattleCallback::getPlayerID() const
  400. {
  401. return player;
  402. }
  403. void CBattleCallback::onBattleStarted(const IBattleInfo * info)
  404. {
  405. if (activeBattles.count(info->getBattleID()) > 0)
  406. throw std::runtime_error("Player " + player->toString() + " is already engaged in battle " + std::to_string(info->getBattleID().getNum()));
  407. logGlobal->debug("Battle %d started for player %s", info->getBattleID(), player->toString());
  408. activeBattles[info->getBattleID()] = std::make_shared<CPlayerBattleCallback>(info, *getPlayerID());
  409. }
  410. void CBattleCallback::onBattleEnded(const BattleID & battleID)
  411. {
  412. if (activeBattles.count(battleID) == 0)
  413. throw std::runtime_error("Player " + player->toString() + " is not engaged in battle " + std::to_string(battleID.getNum()));
  414. logGlobal->debug("Battle %d ended for player %s", battleID, player->toString());
  415. activeBattles.erase(battleID);
  416. }