CCallback.cpp 13 KB

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