CCallback.cpp 13 KB

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