AIGateway.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675
  1. /*
  2. * AIGateway.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 "../../lib/UnlockGuard.h"
  12. #include "../../lib/mapObjects/MapObjects.h"
  13. #include "../../lib/CConfigHandler.h"
  14. #include "../../lib/CHeroHandler.h"
  15. #include "../../lib/CModHandler.h"
  16. #include "../../lib/CGameState.h"
  17. #include "../../lib/NetPacks.h"
  18. #include "../../lib/serializer/CTypeList.h"
  19. #include "../../lib/serializer/BinarySerializer.h"
  20. #include "../../lib/serializer/BinaryDeserializer.h"
  21. #include "../../lib/battle/BattleStateInfoForRetreat.h"
  22. #include "AIGateway.h"
  23. #include "Goals/Goals.h"
  24. namespace NKAI
  25. {
  26. // our to enemy strength ratio constants
  27. const float SAFE_ATTACK_CONSTANT = 1.2;
  28. const float RETREAT_THRESHOLD = 0.3;
  29. //one thread may be turn of AI and another will be handling a side effect for AI2
  30. boost::thread_specific_ptr<CCallback> cb;
  31. boost::thread_specific_ptr<AIGateway> ai;
  32. //helper RAII to manage global ai/cb ptrs
  33. struct SetGlobalState
  34. {
  35. SetGlobalState(AIGateway * AI)
  36. {
  37. assert(!ai.get());
  38. assert(!cb.get());
  39. ai.reset(AI);
  40. cb.reset(AI->myCb.get());
  41. }
  42. ~SetGlobalState()
  43. {
  44. //TODO: how to handle rm? shouldn't be called after ai is destroyed, hopefully
  45. //TODO: to ensure that, make rm unique_ptr
  46. ai.release();
  47. cb.release();
  48. }
  49. };
  50. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  51. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  52. #define MAKING_TURN SET_GLOBAL_STATE(this)
  53. AIGateway::AIGateway()
  54. {
  55. LOG_TRACE(logAi);
  56. makingTurn = nullptr;
  57. destinationTeleport = ObjectInstanceID();
  58. destinationTeleportPos = int3(-1);
  59. nullkiller.reset(new Nullkiller());
  60. }
  61. AIGateway::~AIGateway()
  62. {
  63. LOG_TRACE(logAi);
  64. finish();
  65. nullkiller.reset();
  66. }
  67. void AIGateway::availableCreaturesChanged(const CGDwelling * town)
  68. {
  69. LOG_TRACE(logAi);
  70. NET_EVENT_HANDLER;
  71. }
  72. void AIGateway::heroMoved(const TryMoveHero & details, bool verbose)
  73. {
  74. LOG_TRACE(logAi);
  75. NET_EVENT_HANDLER;
  76. validateObject(details.id); //enemy hero may have left visible area
  77. auto hero = cb->getHero(details.id);
  78. const int3 from = CGHeroInstance::convertPosition(details.start, false);
  79. const int3 to = CGHeroInstance::convertPosition(details.end, false);
  80. const CGObjectInstance * o1 = vstd::frontOrNull(cb->getVisitableObjs(from, verbose));
  81. const CGObjectInstance * o2 = vstd::frontOrNull(cb->getVisitableObjs(to, verbose));
  82. if(details.result == TryMoveHero::TELEPORTATION)
  83. {
  84. auto t1 = dynamic_cast<const CGTeleport *>(o1);
  85. auto t2 = dynamic_cast<const CGTeleport *>(o2);
  86. if(t1 && t2)
  87. {
  88. if(cb->isTeleportChannelBidirectional(t1->channel))
  89. {
  90. if(o1->ID == Obj::SUBTERRANEAN_GATE && o1->ID == o2->ID) // We need to only add subterranean gates in knownSubterraneanGates. Used for features not yet ported to use teleport channels
  91. {
  92. nullkiller->memory->addSubterraneanGate(o1, o2);
  93. }
  94. }
  95. }
  96. }
  97. else if(details.result == TryMoveHero::EMBARK && hero)
  98. {
  99. //make sure AI not attempt to visit used boat
  100. validateObject(hero->boat);
  101. }
  102. else if(details.result == TryMoveHero::DISEMBARK && o1)
  103. {
  104. auto boat = dynamic_cast<const CGBoat *>(o1);
  105. if(boat)
  106. addVisitableObj(boat);
  107. }
  108. }
  109. void AIGateway::heroInGarrisonChange(const CGTownInstance * town)
  110. {
  111. LOG_TRACE(logAi);
  112. NET_EVENT_HANDLER;
  113. }
  114. void AIGateway::centerView(int3 pos, int focusTime)
  115. {
  116. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  117. NET_EVENT_HANDLER;
  118. }
  119. void AIGateway::artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst)
  120. {
  121. LOG_TRACE(logAi);
  122. NET_EVENT_HANDLER;
  123. }
  124. void AIGateway::artifactAssembled(const ArtifactLocation & al)
  125. {
  126. LOG_TRACE(logAi);
  127. NET_EVENT_HANDLER;
  128. }
  129. void AIGateway::showTavernWindow(const CGObjectInstance * townOrTavern)
  130. {
  131. LOG_TRACE(logAi);
  132. NET_EVENT_HANDLER;
  133. }
  134. void AIGateway::showThievesGuildWindow(const CGObjectInstance * obj)
  135. {
  136. LOG_TRACE(logAi);
  137. NET_EVENT_HANDLER;
  138. }
  139. void AIGateway::playerBlocked(int reason, bool start)
  140. {
  141. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  142. NET_EVENT_HANDLER;
  143. if(start && reason == PlayerBlocked::UPCOMING_BATTLE)
  144. status.setBattle(UPCOMING_BATTLE);
  145. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  146. status.setMove(start);
  147. }
  148. void AIGateway::showPuzzleMap()
  149. {
  150. LOG_TRACE(logAi);
  151. NET_EVENT_HANDLER;
  152. }
  153. void AIGateway::showShipyardDialog(const IShipyard * obj)
  154. {
  155. LOG_TRACE(logAi);
  156. NET_EVENT_HANDLER;
  157. }
  158. void AIGateway::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
  159. {
  160. LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult.messageToSelf);
  161. NET_EVENT_HANDLER;
  162. logAi->debug("Player %d (%s): I heard that player %d (%s) %s.", playerID, playerID.getStr(), player, player.getStr(), (victoryLossCheckResult.victory() ? "won" : "lost"));
  163. // some whitespace to flush stream
  164. logAi->debug(std::string(200, ' '));
  165. if(player == playerID)
  166. {
  167. if(victoryLossCheckResult.victory())
  168. {
  169. logAi->debug("AIGateway: Player %d (%s) won. I won! Incredible!", player, player.getStr());
  170. logAi->debug("Turn nr %d", myCb->getDate());
  171. }
  172. else
  173. {
  174. logAi->debug("AIGateway: Player %d (%s) lost. It's me. What a disappointment! :(", player, player.getStr());
  175. }
  176. // some whitespace to flush stream
  177. logAi->debug(std::string(200, ' '));
  178. finish();
  179. }
  180. }
  181. void AIGateway::artifactPut(const ArtifactLocation & al)
  182. {
  183. LOG_TRACE(logAi);
  184. NET_EVENT_HANDLER;
  185. }
  186. void AIGateway::artifactRemoved(const ArtifactLocation & al)
  187. {
  188. LOG_TRACE(logAi);
  189. NET_EVENT_HANDLER;
  190. }
  191. void AIGateway::artifactDisassembled(const ArtifactLocation & al)
  192. {
  193. LOG_TRACE(logAi);
  194. NET_EVENT_HANDLER;
  195. }
  196. void AIGateway::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  197. {
  198. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->getObjectName() : std::string("n/a")));
  199. NET_EVENT_HANDLER;
  200. if(start && visitedObj) //we can end visit with null object, anyway
  201. {
  202. nullkiller->memory->markObjectVisited(visitedObj);
  203. }
  204. status.heroVisit(visitedObj, start);
  205. }
  206. void AIGateway::availableArtifactsChanged(const CGBlackMarket * bm)
  207. {
  208. LOG_TRACE(logAi);
  209. NET_EVENT_HANDLER;
  210. }
  211. void AIGateway::heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town)
  212. {
  213. LOG_TRACE(logAi);
  214. NET_EVENT_HANDLER;
  215. }
  216. void AIGateway::tileHidden(const std::unordered_set<int3, ShashInt3> & pos)
  217. {
  218. LOG_TRACE(logAi);
  219. NET_EVENT_HANDLER;
  220. nullkiller->memory->removeInvisibleObjects(myCb.get());
  221. }
  222. void AIGateway::tileRevealed(const std::unordered_set<int3, ShashInt3> & pos)
  223. {
  224. LOG_TRACE(logAi);
  225. NET_EVENT_HANDLER;
  226. for(int3 tile : pos)
  227. {
  228. for(const CGObjectInstance * obj : myCb->getVisitableObjs(tile))
  229. addVisitableObj(obj);
  230. }
  231. }
  232. void AIGateway::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  233. {
  234. LOG_TRACE(logAi);
  235. NET_EVENT_HANDLER;
  236. auto firstHero = cb->getHero(hero1);
  237. auto secondHero = cb->getHero(hero2);
  238. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s (%d) and %s (%d)") % firstHero->name % firstHero->tempOwner % secondHero->name % secondHero->tempOwner));
  239. requestActionASAP([=]()
  240. {
  241. auto transferFrom2to1 = [this](const CGHeroInstance * h1, const CGHeroInstance * h2) -> void
  242. {
  243. this->pickBestCreatures(h1, h2);
  244. this->pickBestArtifacts(h1, h2);
  245. };
  246. //Do not attempt army or artifacts exchange if we visited ally player
  247. //Visits can still be useful if hero have skills like Scholar
  248. if(firstHero->tempOwner != secondHero->tempOwner)
  249. {
  250. logAi->debug("Heroes owned by different players. Do not exchange army or artifacts.");
  251. }
  252. else
  253. {
  254. if(nullkiller->isActive(firstHero))
  255. transferFrom2to1(secondHero, firstHero);
  256. else
  257. transferFrom2to1(firstHero, secondHero);
  258. }
  259. answerQuery(query, 0);
  260. });
  261. }
  262. void AIGateway::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  263. {
  264. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which % val);
  265. NET_EVENT_HANDLER;
  266. }
  267. void AIGateway::showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level)
  268. {
  269. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  270. NET_EVENT_HANDLER;
  271. }
  272. void AIGateway::heroMovePointsChanged(const CGHeroInstance * hero)
  273. {
  274. LOG_TRACE(logAi);
  275. NET_EVENT_HANDLER;
  276. }
  277. void AIGateway::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  278. {
  279. LOG_TRACE(logAi);
  280. NET_EVENT_HANDLER;
  281. }
  282. void AIGateway::newObject(const CGObjectInstance * obj)
  283. {
  284. LOG_TRACE(logAi);
  285. NET_EVENT_HANDLER;
  286. if(obj->isVisitable())
  287. addVisitableObj(obj);
  288. }
  289. //to prevent AI from accessing objects that got deleted while they became invisible (Cover of Darkness, enemy hero moved etc.) below code allows AI to know deletion of objects out of sight
  290. //see: RemoveObject::applyFirstCl, to keep AI "not cheating" do not use advantage of this and use this function just to prevent crashes
  291. void AIGateway::objectRemoved(const CGObjectInstance * obj)
  292. {
  293. LOG_TRACE(logAi);
  294. NET_EVENT_HANDLER;
  295. if(!nullkiller) // crash protection
  296. return;
  297. nullkiller->memory->removeFromMemory(obj);
  298. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  299. {
  300. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  301. }
  302. }
  303. void AIGateway::showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor)
  304. {
  305. LOG_TRACE(logAi);
  306. NET_EVENT_HANDLER;
  307. }
  308. void AIGateway::playerBonusChanged(const Bonus & bonus, bool gain)
  309. {
  310. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  311. NET_EVENT_HANDLER;
  312. }
  313. void AIGateway::heroCreated(const CGHeroInstance * h)
  314. {
  315. LOG_TRACE(logAi);
  316. NET_EVENT_HANDLER;
  317. }
  318. void AIGateway::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  319. {
  320. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  321. NET_EVENT_HANDLER;
  322. }
  323. void AIGateway::showInfoDialog(const std::string & text, const std::vector<Component> & components, int soundID)
  324. {
  325. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  326. NET_EVENT_HANDLER;
  327. }
  328. void AIGateway::requestRealized(PackageApplied * pa)
  329. {
  330. LOG_TRACE(logAi);
  331. NET_EVENT_HANDLER;
  332. if(status.haveTurn())
  333. {
  334. if(pa->packType == typeList.getTypeID<EndTurn>())
  335. {
  336. if(pa->result)
  337. status.madeTurn();
  338. }
  339. }
  340. if(pa->packType == typeList.getTypeID<QueryReply>())
  341. {
  342. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  343. }
  344. }
  345. void AIGateway::receivedResource()
  346. {
  347. LOG_TRACE(logAi);
  348. NET_EVENT_HANDLER;
  349. }
  350. void AIGateway::showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor)
  351. {
  352. LOG_TRACE(logAi);
  353. NET_EVENT_HANDLER;
  354. }
  355. void AIGateway::heroManaPointsChanged(const CGHeroInstance * hero)
  356. {
  357. LOG_TRACE(logAi);
  358. NET_EVENT_HANDLER;
  359. }
  360. void AIGateway::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  361. {
  362. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  363. NET_EVENT_HANDLER;
  364. }
  365. void AIGateway::battleResultsApplied()
  366. {
  367. LOG_TRACE(logAi);
  368. NET_EVENT_HANDLER;
  369. assert(status.getBattle() == ENDING_BATTLE);
  370. status.setBattle(NO_BATTLE);
  371. }
  372. void AIGateway::objectPropertyChanged(const SetObjectProperty * sop)
  373. {
  374. LOG_TRACE(logAi);
  375. NET_EVENT_HANDLER;
  376. if(sop->what == ObjProperty::OWNER)
  377. {
  378. auto relations = myCb->getPlayerRelations(playerID, (PlayerColor)sop->val);
  379. auto obj = myCb->getObj(sop->id, false);
  380. if(!nullkiller) // crash protection
  381. return;
  382. if(obj)
  383. {
  384. if(relations == PlayerRelations::ENEMIES)
  385. {
  386. //we want to visit objects owned by oppponents
  387. //addVisitableObj(obj); // TODO: Remove once save compatability broken. In past owned objects were removed from this set
  388. nullkiller->memory->markObjectUnvisited(obj);
  389. }
  390. else if(relations == PlayerRelations::SAME_PLAYER && obj->ID == Obj::TOWN)
  391. {
  392. // reevaluate defence for a new town
  393. nullkiller->dangerHitMap->reset();
  394. }
  395. }
  396. }
  397. }
  398. void AIGateway::buildChanged(const CGTownInstance * town, BuildingID buildingID, int what)
  399. {
  400. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  401. NET_EVENT_HANDLER;
  402. }
  403. void AIGateway::heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain)
  404. {
  405. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  406. NET_EVENT_HANDLER;
  407. }
  408. void AIGateway::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor)
  409. {
  410. LOG_TRACE(logAi);
  411. NET_EVENT_HANDLER;
  412. }
  413. void AIGateway::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions)
  414. {
  415. //TODO: AI support for ViewXXX spell
  416. LOG_TRACE(logAi);
  417. NET_EVENT_HANDLER;
  418. }
  419. boost::optional<BattleAction> AIGateway::makeSurrenderRetreatDecision(
  420. const BattleStateInfoForRetreat & battleState)
  421. {
  422. LOG_TRACE(logAi);
  423. NET_EVENT_HANDLER;
  424. double fightRatio = battleState.getOurStrength() / (double)battleState.getEnemyStrength();
  425. // if we have no towns - things are already bad, so retreat is not an option.
  426. if(cb->getTownsInfo().size() && fightRatio < RETREAT_THRESHOLD && battleState.canFlee)
  427. {
  428. return BattleAction::makeRetreat(battleState.ourSide);
  429. }
  430. return boost::none;
  431. }
  432. void AIGateway::init(std::shared_ptr<Environment> env, std::shared_ptr<CCallback> CB)
  433. {
  434. LOG_TRACE(logAi);
  435. myCb = CB;
  436. cbc = CB;
  437. NET_EVENT_HANDLER;
  438. playerID = *myCb->getMyColor();
  439. myCb->waitTillRealize = true;
  440. myCb->unlockGsWhenWaiting = true;
  441. nullkiller->init(CB, playerID);
  442. retrieveVisitableObjs();
  443. }
  444. void AIGateway::yourTurn()
  445. {
  446. LOG_TRACE(logAi);
  447. NET_EVENT_HANDLER;
  448. status.startedTurn();
  449. makingTurn = make_unique<boost::thread>(&AIGateway::makeTurn, this);
  450. }
  451. void AIGateway::heroGotLevel(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
  452. {
  453. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  454. NET_EVENT_HANDLER;
  455. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->name % hero->level));
  456. HeroPtr hPtr = hero;
  457. requestActionASAP([=]()
  458. {
  459. if(hPtr.validAndSet())
  460. {
  461. nullkiller->heroManager->update();
  462. answerQuery(queryID, nullkiller->heroManager->selectBestSkill(hPtr, skills));
  463. }
  464. });
  465. }
  466. void AIGateway::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  467. {
  468. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  469. NET_EVENT_HANDLER;
  470. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  471. requestActionASAP([=](){ answerQuery(queryID, 0); });
  472. }
  473. void AIGateway::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel)
  474. {
  475. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i'", text % askID % soundID % selection % cancel);
  476. NET_EVENT_HANDLER;
  477. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  478. % components.size() % text));
  479. auto hero = nullkiller->getActiveHero();
  480. auto target = nullkiller->getTargetTile();
  481. if(!selection && cancel)
  482. {
  483. requestActionASAP([=]()
  484. {
  485. //yes&no -> always answer yes, we are a brave AI :)
  486. auto answer = 1;
  487. auto objects = cb->getVisitableObjs(target);
  488. if(hero.validAndSet() && target.valid() && objects.size())
  489. {
  490. auto objType = objects.front()->ID;
  491. if(objType == Obj::ARTIFACT || objType == Obj::RESOURCE)
  492. {
  493. auto ratio = (float)nullkiller->dangerEvaluator->evaluateDanger(target, hero.get()) / (float)hero->getTotalStrength();
  494. bool dangerUnknown = ratio == 0;
  495. bool dangerTooHigh = ratio > (1 / SAFE_ATTACK_CONSTANT);
  496. logAi->trace("Guarded object query hook: %s by %s danger ratio %f", target.toString(), hero.name, ratio);
  497. if(text.find("guarded") >= 0 && (dangerUnknown || dangerTooHigh))
  498. answer = 0; // no
  499. }
  500. }
  501. answerQuery(askID, answer);
  502. });
  503. return;
  504. }
  505. requestActionASAP([=]()
  506. {
  507. int sel = 0;
  508. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  509. sel = components.size();
  510. // TODO: Find better way to understand it is Chest of Treasures
  511. if(hero.validAndSet()
  512. && components.size() == 2
  513. && components.front().id == Component::RESOURCE
  514. && (nullkiller->heroManager->getHeroRole(hero) != HeroRole::MAIN
  515. || nullkiller->buildAnalyzer->getGoldPreasure() > MAX_GOLD_PEASURE))
  516. {
  517. sel = 1; // for now lets pick gold from a chest.
  518. }
  519. answerQuery(askID, sel);
  520. });
  521. }
  522. void AIGateway::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  523. {
  524. NET_EVENT_HANDLER;
  525. status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits") % exits.size()));
  526. int choosenExit = -1;
  527. if(impassable)
  528. {
  529. nullkiller->memory->knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
  530. }
  531. else if(destinationTeleport != ObjectInstanceID() && destinationTeleportPos.valid())
  532. {
  533. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  534. if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  535. choosenExit = vstd::find_pos(exits, neededExit);
  536. }
  537. for(auto exit : exits)
  538. {
  539. if(status.channelProbing() && exit.first == destinationTeleport)
  540. {
  541. choosenExit = vstd::find_pos(exits, exit);
  542. break;
  543. }
  544. else
  545. {
  546. // TODO: Implement checking if visiting that teleport will uncovert any FoW
  547. // So far this is the best option to handle decision about probing
  548. auto obj = cb->getObj(exit.first, false);
  549. if(obj == nullptr && !vstd::contains(teleportChannelProbingList, exit.first))
  550. {
  551. if(exit.first != destinationTeleport)
  552. teleportChannelProbingList.push_back(exit.first);
  553. }
  554. }
  555. }
  556. requestActionASAP([=]()
  557. {
  558. answerQuery(askID, choosenExit);
  559. });
  560. }
  561. void AIGateway::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
  562. {
  563. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  564. NET_EVENT_HANDLER;
  565. std::string s1 = up ? up->nodeName() : "NONE";
  566. std::string s2 = down ? down->nodeName() : "NONE";
  567. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  568. //you can't request action from action-response thread
  569. requestActionASAP([=]()
  570. {
  571. if(removableUnits)
  572. pickBestCreatures(down, up);
  573. answerQuery(queryID, 0);
  574. });
  575. }
  576. void AIGateway::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  577. {
  578. NET_EVENT_HANDLER;
  579. status.addQuery(askID, "Map object select query");
  580. requestActionASAP([=](){ answerQuery(askID, selectedObject.getNum()); });
  581. }
  582. void AIGateway::saveGame(BinarySerializer & h, const int version)
  583. {
  584. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  585. NET_EVENT_HANDLER;
  586. nullkiller->memory->removeInvisibleObjects(myCb.get());
  587. CAdventureAI::saveGame(h, version);
  588. serializeInternal(h, version);
  589. }
  590. void AIGateway::loadGame(BinaryDeserializer & h, const int version)
  591. {
  592. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  593. //NET_EVENT_HANDLER;
  594. #if 0
  595. //disabled due to issue 2890
  596. registerGoals(h);
  597. #endif // 0
  598. CAdventureAI::loadGame(h, version);
  599. serializeInternal(h, version);
  600. }
  601. bool AIGateway::makePossibleUpgrades(const CArmedInstance * obj)
  602. {
  603. if(!obj)
  604. return false;
  605. bool upgraded = false;
  606. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  607. {
  608. if(const CStackInstance * s = obj->getStackPtr(SlotID(i)))
  609. {
  610. UpgradeInfo ui;
  611. myCb->getUpgradeInfo(obj, SlotID(i), ui);
  612. if(ui.oldID >= 0 && nullkiller->getFreeResources().canAfford(ui.cost[0] * s->count))
  613. {
  614. myCb->upgradeCreature(obj, SlotID(i), ui.newID[0]);
  615. upgraded = true;
  616. logAi->debug("Upgraded %d %s to %s", s->count, ui.oldID.toCreature()->namePl, ui.newID[0].toCreature()->namePl);
  617. }
  618. }
  619. }
  620. return upgraded;
  621. }
  622. void AIGateway::makeTurn()
  623. {
  624. MAKING_TURN;
  625. auto day = cb->getDate(Date::EDateType::DAY);
  626. logAi->info("Player %d (%s) starting turn, day %d", playerID, playerID.getStr(), day);
  627. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  628. setThreadName("AIGateway::makeTurn");
  629. if(cb->getDate(Date::DAY_OF_WEEK) == 1)
  630. {
  631. std::vector<const CGObjectInstance *> objs;
  632. retrieveVisitableObjs(objs, true);
  633. for(const CGObjectInstance * obj : objs)
  634. {
  635. if(isWeeklyRevisitable(obj))
  636. {
  637. addVisitableObj(obj);
  638. nullkiller->memory->markObjectUnvisited(obj);
  639. }
  640. }
  641. }
  642. cb->sendMessage("vcmieagles");
  643. if(cb->getDate(Date::DAY) == 1)
  644. {
  645. retrieveVisitableObjs();
  646. }
  647. #if NKAI_TRACE_LEVEL == 0
  648. try
  649. {
  650. #endif
  651. nullkiller->makeTurn();
  652. //for debug purpose
  653. for (auto h : cb->getHeroesInfo())
  654. {
  655. if (h->movement)
  656. logAi->warn("Hero %s has %d MP left", h->name, h->movement);
  657. }
  658. #if NKAI_TRACE_LEVEL == 0
  659. }
  660. catch (boost::thread_interrupted & e)
  661. {
  662. (void)e;
  663. logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
  664. return;
  665. }
  666. catch (std::exception & e)
  667. {
  668. logAi->debug("Making turn thread has caught an exception: %s", e.what());
  669. }
  670. #endif
  671. endTurn();
  672. }
  673. void AIGateway::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  674. {
  675. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->name % obj->getObjectName() % obj->pos.toString());
  676. switch(obj->ID)
  677. {
  678. case Obj::CREATURE_GENERATOR1:
  679. recruitCreatures(dynamic_cast<const CGDwelling *>(obj), h.get());
  680. break;
  681. case Obj::TOWN:
  682. if(h->visitedTown) //we are inside, not just attacking
  683. {
  684. makePossibleUpgrades(h.get());
  685. if(!h->visitedTown->garrisonHero || !nullkiller->isHeroLocked(h->visitedTown->garrisonHero))
  686. moveCreaturesToHero(h->visitedTown);
  687. if(nullkiller->heroManager->getHeroRole(h) == HeroRole::MAIN && !h->hasSpellbook()
  688. && nullkiller->getFreeGold() >= GameConstants::SPELLBOOK_GOLD_COST)
  689. {
  690. if(h->visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  691. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  692. }
  693. }
  694. break;
  695. case Obj::HILL_FORT:
  696. makePossibleUpgrades(h.get());
  697. break;
  698. }
  699. }
  700. void AIGateway::moveCreaturesToHero(const CGTownInstance * t)
  701. {
  702. if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
  703. {
  704. pickBestCreatures(t->visitingHero, t->getUpperArmy());
  705. }
  706. }
  707. void AIGateway::pickBestCreatures(const CArmedInstance * destinationArmy, const CArmedInstance * source)
  708. {
  709. const CArmedInstance * armies[] = {destinationArmy, source};
  710. auto bestArmy = nullkiller->armyManager->getBestArmy(destinationArmy, destinationArmy, source);
  711. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  712. for(SlotID i = SlotID(0); i.validSlot(); i.advance(1)) //i-th strongest creature type will go to i-th slot
  713. {
  714. if(i.getNum() >= bestArmy.size())
  715. {
  716. if(destinationArmy->hasStackAtSlot(i))
  717. {
  718. auto creature = destinationArmy->getCreature(i);
  719. auto targetSlot = source->getSlotFor(creature);
  720. if(targetSlot.validSlot())
  721. {
  722. // remove unwanted creatures
  723. cb->mergeOrSwapStacks(destinationArmy, source, i, targetSlot);
  724. }
  725. else if(destinationArmy->getStack(i).getPower() < destinationArmy->getArmyStrength() / 100)
  726. {
  727. // dismiss creatures if the amount is small
  728. cb->dismissCreature(destinationArmy, i);
  729. }
  730. }
  731. continue;
  732. }
  733. const CCreature * targetCreature = bestArmy[i.getNum()].creature;
  734. for(auto armyPtr : armies)
  735. {
  736. for(SlotID j = SlotID(0); j.validSlot(); j.advance(1))
  737. {
  738. if(armyPtr->getCreature(j) == targetCreature && (i != j || armyPtr != destinationArmy)) //it's a searched creature not in dst SLOT
  739. {
  740. //can't take away last creature without split. generate a new stack with 1 creature which is weak but fast
  741. if(armyPtr == source
  742. && source->needsLastStack()
  743. && source->stacksCount() == 1
  744. && (!destinationArmy->hasStackAtSlot(i) || destinationArmy->getCreature(i) == targetCreature))
  745. {
  746. auto weakest = nullkiller->armyManager->getWeakestCreature(bestArmy);
  747. if(weakest->creature == targetCreature)
  748. {
  749. if(1 == source->getStackCount(j))
  750. break;
  751. // move all except 1 of weakest creature from source to destination
  752. cb->splitStack(
  753. source,
  754. destinationArmy,
  755. j,
  756. destinationArmy->getSlotFor(targetCreature),
  757. destinationArmy->getStackCount(i) + source->getStackCount(j) - 1);
  758. break;
  759. }
  760. else
  761. {
  762. // Source last stack is not weakest. Move 1 of weakest creature from destination to source
  763. cb->splitStack(
  764. destinationArmy,
  765. source,
  766. destinationArmy->getSlotFor(weakest->creature),
  767. source->getFreeSlot(),
  768. 1);
  769. }
  770. }
  771. cb->mergeOrSwapStacks(armyPtr, destinationArmy, j, i);
  772. }
  773. }
  774. }
  775. }
  776. //TODO - having now strongest possible army, we may want to think about arranging stacks
  777. }
  778. void AIGateway::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other)
  779. {
  780. auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void
  781. {
  782. bool changeMade = false;
  783. do
  784. {
  785. changeMade = false;
  786. //we collect gear always in same order
  787. std::vector<ArtifactLocation> allArtifacts;
  788. if(giveStuffToFirstHero)
  789. {
  790. for(auto p : h->artifactsWorn)
  791. {
  792. if(p.second.artifact)
  793. allArtifacts.push_back(ArtifactLocation(h, p.first));
  794. }
  795. }
  796. for(auto slot : h->artifactsInBackpack)
  797. allArtifacts.push_back(ArtifactLocation(h, h->getArtPos(slot.artifact)));
  798. if(otherh)
  799. {
  800. for(auto p : otherh->artifactsWorn)
  801. {
  802. if(p.second.artifact)
  803. allArtifacts.push_back(ArtifactLocation(otherh, p.first));
  804. }
  805. for(auto slot : otherh->artifactsInBackpack)
  806. allArtifacts.push_back(ArtifactLocation(otherh, otherh->getArtPos(slot.artifact)));
  807. }
  808. //we give stuff to one hero or another, depending on giveStuffToFirstHero
  809. const CGHeroInstance * target = nullptr;
  810. if(giveStuffToFirstHero || !otherh)
  811. target = h;
  812. else
  813. target = otherh;
  814. for(auto location : allArtifacts)
  815. {
  816. if(location.relatedObj() == target && location.slot < ArtifactPosition::AFTER_LAST)
  817. continue; //don't reequip artifact we already wear
  818. if(location.slot == ArtifactPosition::MACH4) // don't attempt to move catapult
  819. continue;
  820. auto s = location.getSlot();
  821. if(!s || s->locked) //we can't move locks
  822. continue;
  823. auto artifact = s->artifact;
  824. if(!artifact)
  825. continue;
  826. //FIXME: why are the above possible to be null?
  827. bool emptySlotFound = false;
  828. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  829. {
  830. ArtifactLocation destLocation(target, slot);
  831. if(target->isPositionFree(slot) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  832. {
  833. cb->swapArtifacts(location, destLocation); //just put into empty slot
  834. emptySlotFound = true;
  835. changeMade = true;
  836. break;
  837. }
  838. }
  839. if(!emptySlotFound) //try to put that atifact in already occupied slot
  840. {
  841. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  842. {
  843. auto otherSlot = target->getSlot(slot);
  844. if(otherSlot && otherSlot->artifact) //we need to exchange artifact for better one
  845. {
  846. ArtifactLocation destLocation(target, slot);
  847. //if that artifact is better than what we have, pick it
  848. if(compareArtifacts(artifact, otherSlot->artifact) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  849. {
  850. cb->swapArtifacts(location, ArtifactLocation(target, target->getArtPos(otherSlot->artifact)));
  851. changeMade = true;
  852. break;
  853. }
  854. }
  855. }
  856. }
  857. if(changeMade)
  858. break; //start evaluating artifacts from scratch
  859. }
  860. }
  861. while(changeMade);
  862. };
  863. equipBest(h, other, true);
  864. if(other)
  865. equipBest(h, other, false);
  866. }
  867. void AIGateway::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
  868. {
  869. //now used only for visited dwellings / towns, not BuyArmy goal
  870. for(int i = 0; i < d->creatures.size(); i++)
  871. {
  872. if(!d->creatures[i].second.size())
  873. continue;
  874. int count = d->creatures[i].first;
  875. CreatureID creID = d->creatures[i].second.back();
  876. vstd::amin(count, cb->getResourceAmount() / VLC->creh->objects[creID]->cost);
  877. if(count > 0)
  878. cb->recruitCreatures(d, recruiter, creID, count, i);
  879. }
  880. }
  881. bool AIGateway::canRecruitAnyHero(const CGTownInstance * t) const
  882. {
  883. //TODO: make gathering gold, building tavern or conquering town (?) possible subgoals
  884. if(!t)
  885. t = findTownWithTavern();
  886. if(!t || !townHasFreeTavern(t))
  887. return false;
  888. if(cb->getResourceAmount(Res::GOLD) < GameConstants::HERO_GOLD_COST) //TODO: use ResourceManager
  889. return false;
  890. if(cb->getHeroesInfo().size() >= ALLOWED_ROAMING_HEROES)
  891. return false;
  892. if(cb->getHeroesInfo().size() >= VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)
  893. return false;
  894. if(!cb->getAvailableHeroes(t).size())
  895. return false;
  896. return true;
  897. }
  898. void AIGateway::battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side)
  899. {
  900. NET_EVENT_HANDLER;
  901. assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  902. status.setBattle(ONGOING_BATTLE);
  903. const CGObjectInstance * presumedEnemy = vstd::backOrNull(cb->getVisitableObjs(tile)); //may be nullptr in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit
  904. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->getObjectName() : "unknown enemy") % tile.toString());
  905. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  906. }
  907. void AIGateway::battleEnd(const BattleResult * br)
  908. {
  909. NET_EVENT_HANDLER;
  910. assert(status.getBattle() == ONGOING_BATTLE);
  911. status.setBattle(ENDING_BATTLE);
  912. bool won = br->winner == myCb->battleGetMySide();
  913. logAi->debug("Player %d (%s): I %s the %s!", playerID, playerID.getStr(), (won ? "won" : "lost"), battlename);
  914. battlename.clear();
  915. CAdventureAI::battleEnd(br);
  916. }
  917. void AIGateway::waitTillFree()
  918. {
  919. auto unlock = vstd::makeUnlockSharedGuard(CGameState::mutex);
  920. status.waitTillFree();
  921. }
  922. void AIGateway::retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned) const
  923. {
  924. foreach_tile_pos([&](const int3 & pos)
  925. {
  926. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  927. {
  928. if(includeOwned || obj->tempOwner != playerID)
  929. out.push_back(obj);
  930. }
  931. });
  932. }
  933. void AIGateway::retrieveVisitableObjs()
  934. {
  935. foreach_tile_pos([&](const int3 & pos)
  936. {
  937. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  938. {
  939. if(obj->tempOwner != playerID)
  940. addVisitableObj(obj);
  941. }
  942. });
  943. }
  944. std::vector<const CGObjectInstance *> AIGateway::getFlaggedObjects() const
  945. {
  946. std::vector<const CGObjectInstance *> ret;
  947. for(const CGObjectInstance * obj : nullkiller->memory->visitableObjs)
  948. {
  949. if(obj->tempOwner == playerID)
  950. ret.push_back(obj);
  951. }
  952. return ret;
  953. }
  954. void AIGateway::addVisitableObj(const CGObjectInstance * obj)
  955. {
  956. if(obj->ID == Obj::EVENT)
  957. return;
  958. nullkiller->memory->addVisitableObject(obj);
  959. if(obj->ID == Obj::HERO && cb->getPlayerRelations(obj->tempOwner, playerID) == PlayerRelations::ENEMIES)
  960. {
  961. nullkiller->dangerHitMap->reset();
  962. }
  963. }
  964. HeroPtr AIGateway::getHeroWithGrail() const
  965. {
  966. for(const CGHeroInstance * h : cb->getHeroesInfo())
  967. {
  968. if(h->hasArt(ArtifactID::GRAIL))
  969. return h;
  970. }
  971. return nullptr;
  972. }
  973. bool AIGateway::moveHeroToTile(int3 dst, HeroPtr h)
  974. {
  975. if(h->inTownGarrison && h->visitedTown)
  976. {
  977. cb->swapGarrisonHero(h->visitedTown);
  978. moveCreaturesToHero(h->visitedTown);
  979. }
  980. //TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
  981. auto afterMovementCheck = [&]() -> void
  982. {
  983. waitTillFree(); //movement may cause battle or blocking dialog
  984. if(!h)
  985. {
  986. lostHero(h);
  987. teleportChannelProbingList.clear();
  988. if(status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
  989. status.setChannelProbing(false);
  990. throw cannotFulfillGoalException("Hero was lost!");
  991. }
  992. };
  993. logAi->debug("Moving hero %s to tile %s", h->name, dst.toString());
  994. int3 startHpos = h->visitablePos();
  995. bool ret = false;
  996. if(startHpos == dst)
  997. {
  998. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  999. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1000. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1001. afterMovementCheck(); // TODO: is it feasible to hero get killed there if game work properly?
  1002. // If revisiting, teleport probing is never done, and so the entries into the list would remain unused and uncleared
  1003. teleportChannelProbingList.clear();
  1004. // not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
  1005. ret = true;
  1006. }
  1007. else
  1008. {
  1009. CGPath path;
  1010. cb->getPathsInfo(h.get())->getPath(path, dst);
  1011. if(path.nodes.empty())
  1012. {
  1013. logAi->error("Hero %s cannot reach %s.", h->name, dst.toString());
  1014. return true;
  1015. }
  1016. int i = (int)path.nodes.size() - 1;
  1017. auto getObj = [&](int3 coord, bool ignoreHero)
  1018. {
  1019. auto tile = cb->getTile(coord, false);
  1020. assert(tile);
  1021. return tile->topVisitableObj(ignoreHero);
  1022. //return cb->getTile(coord,false)->topVisitableObj(ignoreHero);
  1023. };
  1024. auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool
  1025. {
  1026. if(action != CGPathNode::TELEPORT_NORMAL && action != CGPathNode::TELEPORT_BLOCKING_VISIT)
  1027. {
  1028. if(action != CGPathNode::TELEPORT_BATTLE)
  1029. {
  1030. return false;
  1031. }
  1032. }
  1033. return true;
  1034. };
  1035. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1036. {
  1037. if(CGTeleport::isConnected(currentObject, nextObjectTop))
  1038. return nextObjectTop;
  1039. if(nextObjectTop && nextObjectTop->ID == Obj::HERO)
  1040. {
  1041. if(CGTeleport::isConnected(currentObject, nextObject))
  1042. return nextObject;
  1043. }
  1044. return nullptr;
  1045. };
  1046. auto doMovement = [&](int3 dst, bool transit)
  1047. {
  1048. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true), transit);
  1049. };
  1050. auto doTeleportMovement = [&](ObjectInstanceID exitId, int3 exitPos)
  1051. {
  1052. destinationTeleport = exitId;
  1053. if(exitPos.valid())
  1054. destinationTeleportPos = CGHeroInstance::convertPosition(exitPos, true);
  1055. cb->moveHero(*h, h->pos);
  1056. destinationTeleport = ObjectInstanceID();
  1057. destinationTeleportPos = int3(-1);
  1058. afterMovementCheck();
  1059. };
  1060. auto doChannelProbing = [&]() -> void
  1061. {
  1062. auto currentPos = CGHeroInstance::convertPosition(h->pos, false);
  1063. auto currentExit = getObj(currentPos, true)->id;
  1064. status.setChannelProbing(true);
  1065. for(auto exit : teleportChannelProbingList)
  1066. doTeleportMovement(exit, int3(-1));
  1067. teleportChannelProbingList.clear();
  1068. status.setChannelProbing(false);
  1069. doTeleportMovement(currentExit, currentPos);
  1070. };
  1071. for(; i > 0; i--)
  1072. {
  1073. int3 currentCoord = path.nodes[i].coord;
  1074. int3 nextCoord = path.nodes[i - 1].coord;
  1075. auto currentObject = getObj(currentCoord, currentCoord == CGHeroInstance::convertPosition(h->pos, false));
  1076. auto nextObjectTop = getObj(nextCoord, false);
  1077. auto nextObject = getObj(nextCoord, true);
  1078. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  1079. if(isTeleportAction(path.nodes[i - 1].action) && destTeleportObj != nullptr)
  1080. {
  1081. //we use special login if hero standing on teleporter it's mean we need
  1082. doTeleportMovement(destTeleportObj->id, nextCoord);
  1083. if(teleportChannelProbingList.size())
  1084. doChannelProbing();
  1085. nullkiller->memory->markObjectVisited(destTeleportObj); //FIXME: Monoliths are not correctly visited
  1086. continue;
  1087. }
  1088. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1089. if(path.nodes[i - 1].turns)
  1090. {
  1091. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1092. break;
  1093. }
  1094. int3 endpos = path.nodes[i - 1].coord;
  1095. if(endpos == h->visitablePos())
  1096. continue;
  1097. bool isConnected = false;
  1098. bool isNextObjectTeleport = false;
  1099. // Check there is node after next one; otherwise transit is pointless
  1100. if(i - 2 >= 0)
  1101. {
  1102. isConnected = CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i - 2].coord, false));
  1103. isNextObjectTeleport = CGTeleport::isTeleport(nextObjectTop);
  1104. }
  1105. if(isConnected || isNextObjectTeleport)
  1106. {
  1107. // Hero should be able to go through object if it's allow transit
  1108. doMovement(endpos, true);
  1109. }
  1110. else if(path.nodes[i - 1].layer == EPathfindingLayer::AIR)
  1111. {
  1112. doMovement(endpos, true);
  1113. }
  1114. else
  1115. {
  1116. doMovement(endpos, false);
  1117. }
  1118. afterMovementCheck();
  1119. if(teleportChannelProbingList.size())
  1120. doChannelProbing();
  1121. }
  1122. if(path.nodes[0].action == CGPathNode::BLOCKING_VISIT || path.nodes[0].action == CGPathNode::BATTLE)
  1123. {
  1124. // when we take resource we do not reach its position. We even might not move
  1125. // also guarded town is not get visited automatically after capturing
  1126. ret = h && i == 0;
  1127. }
  1128. }
  1129. if(h)
  1130. {
  1131. if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1132. {
  1133. if(visitedObject != *h)
  1134. performObjectInteraction(visitedObject, h);
  1135. }
  1136. }
  1137. if(h) //we could have lost hero after last move
  1138. {
  1139. ret = ret || (dst == h->visitablePos());
  1140. if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1141. {
  1142. throw cannotFulfillGoalException("Invalid path found!");
  1143. }
  1144. logAi->debug("Hero %s moved from %s to %s. Returning %d.", h->name, startHpos.toString(), h->visitablePos().toString(), ret);
  1145. }
  1146. return ret;
  1147. }
  1148. void AIGateway::buildStructure(const CGTownInstance * t, BuildingID building)
  1149. {
  1150. auto name = t->town->buildings.at(building)->Name();
  1151. logAi->debug("Player %d will build %s in town of %s at %s", ai->playerID, name, t->name, t->pos.toString());
  1152. cb->buildBuilding(t, building); //just do this;
  1153. }
  1154. void AIGateway::tryRealize(Goals::DigAtTile & g)
  1155. {
  1156. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1157. if(g.hero->diggingStatus() == EDiggingStatus::CAN_DIG)
  1158. {
  1159. cb->dig(g.hero.get());
  1160. }
  1161. else
  1162. {
  1163. throw cannotFulfillGoalException("A hero can't dig!\n");
  1164. }
  1165. }
  1166. void AIGateway::tryRealize(Goals::Trade & g) //trade
  1167. {
  1168. if(cb->getResourceAmount((Res::ERes)g.resID) >= g.value) //goal is already fulfilled. Why we need this check, anyway?
  1169. throw goalFulfilledException(sptr(g));
  1170. int accquiredResources = 0;
  1171. if(const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1172. {
  1173. if(const IMarket * m = IMarket::castFrom(obj, false))
  1174. {
  1175. auto freeRes = cb->getResourceAmount(); //trade only resources which are not reserved
  1176. for(auto it = Res::ResourceSet::nziterator(freeRes); it.valid(); it++)
  1177. {
  1178. auto res = it->resType;
  1179. if(res == g.resID) //sell any other resource
  1180. continue;
  1181. int toGive, toGet;
  1182. m->getOffer(res, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1183. toGive = static_cast<int>(toGive * (it->resVal / toGive)); //round down
  1184. //TODO trade only as much as needed
  1185. if (toGive) //don't try to sell 0 resources
  1186. {
  1187. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, res, g.resID, toGive);
  1188. accquiredResources = static_cast<int>(toGet * (it->resVal / toGive));
  1189. logAi->debug("Traded %d of %s for %d of %s at %s", toGive, res, accquiredResources, g.resID, obj->getObjectName());
  1190. }
  1191. if (cb->getResourceAmount((Res::ERes)g.resID) >= g.value)
  1192. throw goalFulfilledException(sptr(g)); //we traded all we needed
  1193. }
  1194. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1195. }
  1196. else
  1197. {
  1198. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1199. }
  1200. }
  1201. else
  1202. {
  1203. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1204. }
  1205. }
  1206. const CGTownInstance * AIGateway::findTownWithTavern() const
  1207. {
  1208. for(const CGTownInstance * t : cb->getTownsInfo())
  1209. if(townHasFreeTavern(t))
  1210. return t;
  1211. return nullptr;
  1212. }
  1213. void AIGateway::endTurn()
  1214. {
  1215. logAi->info("Player %d (%s) ends turn", playerID, playerID.getStr());
  1216. if(!status.haveTurn())
  1217. {
  1218. logAi->error("Not having turn at the end of turn???");
  1219. }
  1220. logAi->debug("Resources at the end of turn: %s", cb->getResourceAmount().toString());
  1221. do
  1222. {
  1223. cb->endTurn();
  1224. }
  1225. while(status.haveTurn()); //for some reasons, our request may fail -> stop requesting end of turn only after we've received a confirmation that it's over
  1226. logGlobal->info("Player %d (%s) ended turn", playerID, playerID.getStr());
  1227. }
  1228. void AIGateway::buildArmyIn(const CGTownInstance * t)
  1229. {
  1230. makePossibleUpgrades(t->visitingHero);
  1231. makePossibleUpgrades(t);
  1232. recruitCreatures(t, t->getUpperArmy());
  1233. moveCreaturesToHero(t);
  1234. }
  1235. void AIGateway::finish()
  1236. {
  1237. //we want to lock to avoid multiple threads from calling makingTurn->join() at same time
  1238. boost::lock_guard<boost::mutex> multipleCleanupGuard(turnInterruptionMutex);
  1239. if(makingTurn)
  1240. {
  1241. makingTurn->interrupt();
  1242. makingTurn->join();
  1243. makingTurn.reset();
  1244. }
  1245. }
  1246. void AIGateway::requestActionASAP(std::function<void()> whatToDo)
  1247. {
  1248. boost::thread newThread([this, whatToDo]()
  1249. {
  1250. setThreadName("AIGateway::requestActionASAP::whatToDo");
  1251. SET_GLOBAL_STATE(this);
  1252. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  1253. whatToDo();
  1254. });
  1255. }
  1256. void AIGateway::lostHero(HeroPtr h)
  1257. {
  1258. logAi->debug("I lost my hero %s. It's best to forget and move on.", h.name);
  1259. }
  1260. void AIGateway::answerQuery(QueryID queryID, int selection)
  1261. {
  1262. logAi->debug("I'll answer the query %d giving the choice %d", queryID, selection);
  1263. if(queryID != QueryID(-1))
  1264. {
  1265. cb->selectionMade(selection, queryID);
  1266. }
  1267. else
  1268. {
  1269. logAi->debug("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  1270. //do nothing
  1271. }
  1272. }
  1273. void AIGateway::requestSent(const CPackForServer * pack, int requestID)
  1274. {
  1275. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  1276. if(auto reply = dynamic_cast<const QueryReply *>(pack))
  1277. {
  1278. status.attemptedAnsweringQuery(reply->qid, requestID);
  1279. }
  1280. }
  1281. std::string AIGateway::getBattleAIName() const
  1282. {
  1283. if(settings["server"]["enemyAI"].getType() == JsonNode::JsonType::DATA_STRING)
  1284. return settings["server"]["enemyAI"].String();
  1285. else
  1286. return "BattleAI";
  1287. }
  1288. void AIGateway::validateObject(const CGObjectInstance * obj)
  1289. {
  1290. validateObject(obj->id);
  1291. }
  1292. void AIGateway::validateObject(ObjectIdRef obj)
  1293. {
  1294. if(!obj)
  1295. {
  1296. nullkiller->memory->removeFromMemory(obj);
  1297. }
  1298. }
  1299. AIStatus::AIStatus()
  1300. {
  1301. battle = NO_BATTLE;
  1302. havingTurn = false;
  1303. ongoingHeroMovement = false;
  1304. ongoingChannelProbing = false;
  1305. }
  1306. AIStatus::~AIStatus()
  1307. {
  1308. }
  1309. void AIStatus::setBattle(BattleState BS)
  1310. {
  1311. boost::unique_lock<boost::mutex> lock(mx);
  1312. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  1313. battle = BS;
  1314. cv.notify_all();
  1315. }
  1316. BattleState AIStatus::getBattle()
  1317. {
  1318. boost::unique_lock<boost::mutex> lock(mx);
  1319. return battle;
  1320. }
  1321. void AIStatus::addQuery(QueryID ID, std::string description)
  1322. {
  1323. if(ID == QueryID(-1))
  1324. {
  1325. logAi->debug("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID, description);
  1326. return;
  1327. }
  1328. assert(ID.getNum() >= 0);
  1329. boost::unique_lock<boost::mutex> lock(mx);
  1330. assert(!vstd::contains(remainingQueries, ID));
  1331. remainingQueries[ID] = description;
  1332. cv.notify_all();
  1333. logAi->debug("Adding query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  1334. }
  1335. void AIStatus::removeQuery(QueryID ID)
  1336. {
  1337. boost::unique_lock<boost::mutex> lock(mx);
  1338. assert(vstd::contains(remainingQueries, ID));
  1339. std::string description = remainingQueries[ID];
  1340. remainingQueries.erase(ID);
  1341. cv.notify_all();
  1342. logAi->debug("Removing query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  1343. }
  1344. int AIStatus::getQueriesCount()
  1345. {
  1346. boost::unique_lock<boost::mutex> lock(mx);
  1347. return static_cast<int>(remainingQueries.size());
  1348. }
  1349. void AIStatus::startedTurn()
  1350. {
  1351. boost::unique_lock<boost::mutex> lock(mx);
  1352. havingTurn = true;
  1353. cv.notify_all();
  1354. }
  1355. void AIStatus::madeTurn()
  1356. {
  1357. boost::unique_lock<boost::mutex> lock(mx);
  1358. havingTurn = false;
  1359. cv.notify_all();
  1360. }
  1361. void AIStatus::waitTillFree()
  1362. {
  1363. boost::unique_lock<boost::mutex> lock(mx);
  1364. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  1365. cv.timed_wait(lock, boost::posix_time::milliseconds(100));
  1366. }
  1367. bool AIStatus::haveTurn()
  1368. {
  1369. boost::unique_lock<boost::mutex> lock(mx);
  1370. return havingTurn;
  1371. }
  1372. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  1373. {
  1374. boost::unique_lock<boost::mutex> lock(mx);
  1375. assert(vstd::contains(remainingQueries, queryID));
  1376. std::string description = remainingQueries[queryID];
  1377. logAi->debug("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID, description, answerRequestID);
  1378. requestToQueryID[answerRequestID] = queryID;
  1379. }
  1380. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  1381. {
  1382. assert(vstd::contains(requestToQueryID, answerRequestID));
  1383. QueryID query = requestToQueryID[answerRequestID];
  1384. assert(vstd::contains(remainingQueries, query));
  1385. requestToQueryID.erase(answerRequestID);
  1386. if(result)
  1387. {
  1388. removeQuery(query);
  1389. }
  1390. else
  1391. {
  1392. logAi->error("Something went really wrong, failed to answer query %d : %s", query.getNum(), remainingQueries[query]);
  1393. //TODO safely retry
  1394. }
  1395. }
  1396. void AIStatus::heroVisit(const CGObjectInstance * obj, bool started)
  1397. {
  1398. boost::unique_lock<boost::mutex> lock(mx);
  1399. if(started)
  1400. {
  1401. objectsBeingVisited.push_back(obj);
  1402. }
  1403. else
  1404. {
  1405. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  1406. // causing visit to hero on the other side.
  1407. // However, we are guaranteed that start/end visit notification maintain stack order.
  1408. assert(!objectsBeingVisited.empty());
  1409. objectsBeingVisited.pop_back();
  1410. }
  1411. cv.notify_all();
  1412. }
  1413. void AIStatus::setMove(bool ongoing)
  1414. {
  1415. boost::unique_lock<boost::mutex> lock(mx);
  1416. ongoingHeroMovement = ongoing;
  1417. cv.notify_all();
  1418. }
  1419. void AIStatus::setChannelProbing(bool ongoing)
  1420. {
  1421. boost::unique_lock<boost::mutex> lock(mx);
  1422. ongoingChannelProbing = ongoing;
  1423. cv.notify_all();
  1424. }
  1425. bool AIStatus::channelProbing()
  1426. {
  1427. return ongoingChannelProbing;
  1428. }
  1429. }