VCAI.cpp 55 KB

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