VCAI.cpp 46 KB

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