VCAI.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877
  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 "ResourceManager.h"
  14. #include "BuildingManager.h"
  15. #include "Goals/Goals.h"
  16. #include "../../lib/ArtifactUtils.h"
  17. #include "../../lib/UnlockGuard.h"
  18. #include "../../lib/StartInfo.h"
  19. #include "../../lib/mapObjects/MapObjects.h"
  20. #include "../../lib/mapObjects/ObjectTemplate.h"
  21. #include "../../lib/CConfigHandler.h"
  22. #include "../../lib/IGameSettings.h"
  23. #include "../../lib/gameState/CGameState.h"
  24. #include "../../lib/bonuses/Limiters.h"
  25. #include "../../lib/bonuses/Updaters.h"
  26. #include "../../lib/bonuses/Propagators.h"
  27. #include "../../lib/entities/building/CBuilding.h"
  28. #include "../../lib/networkPacks/PacksForClient.h"
  29. #include "../../lib/networkPacks/PacksForClientBattle.h"
  30. #include "../../lib/networkPacks/PacksForServer.h"
  31. #include "../../lib/serializer/CTypeList.h"
  32. #include "AIhelper.h"
  33. extern FuzzyHelper * fh;
  34. const double SAFE_ATTACK_CONSTANT = 1.5;
  35. //one thread may be turn of AI and another will be handling a side effect for AI2
  36. thread_local CCallback * cb = nullptr;
  37. thread_local VCAI * ai = nullptr;
  38. //std::map<int, std::map<int, int> > HeroView::infosCount;
  39. //helper RAII to manage global ai/cb ptrs
  40. struct SetGlobalState
  41. {
  42. SetGlobalState(VCAI * AI)
  43. {
  44. assert(!ai);
  45. assert(!cb);
  46. ai = AI;
  47. cb = AI->myCb.get();
  48. }
  49. ~SetGlobalState()
  50. {
  51. //TODO: how to handle rm? shouldn't be called after ai is destroyed, hopefully
  52. //TODO: to ensure that, make rm unique_ptr
  53. ai = nullptr;
  54. cb = nullptr;
  55. }
  56. };
  57. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai)
  58. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  59. #define MAKING_TURN SET_GLOBAL_STATE(this)
  60. VCAI::VCAI()
  61. {
  62. LOG_TRACE(logAi);
  63. makingTurn = nullptr;
  64. destinationTeleport = ObjectInstanceID();
  65. destinationTeleportPos = int3(-1);
  66. ah = new AIhelper();
  67. ah->setAI(this);
  68. }
  69. VCAI::~VCAI()
  70. {
  71. delete ah;
  72. LOG_TRACE(logAi);
  73. finish();
  74. }
  75. void VCAI::availableCreaturesChanged(const CGDwelling * town)
  76. {
  77. LOG_TRACE(logAi);
  78. NET_EVENT_HANDLER;
  79. }
  80. void VCAI::heroMoved(const TryMoveHero & details, bool verbose)
  81. {
  82. LOG_TRACE(logAi);
  83. NET_EVENT_HANDLER;
  84. //enemy hero may have left visible area
  85. validateObject(details.id);
  86. auto hero = cb->getHero(details.id);
  87. const int3 from = hero ? hero->convertToVisitablePos(details.start) : (details.start - int3(0,1,0));
  88. const int3 to = hero ? hero->convertToVisitablePos(details.end) : (details.end - int3(0,1,0));
  89. const CGObjectInstance * o1 = vstd::frontOrNull(cb->getVisitableObjs(from, verbose));
  90. const CGObjectInstance * o2 = vstd::frontOrNull(cb->getVisitableObjs(to, verbose));
  91. if(details.result == TryMoveHero::TELEPORTATION)
  92. {
  93. auto t1 = dynamic_cast<const CGTeleport *>(o1);
  94. auto t2 = dynamic_cast<const CGTeleport *>(o2);
  95. if(t1 && t2)
  96. {
  97. if(cb->isTeleportChannelBidirectional(t1->channel))
  98. {
  99. 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
  100. {
  101. knownSubterraneanGates[o1] = o2;
  102. knownSubterraneanGates[o2] = o1;
  103. logAi->debug("Found a pair of subterranean gates between %s and %s!", from.toString(), to.toString());
  104. }
  105. }
  106. }
  107. //FIXME: teleports are not correctly visited
  108. unreserveObject(hero, t1);
  109. unreserveObject(hero, t2);
  110. }
  111. else if(details.result == TryMoveHero::EMBARK && hero)
  112. {
  113. //make sure AI not attempt to visit used boat
  114. validateObject(hero->boat);
  115. }
  116. else if(details.result == TryMoveHero::DISEMBARK && o1)
  117. {
  118. auto boat = dynamic_cast<const CGBoat *>(o1);
  119. if(boat)
  120. addVisitableObj(boat);
  121. }
  122. }
  123. void VCAI::heroInGarrisonChange(const CGTownInstance * town)
  124. {
  125. LOG_TRACE(logAi);
  126. NET_EVENT_HANDLER;
  127. }
  128. void VCAI::centerView(int3 pos, int focusTime)
  129. {
  130. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  131. NET_EVENT_HANDLER;
  132. }
  133. void VCAI::artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst)
  134. {
  135. LOG_TRACE(logAi);
  136. NET_EVENT_HANDLER;
  137. }
  138. void VCAI::artifactAssembled(const ArtifactLocation & al)
  139. {
  140. LOG_TRACE(logAi);
  141. NET_EVENT_HANDLER;
  142. }
  143. void VCAI::showTavernWindow(const CGObjectInstance * object, const CGHeroInstance * visitor, QueryID queryID)
  144. {
  145. LOG_TRACE(logAi);
  146. NET_EVENT_HANDLER;
  147. status.addQuery(queryID, "TavernWindow");
  148. requestActionASAP([=](){ answerQuery(queryID, 0); });
  149. }
  150. void VCAI::showThievesGuildWindow(const CGObjectInstance * obj)
  151. {
  152. LOG_TRACE(logAi);
  153. NET_EVENT_HANDLER;
  154. }
  155. void VCAI::playerBlocked(int reason, bool start)
  156. {
  157. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  158. NET_EVENT_HANDLER;
  159. if(start && reason == PlayerBlocked::UPCOMING_BATTLE)
  160. status.setBattle(UPCOMING_BATTLE);
  161. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  162. status.setMove(start);
  163. }
  164. void VCAI::showPuzzleMap()
  165. {
  166. LOG_TRACE(logAi);
  167. NET_EVENT_HANDLER;
  168. }
  169. void VCAI::showShipyardDialog(const IShipyard * obj)
  170. {
  171. LOG_TRACE(logAi);
  172. NET_EVENT_HANDLER;
  173. }
  174. void VCAI::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
  175. {
  176. LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult.messageToSelf.toString());
  177. NET_EVENT_HANDLER;
  178. logAi->debug("Player %d (%s): I heard that player %d (%s) %s.", playerID, playerID.toString(), player, player.toString(), (victoryLossCheckResult.victory() ? "won" : "lost"));
  179. if(player == playerID)
  180. {
  181. if(victoryLossCheckResult.victory())
  182. {
  183. logAi->debug("VCAI: I won! Incredible!");
  184. logAi->debug("Turn nr %d", myCb->getDate());
  185. }
  186. else
  187. {
  188. logAi->debug("VCAI: Player %d (%s) lost. It's me. What a disappointment! :(", player, player.toString());
  189. }
  190. finish();
  191. }
  192. }
  193. void VCAI::artifactPut(const ArtifactLocation & al)
  194. {
  195. LOG_TRACE(logAi);
  196. NET_EVENT_HANDLER;
  197. }
  198. void VCAI::artifactRemoved(const ArtifactLocation & al)
  199. {
  200. LOG_TRACE(logAi);
  201. NET_EVENT_HANDLER;
  202. }
  203. void VCAI::artifactDisassembled(const ArtifactLocation & al)
  204. {
  205. LOG_TRACE(logAi);
  206. NET_EVENT_HANDLER;
  207. }
  208. void VCAI::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  209. {
  210. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->getObjectName() : std::string("n/a")));
  211. NET_EVENT_HANDLER;
  212. if(start && visitedObj) //we can end visit with null object, anyway
  213. {
  214. markObjectVisited(visitedObj);
  215. unreserveObject(visitor, visitedObj);
  216. completeGoal(sptr(Goals::VisitObj(visitedObj->id.getNum()).sethero(visitor))); //we don't need to visit it anymore
  217. //TODO: what if we visited one-time visitable object that was reserved by another hero (shouldn't, but..)
  218. if (visitedObj->ID == Obj::HERO)
  219. {
  220. visitedHeroes[visitor].insert(HeroPtr(dynamic_cast<const CGHeroInstance *>(visitedObj)));
  221. }
  222. }
  223. status.heroVisit(visitedObj, start);
  224. }
  225. void VCAI::availableArtifactsChanged(const CGBlackMarket * bm)
  226. {
  227. LOG_TRACE(logAi);
  228. NET_EVENT_HANDLER;
  229. }
  230. void VCAI::heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town)
  231. {
  232. LOG_TRACE(logAi);
  233. NET_EVENT_HANDLER;
  234. //buildArmyIn(town);
  235. //moveCreaturesToHero(town);
  236. }
  237. void VCAI::tileHidden(const std::unordered_set<int3> & pos)
  238. {
  239. LOG_TRACE(logAi);
  240. NET_EVENT_HANDLER;
  241. validateVisitableObjs();
  242. clearPathsInfo();
  243. }
  244. void VCAI::tileRevealed(const std::unordered_set<int3> & pos)
  245. {
  246. LOG_TRACE(logAi);
  247. NET_EVENT_HANDLER;
  248. for(int3 tile : pos)
  249. {
  250. for(const CGObjectInstance * obj : myCb->getVisitableObjs(tile))
  251. addVisitableObj(obj);
  252. }
  253. clearPathsInfo();
  254. }
  255. void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  256. {
  257. LOG_TRACE(logAi);
  258. NET_EVENT_HANDLER;
  259. auto firstHero = cb->getHero(hero1);
  260. auto secondHero = cb->getHero(hero2);
  261. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s (%d) and %s (%d)") % firstHero->getNameTranslated() % firstHero->tempOwner % secondHero->getNameTranslated() % secondHero->tempOwner));
  262. requestActionASAP([=]()
  263. {
  264. float goalpriority1 = 0;
  265. float goalpriority2 = 0;
  266. auto firstGoal = getGoal(firstHero);
  267. if(firstGoal->goalType == Goals::GATHER_ARMY)
  268. goalpriority1 = firstGoal->priority;
  269. auto secondGoal = getGoal(secondHero);
  270. if(secondGoal->goalType == Goals::GATHER_ARMY)
  271. goalpriority2 = secondGoal->priority;
  272. auto transferFrom2to1 = [this](const CGHeroInstance * h1, const CGHeroInstance * h2) -> void
  273. {
  274. this->pickBestCreatures(h1, h2);
  275. this->pickBestArtifacts(h1, h2);
  276. };
  277. //Do not attempt army or artifacts exchange if we visited ally player
  278. //Visits can still be useful if hero have skills like Scholar
  279. if(firstHero->tempOwner != secondHero->tempOwner)
  280. {
  281. logAi->debug("Heroes owned by different players. Do not exchange army or artifacts.");
  282. }
  283. else if(goalpriority1 > goalpriority2)
  284. {
  285. transferFrom2to1(firstHero, secondHero);
  286. }
  287. else if(goalpriority1 < goalpriority2)
  288. {
  289. transferFrom2to1(secondHero, firstHero);
  290. }
  291. else //regular criteria
  292. {
  293. if(firstHero->getFightingStrength() > secondHero->getFightingStrength() && ah->canGetArmy(firstHero, secondHero))
  294. transferFrom2to1(firstHero, secondHero);
  295. else if(ah->canGetArmy(secondHero, firstHero))
  296. transferFrom2to1(secondHero, firstHero);
  297. }
  298. completeGoal(sptr(Goals::VisitHero(firstHero->id.getNum()))); //TODO: what if we were visited by other hero in the meantime?
  299. completeGoal(sptr(Goals::VisitHero(secondHero->id.getNum())));
  300. answerQuery(query, 0);
  301. });
  302. }
  303. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, PrimarySkill which, si64 val)
  304. {
  305. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", static_cast<int>(which) % val);
  306. NET_EVENT_HANDLER;
  307. }
  308. void VCAI::showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level, QueryID queryID)
  309. {
  310. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  311. NET_EVENT_HANDLER;
  312. status.addQuery(queryID, "RecruitmentDialog");
  313. requestActionASAP([=](){
  314. recruitCreatures(dwelling, dst);
  315. checkHeroArmy(dynamic_cast<const CGHeroInstance*>(dst));
  316. answerQuery(queryID, 0);
  317. });
  318. }
  319. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  320. {
  321. LOG_TRACE(logAi);
  322. NET_EVENT_HANDLER;
  323. }
  324. void VCAI::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  325. {
  326. LOG_TRACE(logAi);
  327. NET_EVENT_HANDLER;
  328. }
  329. void VCAI::newObject(const CGObjectInstance * obj)
  330. {
  331. LOG_TRACE(logAi);
  332. NET_EVENT_HANDLER;
  333. if(obj->isVisitable())
  334. addVisitableObj(obj);
  335. }
  336. //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
  337. //see: RemoveObject::applyFirstCl, to keep AI "not cheating" do not use advantage of this and use this function just to prevent crashes
  338. void VCAI::objectRemoved(const CGObjectInstance * obj, const PlayerColor & initiator)
  339. {
  340. LOG_TRACE(logAi);
  341. NET_EVENT_HANDLER;
  342. vstd::erase_if_present(visitableObjs, obj);
  343. vstd::erase_if_present(alreadyVisited, obj);
  344. for(auto h : cb->getHeroesInfo())
  345. unreserveObject(h, obj);
  346. std::function<bool(const Goals::TSubgoal &)> checkRemovalValidity = [&](const Goals::TSubgoal & x) -> bool
  347. {
  348. if((x->goalType == Goals::VISIT_OBJ) && (x->objid == obj->id.getNum()))
  349. return true;
  350. else if(x->parent && checkRemovalValidity(x->parent)) //repeat this lambda check recursively on parent goal
  351. return true;
  352. else
  353. return false;
  354. };
  355. //clear VCAI / main loop caches
  356. vstd::erase_if(lockedHeroes, [&](const std::pair<HeroPtr, Goals::TSubgoal> & x) -> bool
  357. {
  358. return checkRemovalValidity(x.second);
  359. });
  360. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  361. {
  362. return checkRemovalValidity(x.first);
  363. });
  364. vstd::erase_if(basicGoals, checkRemovalValidity);
  365. vstd::erase_if(goalsToAdd, checkRemovalValidity);
  366. vstd::erase_if(goalsToRemove, checkRemovalValidity);
  367. for(auto goal : ultimateGoalsFromBasic)
  368. vstd::erase_if(goal.second, checkRemovalValidity);
  369. //clear resource manager goal cache
  370. ah->removeOutdatedObjectives(checkRemovalValidity);
  371. //TODO: Find better way to handle hero boat removal
  372. if(auto hero = dynamic_cast<const CGHeroInstance *>(obj))
  373. {
  374. if(hero->boat)
  375. {
  376. vstd::erase_if_present(visitableObjs, hero->boat);
  377. vstd::erase_if_present(alreadyVisited, hero->boat);
  378. for(auto h : cb->getHeroesInfo())
  379. unreserveObject(h, hero->boat);
  380. }
  381. }
  382. //TODO
  383. //there are other places where CGObjectinstance ptrs are stored...
  384. //
  385. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  386. {
  387. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  388. }
  389. }
  390. void VCAI::showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor)
  391. {
  392. LOG_TRACE(logAi);
  393. NET_EVENT_HANDLER;
  394. requestActionASAP([=]()
  395. {
  396. makePossibleUpgrades(visitor);
  397. });
  398. }
  399. void VCAI::playerBonusChanged(const Bonus & bonus, bool gain)
  400. {
  401. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  402. NET_EVENT_HANDLER;
  403. }
  404. void VCAI::heroCreated(const CGHeroInstance * h)
  405. {
  406. LOG_TRACE(logAi);
  407. if(h->visitedTown)
  408. townVisitsThisWeek[HeroPtr(h)].insert(h->visitedTown);
  409. NET_EVENT_HANDLER;
  410. }
  411. void VCAI::advmapSpellCast(const CGHeroInstance * caster, SpellID spellID)
  412. {
  413. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  414. NET_EVENT_HANDLER;
  415. }
  416. void VCAI::showInfoDialog(EInfoWindowMode type, const std::string & text, const std::vector<Component> & components, int soundID)
  417. {
  418. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  419. NET_EVENT_HANDLER;
  420. }
  421. void VCAI::requestRealized(PackageApplied * pa)
  422. {
  423. LOG_TRACE(logAi);
  424. NET_EVENT_HANDLER;
  425. if(status.haveTurn())
  426. {
  427. if(pa->packType == CTypeList::getInstance().getTypeID<EndTurn>(nullptr))
  428. {
  429. if(pa->result)
  430. status.madeTurn();
  431. }
  432. }
  433. if(pa->packType == CTypeList::getInstance().getTypeID<QueryReply>(nullptr))
  434. {
  435. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  436. }
  437. }
  438. void VCAI::receivedResource()
  439. {
  440. LOG_TRACE(logAi);
  441. NET_EVENT_HANDLER;
  442. }
  443. void VCAI::showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
  444. {
  445. LOG_TRACE(logAi);
  446. NET_EVENT_HANDLER;
  447. status.addQuery(queryID, "UniversityWindow");
  448. requestActionASAP([=](){ answerQuery(queryID, 0); });
  449. }
  450. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  451. {
  452. LOG_TRACE(logAi);
  453. NET_EVENT_HANDLER;
  454. }
  455. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  456. {
  457. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  458. NET_EVENT_HANDLER;
  459. }
  460. void VCAI::battleResultsApplied()
  461. {
  462. LOG_TRACE(logAi);
  463. NET_EVENT_HANDLER;
  464. assert(status.getBattle() == ENDING_BATTLE);
  465. status.setBattle(NO_BATTLE);
  466. }
  467. void VCAI::beforeObjectPropertyChanged(const SetObjectProperty * sop)
  468. {
  469. }
  470. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  471. {
  472. LOG_TRACE(logAi);
  473. NET_EVENT_HANDLER;
  474. if(sop->what == ObjProperty::OWNER)
  475. {
  476. if(myCb->getPlayerRelations(playerID, sop->identifier.as<PlayerColor>()) == PlayerRelations::ENEMIES)
  477. {
  478. //we want to visit objects owned by oppponents
  479. auto obj = myCb->getObj(sop->id, false);
  480. if(obj)
  481. {
  482. addVisitableObj(obj); // TODO: Remove once save compatibility broken. In past owned objects were removed from this set
  483. vstd::erase_if_present(alreadyVisited, obj);
  484. }
  485. }
  486. }
  487. }
  488. void VCAI::buildChanged(const CGTownInstance * town, BuildingID buildingID, int what)
  489. {
  490. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  491. NET_EVENT_HANDLER;
  492. if(town->getOwner() == playerID && what == 1) //built
  493. completeGoal(sptr(Goals::BuildThis(buildingID, town)));
  494. }
  495. void VCAI::heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain)
  496. {
  497. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  498. NET_EVENT_HANDLER;
  499. }
  500. void VCAI::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
  501. {
  502. LOG_TRACE(logAi);
  503. NET_EVENT_HANDLER;
  504. status.addQuery(queryID, "MarketWindow");
  505. requestActionASAP([=](){ answerQuery(queryID, 0); });
  506. }
  507. void VCAI::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain)
  508. {
  509. //TODO: AI support for ViewXXX spell
  510. LOG_TRACE(logAi);
  511. NET_EVENT_HANDLER;
  512. }
  513. void VCAI::initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
  514. {
  515. LOG_TRACE(logAi);
  516. env = ENV;
  517. myCb = CB;
  518. cbc = CB;
  519. ah->init(CB.get());
  520. NET_EVENT_HANDLER; //sets ah->rm->cb
  521. playerID = *myCb->getPlayerID();
  522. myCb->waitTillRealize = true;
  523. myCb->unlockGsWhenWaiting = true;
  524. if(!fh)
  525. fh = new FuzzyHelper();
  526. retrieveVisitableObjs();
  527. }
  528. void VCAI::yourTurn(QueryID queryID)
  529. {
  530. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  531. NET_EVENT_HANDLER;
  532. status.addQuery(queryID, "YourTurn");
  533. requestActionASAP([=](){ answerQuery(queryID, 0); });
  534. status.startedTurn();
  535. makingTurn = std::make_unique<boost::thread>(&VCAI::makeTurn, this);
  536. }
  537. void VCAI::heroGotLevel(const CGHeroInstance * hero, PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
  538. {
  539. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  540. NET_EVENT_HANDLER;
  541. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->getNameTranslated() % hero->level));
  542. requestActionASAP([=](){ answerQuery(queryID, 0); });
  543. }
  544. void VCAI::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  545. {
  546. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  547. NET_EVENT_HANDLER;
  548. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  549. requestActionASAP([=](){ answerQuery(queryID, 0); });
  550. }
  551. void VCAI::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel, bool safeToAutoaccept)
  552. {
  553. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i', autoaccept '%i'", text % askID % soundID % selection % cancel % safeToAutoaccept);
  554. NET_EVENT_HANDLER;
  555. int sel = 0;
  556. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  557. % components.size() % text));
  558. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  559. sel = static_cast<int>(components.size());
  560. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  561. sel = 1;
  562. requestActionASAP([=]()
  563. {
  564. answerQuery(askID, sel);
  565. });
  566. }
  567. void VCAI::showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  568. {
  569. // LOG_TRACE_PARAMS(logAi, "askID '%i', exits '%s'", askID % exits);
  570. NET_EVENT_HANDLER;
  571. status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits")
  572. % exits.size()));
  573. int chosenExit = -1;
  574. if(impassable)
  575. {
  576. knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
  577. }
  578. else if(destinationTeleport != ObjectInstanceID() && destinationTeleportPos.valid())
  579. {
  580. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  581. if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  582. chosenExit = vstd::find_pos(exits, neededExit);
  583. }
  584. for(auto exit : exits)
  585. {
  586. if(status.channelProbing() && exit.first == destinationTeleport)
  587. {
  588. chosenExit = vstd::find_pos(exits, exit);
  589. break;
  590. }
  591. else
  592. {
  593. // TODO: Implement checking if visiting that teleport will uncovert any FoW
  594. // So far this is the best option to handle decision about probing
  595. auto obj = cb->getObj(exit.first, false);
  596. if(obj == nullptr && !vstd::contains(teleportChannelProbingList, exit.first))
  597. {
  598. if(exit.first != destinationTeleport)
  599. teleportChannelProbingList.push_back(exit.first);
  600. }
  601. }
  602. }
  603. requestActionASAP([=]()
  604. {
  605. answerQuery(askID, chosenExit);
  606. });
  607. }
  608. void VCAI::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
  609. {
  610. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  611. NET_EVENT_HANDLER;
  612. std::string s1 = up ? up->nodeName() : "NONE";
  613. std::string s2 = down ? down->nodeName() : "NONE";
  614. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  615. //you can't request action from action-response thread
  616. requestActionASAP([=]()
  617. {
  618. if(removableUnits && !cb->getStartInfo()->isRestorationOfErathiaCampaign())
  619. pickBestCreatures(down, up);
  620. answerQuery(queryID, 0);
  621. });
  622. }
  623. void VCAI::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  624. {
  625. NET_EVENT_HANDLER;
  626. status.addQuery(askID, "Map object select query");
  627. requestActionASAP([=](){ answerQuery(askID, selectedObject.getNum()); });
  628. }
  629. void makePossibleUpgrades(const CArmedInstance * obj)
  630. {
  631. if(!obj)
  632. return;
  633. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  634. {
  635. if(const CStackInstance * s = obj->getStackPtr(SlotID(i)))
  636. {
  637. UpgradeInfo ui;
  638. cb->fillUpgradeInfo(obj, SlotID(i), ui);
  639. if(ui.oldID != CreatureID::NONE && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  640. {
  641. cb->upgradeCreature(obj, SlotID(i), ui.newID[0]);
  642. }
  643. }
  644. }
  645. }
  646. void VCAI::makeTurn()
  647. {
  648. MAKING_TURN;
  649. auto day = cb->getDate(Date::DAY);
  650. logAi->info("Player %d (%s) starting turn, day %d", playerID, playerID.toString(), day);
  651. boost::shared_lock gsLock(CGameState::mutex);
  652. setThreadName("VCAI::makeTurn");
  653. switch(cb->getDate(Date::DAY_OF_WEEK))
  654. {
  655. case 1:
  656. {
  657. townVisitsThisWeek.clear();
  658. std::vector<const CGObjectInstance *> objs;
  659. retrieveVisitableObjs(objs, true);
  660. for(const CGObjectInstance * obj : objs)
  661. {
  662. if(isWeeklyRevisitable(obj))
  663. {
  664. addVisitableObj(obj);
  665. vstd::erase_if_present(alreadyVisited, obj);
  666. }
  667. }
  668. break;
  669. }
  670. }
  671. markHeroAbleToExplore(primaryHero());
  672. visitedHeroes.clear();
  673. try
  674. {
  675. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  676. for (const CGTownInstance * t : cb->getTownsInfo())
  677. moveCreaturesToHero(t);
  678. mainLoop();
  679. /*Below function is also responsible for hero movement via internal wander function. By design it is separate logic for heroes that have nothing to do.
  680. Heroes that were not picked by striveToGoal(sptr(Goals::Win())); recently (so they do not have new goals and cannot continue/reevaluate previously locked goals) will do logic in wander().*/
  681. performTypicalActions();
  682. //for debug purpose
  683. for (auto h : cb->getHeroesInfo())
  684. {
  685. if (h->movementPointsRemaining())
  686. logAi->info("Hero %s has %d MP left", h->getNameTranslated(), h->movementPointsRemaining());
  687. }
  688. }
  689. catch (boost::thread_interrupted & e)
  690. {
  691. (void)e;
  692. logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
  693. return;
  694. }
  695. catch (std::exception & e)
  696. {
  697. logAi->debug("Making turn thread has caught an exception: %s", e.what());
  698. }
  699. endTurn();
  700. }
  701. std::vector<HeroPtr> VCAI::getMyHeroes() const
  702. {
  703. std::vector<HeroPtr> ret;
  704. for(auto h : cb->getHeroesInfo())
  705. {
  706. ret.push_back(h);
  707. }
  708. return ret;
  709. }
  710. void VCAI::mainLoop()
  711. {
  712. std::vector<Goals::TSubgoal> elementarGoals; //no duplicates allowed (operator ==)
  713. basicGoals.clear();
  714. validateVisitableObjs();
  715. //get all potential and saved goals
  716. //TODO: not lose
  717. basicGoals.push_back(sptr(Goals::Win()));
  718. for (auto goalPair : lockedHeroes)
  719. {
  720. fh->setPriority(goalPair.second); //re-evaluate, as heroes moved in the meantime
  721. basicGoals.push_back(goalPair.second);
  722. }
  723. if (ah->hasTasksLeft())
  724. basicGoals.push_back(ah->whatToDo());
  725. for (auto quest : myCb->getMyQuests())
  726. {
  727. basicGoals.push_back(sptr(Goals::CompleteQuest(quest)));
  728. }
  729. basicGoals.push_back(sptr(Goals::Build()));
  730. invalidPathHeroes.clear();
  731. for (int pass = 0; pass< 30 && basicGoals.size(); pass++)
  732. {
  733. vstd::removeDuplicates(basicGoals); //TODO: container which does this automagically without has would be nice
  734. goalsToAdd.clear();
  735. goalsToRemove.clear();
  736. elementarGoals.clear();
  737. ultimateGoalsFromBasic.clear();
  738. ah->updatePaths(getMyHeroes());
  739. logAi->debug("Main loop: decomposing %i basic goals", basicGoals.size());
  740. for (auto basicGoal : basicGoals)
  741. {
  742. logAi->debug("Main loop: decomposing basic goal %s", basicGoal->name());
  743. auto goalToDecompose = basicGoal;
  744. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  745. int maxAbstractGoals = 10;
  746. while (!elementarGoal->isElementar && maxAbstractGoals)
  747. {
  748. try
  749. {
  750. elementarGoal = decomposeGoal(goalToDecompose);
  751. }
  752. catch (goalFulfilledException & e)
  753. {
  754. //it is impossible to continue some goals (like exploration, for example)
  755. //complete abstract goal for now, but maybe main goal finds another path
  756. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  757. completeGoal(e.goal); //put in goalsToRemove
  758. break;
  759. }
  760. catch(cannotFulfillGoalException & e)
  761. {
  762. //it is impossible to continue some goals (like exploration, for example)
  763. //complete abstract goal for now, but maybe main goal finds another path
  764. goalsToRemove.push_back(basicGoal);
  765. logAi->debug("Goal %s decomposition failed: %s", goalToDecompose->name(), e.what());
  766. break;
  767. }
  768. catch (std::exception & e) //decomposition failed, which means we can't decompose entire tree
  769. {
  770. goalsToRemove.push_back(basicGoal);
  771. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  772. break;
  773. }
  774. if (elementarGoal->isAbstract) //we can decompose it further
  775. {
  776. goalsToAdd.push_back(elementarGoal);
  777. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  778. goalToDecompose = elementarGoal;
  779. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  780. maxAbstractGoals--;
  781. }
  782. else if (elementarGoal->isElementar) //should be
  783. {
  784. logAi->debug("Found elementar goal %s", elementarGoal->name());
  785. elementarGoals.push_back(elementarGoal);
  786. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  787. break;
  788. }
  789. else //should never be here
  790. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  791. }
  792. }
  793. logAi->trace("Main loop: selecting best elementar goal");
  794. //now choose one elementar goal to realize
  795. Goals::TGoalVec possibleGoals(elementarGoals.begin(), elementarGoals.end()); //copy to vector
  796. Goals::TSubgoal goalToRealize = sptr(Goals::Invalid());
  797. while (possibleGoals.size())
  798. {
  799. //allow assign goals to heroes with 0 movement, but don't realize them
  800. //maybe there are better ones left
  801. auto bestGoal = fh->chooseSolution(possibleGoals);
  802. if (bestGoal->hero) //lock this hero to fulfill goal
  803. {
  804. setGoal(bestGoal->hero, bestGoal);
  805. if (!bestGoal->hero->movementPointsRemaining() || vstd::contains(invalidPathHeroes, bestGoal->hero))
  806. {
  807. if (!vstd::erase_if_present(possibleGoals, bestGoal))
  808. {
  809. logAi->error("erase_if_preset failed? Something very wrong!");
  810. break;
  811. }
  812. continue; //chose next from the list
  813. }
  814. }
  815. goalToRealize = bestGoal; //we found our goal to execute
  816. break;
  817. }
  818. //realize best goal
  819. if (!goalToRealize->invalid())
  820. {
  821. logAi->debug("Trying to realize %s (value %2.3f)", goalToRealize->name(), goalToRealize->priority);
  822. try
  823. {
  824. boost::this_thread::interruption_point();
  825. goalToRealize->accept(this); //visitor pattern
  826. boost::this_thread::interruption_point();
  827. }
  828. catch (boost::thread_interrupted & e)
  829. {
  830. (void)e;
  831. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  832. throw; //rethrow, we want to truly end this thread
  833. }
  834. catch (goalFulfilledException & e)
  835. {
  836. //the sub-goal was completed successfully
  837. completeGoal(e.goal);
  838. //local goal was also completed?
  839. completeGoal(goalToRealize);
  840. // remove abstract visit tile if we completed the elementar one
  841. vstd::erase_if_present(goalsToAdd, goalToRealize);
  842. }
  843. catch (std::exception & e)
  844. {
  845. logAi->debug("Failed to realize subgoal of type %s, I will stop.", goalToRealize->name());
  846. logAi->debug("The error message was: %s", e.what());
  847. //erase base goal if we failed to execute decomposed goal
  848. for (auto basicGoal : ultimateGoalsFromBasic[goalToRealize])
  849. goalsToRemove.push_back(basicGoal);
  850. // sometimes resource manager contains an elementar goal which is not able to execute anymore and just fails each turn.
  851. ai->ah->notifyGoalCompleted(goalToRealize);
  852. //we failed to realize best goal, but maybe others are still possible?
  853. }
  854. //remove goals we couldn't decompose
  855. for (auto goal : goalsToRemove)
  856. vstd::erase_if_present(basicGoals, goal);
  857. //add abstract goals
  858. boost::sort(goalsToAdd, [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  859. {
  860. return lhs->priority > rhs->priority; //highest priority at the beginning
  861. });
  862. //max number of goals = 10
  863. int i = 0;
  864. while (basicGoals.size() < 10 && goalsToAdd.size() > i)
  865. {
  866. if (!vstd::contains(basicGoals, goalsToAdd[i])) //don't add duplicates
  867. basicGoals.push_back(goalsToAdd[i]);
  868. i++;
  869. }
  870. }
  871. else //no elementar goals possible
  872. {
  873. logAi->debug("Goal decomposition exhausted");
  874. break;
  875. }
  876. }
  877. }
  878. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  879. {
  880. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->getNameTranslated() % obj->getObjectName() % obj->anchorPos().toString());
  881. switch(obj->ID)
  882. {
  883. case Obj::TOWN:
  884. moveCreaturesToHero(dynamic_cast<const CGTownInstance *>(obj));
  885. if(h->visitedTown) //we are inside, not just attacking
  886. {
  887. townVisitsThisWeek[h].insert(h->visitedTown);
  888. if(!h->hasSpellbook() && ah->freeGold() >= GameConstants::SPELLBOOK_GOLD_COST)
  889. {
  890. if(h->visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  891. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  892. }
  893. }
  894. break;
  895. }
  896. completeGoal(sptr(Goals::VisitObj(obj->id.getNum()).sethero(h)));
  897. }
  898. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  899. {
  900. if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
  901. {
  902. pickBestCreatures(t->visitingHero, t);
  903. }
  904. }
  905. void VCAI::pickBestCreatures(const CArmedInstance * destinationArmy, const CArmedInstance * source)
  906. {
  907. const CArmedInstance * armies[] = {destinationArmy, source};
  908. auto bestArmy = ah->getSortedSlots(destinationArmy, source);
  909. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  910. 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
  911. {
  912. const CCreature * targetCreature = bestArmy[i.getNum()].creature;
  913. for(auto armyPtr : armies)
  914. {
  915. for(SlotID j = SlotID(0); j.validSlot(); j.advance(1))
  916. {
  917. if(armyPtr->getCreature(j) == targetCreature && (i != j || armyPtr != destinationArmy)) //it's a searched creature not in dst SLOT
  918. {
  919. //can't take away last creature without split. generate a new stack with 1 creature which is weak but fast
  920. if(armyPtr == source
  921. && source->needsLastStack()
  922. && source->stacksCount() == 1
  923. && (!destinationArmy->hasStackAtSlot(i) || destinationArmy->getCreature(i) == targetCreature))
  924. {
  925. auto weakest = ah->getWeakestCreature(bestArmy);
  926. if(weakest->creature == targetCreature)
  927. {
  928. if(1 == source->getStackCount(j))
  929. break;
  930. // move all except 1 of weakest creature from source to destination
  931. cb->splitStack(
  932. source,
  933. destinationArmy,
  934. j,
  935. destinationArmy->getSlotFor(targetCreature),
  936. destinationArmy->getStackCount(i) + source->getStackCount(j) - 1);
  937. break;
  938. }
  939. else
  940. {
  941. // Source last stack is not weakest. Move 1 of weakest creature from destination to source
  942. cb->splitStack(
  943. destinationArmy,
  944. source,
  945. destinationArmy->getSlotFor(weakest->creature),
  946. source->getFreeSlot(),
  947. 1);
  948. }
  949. }
  950. cb->mergeOrSwapStacks(armyPtr, destinationArmy, j, i);
  951. }
  952. }
  953. }
  954. }
  955. //TODO - having now strongest possible army, we may want to think about arranging stacks
  956. auto hero = dynamic_cast<const CGHeroInstance *>(destinationArmy);
  957. if(hero)
  958. checkHeroArmy(hero);
  959. }
  960. void VCAI::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other)
  961. {
  962. auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void
  963. {
  964. bool changeMade = false;
  965. do
  966. {
  967. changeMade = false;
  968. //we collect gear always in same order
  969. std::vector<ArtifactLocation> allArtifacts;
  970. if(giveStuffToFirstHero)
  971. {
  972. for(auto p : h->artifactsWorn)
  973. {
  974. if(p.second.artifact)
  975. allArtifacts.push_back(ArtifactLocation(h->id, p.first));
  976. }
  977. }
  978. for(auto slot : h->artifactsInBackpack)
  979. allArtifacts.push_back(ArtifactLocation(h->id, h->getArtPos(slot.artifact)));
  980. if(otherh)
  981. {
  982. for(auto p : otherh->artifactsWorn)
  983. {
  984. if(p.second.artifact)
  985. allArtifacts.push_back(ArtifactLocation(otherh->id, p.first));
  986. }
  987. for(auto slot : otherh->artifactsInBackpack)
  988. allArtifacts.push_back(ArtifactLocation(otherh->id, otherh->getArtPos(slot.artifact)));
  989. }
  990. //we give stuff to one hero or another, depending on giveStuffToFirstHero
  991. const CGHeroInstance * target = nullptr;
  992. if(giveStuffToFirstHero || !otherh)
  993. target = h;
  994. else
  995. target = otherh;
  996. for(auto location : allArtifacts)
  997. {
  998. if(location.slot == ArtifactPosition::MACH4 || location.slot == ArtifactPosition::SPELLBOOK)
  999. continue; // don't attempt to move catapult and spellbook
  1000. if(location.artHolder == target->id && ArtifactUtils::isSlotEquipment(location.slot))
  1001. continue; //don't reequip artifact we already wear
  1002. auto s = cb->getHero(location.artHolder)->getSlot(location.slot);
  1003. if(!s || s->locked) //we can't move locks
  1004. continue;
  1005. auto artifact = s->artifact;
  1006. if(!artifact)
  1007. continue;
  1008. //FIXME: why are the above possible to be null?
  1009. bool emptySlotFound = false;
  1010. for(auto slot : artifact->getType()->getPossibleSlots().at(target->bearerType()))
  1011. {
  1012. if(target->isPositionFree(slot) && artifact->canBePutAt(target, slot, true)) //combined artifacts are not always allowed to move
  1013. {
  1014. ArtifactLocation destLocation(target->id, slot);
  1015. cb->swapArtifacts(location, destLocation); //just put into empty slot
  1016. emptySlotFound = true;
  1017. changeMade = true;
  1018. break;
  1019. }
  1020. }
  1021. if(!emptySlotFound) //try to put that atifact in already occupied slot
  1022. {
  1023. for(auto slot : artifact->getType()->getPossibleSlots().at(target->bearerType()))
  1024. {
  1025. auto otherSlot = target->getSlot(slot);
  1026. if(otherSlot && otherSlot->artifact) //we need to exchange artifact for better one
  1027. {
  1028. //if that artifact is better than what we have, pick it
  1029. if(compareArtifacts(artifact, otherSlot->artifact) && artifact->canBePutAt(target, slot, true)) //combined artifacts are not always allowed to move
  1030. {
  1031. ArtifactLocation destLocation(target->id, slot);
  1032. cb->swapArtifacts(location, ArtifactLocation(target->id, target->getArtPos(otherSlot->artifact)));
  1033. changeMade = true;
  1034. break;
  1035. }
  1036. }
  1037. }
  1038. }
  1039. if(changeMade)
  1040. break; //start evaluating artifacts from scratch
  1041. }
  1042. }
  1043. while(changeMade);
  1044. };
  1045. equipBest(h, other, true);
  1046. if(other)
  1047. equipBest(h, other, false);
  1048. }
  1049. void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
  1050. {
  1051. //now used only for visited dwellings / towns, not BuyArmy goal
  1052. for(int i = 0; i < d->creatures.size(); i++)
  1053. {
  1054. if(!d->creatures[i].second.size())
  1055. continue;
  1056. int count = d->creatures[i].first;
  1057. CreatureID creID = d->creatures[i].second.back();
  1058. vstd::amin(count, ah->freeResources() / VLC->creatures()->getById(creID)->getFullRecruitCost());
  1059. if(count > 0)
  1060. cb->recruitCreatures(d, recruiter, creID, count, i);
  1061. }
  1062. }
  1063. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, std::optional<float> movementCostLimit)
  1064. {
  1065. int3 op = obj->visitablePos();
  1066. auto paths = ah->getPathsToTile(h, op);
  1067. for(const auto & path : paths)
  1068. {
  1069. if(movementCostLimit && movementCostLimit.value() < path.movementCost())
  1070. return false;
  1071. if(isGoodForVisit(obj, h, path))
  1072. return true;
  1073. }
  1074. return false;
  1075. }
  1076. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const
  1077. {
  1078. const int3 pos = obj->visitablePos();
  1079. const int3 targetPos = path.firstTileToGet();
  1080. if (!targetPos.valid())
  1081. return false;
  1082. if (!isTileNotReserved(h.get(), targetPos))
  1083. return false;
  1084. if (obj->wasVisited(playerID))
  1085. return false;
  1086. if (cb->getPlayerRelations(playerID, obj->tempOwner) != PlayerRelations::ENEMIES && !isWeeklyRevisitable(obj))
  1087. return false; // Otherwise we flag or get weekly resources / creatures
  1088. if (!isSafeToVisit(h, pos))
  1089. return false;
  1090. if (!shouldVisit(h, obj))
  1091. return false;
  1092. if (vstd::contains(alreadyVisited, obj))
  1093. return false;
  1094. if (vstd::contains(reservedObjs, obj))
  1095. return false;
  1096. // TODO: looks extra if we already have AIPath
  1097. //if (!isAccessibleForHero(targetPos, h))
  1098. // return false;
  1099. const CGObjectInstance * topObj = cb->getVisitableObjs(obj->visitablePos()).back(); //it may be hero visiting this obj
  1100. //we don't try visiting object on which allied or owned hero stands
  1101. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1102. return !(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES); //all of the following is met
  1103. }
  1104. bool VCAI::isTileNotReserved(const CGHeroInstance * h, int3 t) const
  1105. {
  1106. if(t.valid())
  1107. {
  1108. auto obj = cb->getTopObj(t);
  1109. if(obj && vstd::contains(ai->reservedObjs, obj)
  1110. && vstd::contains(reservedHeroesMap, h)
  1111. && !vstd::contains(reservedHeroesMap.at(h), obj))
  1112. return false; //do not capture object reserved by another hero
  1113. else
  1114. return true;
  1115. }
  1116. else
  1117. {
  1118. return false;
  1119. }
  1120. }
  1121. bool VCAI::canRecruitAnyHero(const CGTownInstance * t) const
  1122. {
  1123. //TODO: make gathering gold, building tavern or conquering town (?) possible subgoals
  1124. if(!t)
  1125. t = findTownWithTavern();
  1126. if(!t)
  1127. return false;
  1128. if(cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST) //TODO: use ResourceManager
  1129. return false;
  1130. if(cb->getHeroesInfo().size() >= cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  1131. return false;
  1132. if(!cb->getAvailableHeroes(t).size())
  1133. return false;
  1134. return true;
  1135. }
  1136. void VCAI::wander(HeroPtr h)
  1137. {
  1138. auto visitTownIfAny = [this](HeroPtr h) -> bool
  1139. {
  1140. if (h->visitedTown)
  1141. {
  1142. townVisitsThisWeek[h].insert(h->visitedTown);
  1143. buildArmyIn(h->visitedTown);
  1144. return true;
  1145. }
  1146. return false;
  1147. };
  1148. //unclaim objects that are now dangerous for us
  1149. auto reservedObjsSetCopy = reservedHeroesMap[h];
  1150. for(auto obj : reservedObjsSetCopy)
  1151. {
  1152. if(!isSafeToVisit(h, obj->visitablePos()))
  1153. unreserveObject(h, obj);
  1154. }
  1155. TimeCheck tc("looking for wander destination");
  1156. for(int k = 0; k < 10 && h->movementPointsRemaining(); k++)
  1157. {
  1158. validateVisitableObjs();
  1159. ah->updatePaths(getMyHeroes());
  1160. std::vector<ObjectIdRef> dests;
  1161. //also visit our reserved objects - but they are not prioritized to avoid running back and forth
  1162. vstd::copy_if(reservedHeroesMap[h], std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1163. {
  1164. return ah->isTileAccessible(h, obj->visitablePos());
  1165. });
  1166. int pass = 0;
  1167. std::vector<std::optional<float>> distanceLimits = {1.0, 2.0, std::nullopt};
  1168. while(!dests.size() && pass < distanceLimits.size())
  1169. {
  1170. auto & distanceLimit = distanceLimits[pass];
  1171. logAi->debug("Looking for wander destination pass=%i, cost limit=%f", pass, distanceLimit.value_or(-1.0));
  1172. vstd::copy_if(visitableObjs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1173. {
  1174. return isGoodForVisit(obj, h, distanceLimit);
  1175. });
  1176. pass++;
  1177. }
  1178. if(!dests.size())
  1179. {
  1180. logAi->debug("Looking for town destination");
  1181. if(cb->getVisitableObjs(h->visitablePos()).size() > 1)
  1182. moveHeroToTile(h->visitablePos(), h); //just in case we're standing on blocked subterranean gate
  1183. auto compareReinforcements = [&](const CGTownInstance * lhs, const CGTownInstance * rhs) -> bool
  1184. {
  1185. const CGHeroInstance * hptr = h.get();
  1186. auto r1 = ah->howManyReinforcementsCanGet(hptr, lhs);
  1187. auto r2 = ah->howManyReinforcementsCanGet(hptr, rhs);
  1188. if (r1 != r2)
  1189. return r1 < r2;
  1190. else
  1191. return ah->howManyReinforcementsCanBuy(hptr, lhs) < ah->howManyReinforcementsCanBuy(hptr, rhs);
  1192. };
  1193. std::vector<const CGTownInstance *> townsReachable;
  1194. std::vector<const CGTownInstance *> townsNotReachable;
  1195. for(const CGTownInstance * t : cb->getTownsInfo())
  1196. {
  1197. if(!t->visitingHero && !vstd::contains(townVisitsThisWeek[h], t))
  1198. {
  1199. if(isAccessibleForHero(t->visitablePos(), h))
  1200. townsReachable.push_back(t);
  1201. else
  1202. townsNotReachable.push_back(t);
  1203. }
  1204. }
  1205. if(townsReachable.size()) //travel to town with largest garrison, or empty - better than nothing
  1206. {
  1207. dests.push_back(*boost::max_element(townsReachable, compareReinforcements));
  1208. }
  1209. else if(townsNotReachable.size())
  1210. {
  1211. //TODO pick the truly best
  1212. const CGTownInstance * t = *boost::max_element(townsNotReachable, compareReinforcements);
  1213. logAi->debug("%s can't reach any town, we'll try to make our way to %s at %s", h->getNameTranslated(), t->getNameTranslated(), t->visitablePos().toString());
  1214. int3 posBefore = h->visitablePos();
  1215. striveToGoal(sptr(Goals::ClearWayTo(t->visitablePos()).sethero(h))); //TODO: drop "strive", add to mainLoop
  1216. //if out hero is stuck, we may need to request another hero to clear the way we see
  1217. if(posBefore == h->visitablePos() && h == primaryHero()) //hero can't move
  1218. {
  1219. if(canRecruitAnyHero(t))
  1220. recruitHero(t);
  1221. }
  1222. break;
  1223. }
  1224. else if(cb->getResourceAmount(EGameResID::GOLD) >= GameConstants::HERO_GOLD_COST)
  1225. {
  1226. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1227. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  1228. {
  1229. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1230. {
  1231. if(!t->getArmyStrength() || ah->howManyReinforcementsCanGet(h, t))
  1232. return true;
  1233. }
  1234. return false;
  1235. });
  1236. if (towns.size())
  1237. {
  1238. recruitHero(*boost::max_element(towns, compareArmyStrength));
  1239. }
  1240. break;
  1241. }
  1242. else
  1243. {
  1244. logAi->debug("Nowhere more to go...");
  1245. break;
  1246. }
  1247. }
  1248. //end of objs empty
  1249. if(dests.size()) //performance improvement
  1250. {
  1251. Goals::TGoalVec targetObjectGoals;
  1252. for(auto destination : dests)
  1253. {
  1254. vstd::concatenate(targetObjectGoals, ah->howToVisitObj(h, destination, false));
  1255. }
  1256. if(targetObjectGoals.size())
  1257. {
  1258. auto bestObjectGoal = fh->chooseSolution(targetObjectGoals);
  1259. //wander should not cause heroes to be reserved - they are always considered free
  1260. if(bestObjectGoal->goalType == Goals::VISIT_OBJ)
  1261. {
  1262. auto chosenObject = cb->getObjInstance(ObjectInstanceID(bestObjectGoal->objid));
  1263. if(chosenObject != nullptr)
  1264. logAi->debug("Of all %d destinations, object %s at pos=%s seems nice", dests.size(), chosenObject->getObjectName(), chosenObject->anchorPos().toString());
  1265. }
  1266. else
  1267. logAi->debug("Trying to realize goal of type %s as part of wandering.", bestObjectGoal->name());
  1268. try
  1269. {
  1270. decomposeGoal(bestObjectGoal)->accept(this);
  1271. }
  1272. catch(const goalFulfilledException & e)
  1273. {
  1274. if(e.goal->goalType == Goals::EGoals::VISIT_TILE || e.goal->goalType == Goals::EGoals::VISIT_OBJ)
  1275. continue;
  1276. throw;
  1277. }
  1278. }
  1279. else
  1280. {
  1281. logAi->debug("Nowhere more to go...");
  1282. break;
  1283. }
  1284. visitTownIfAny(h);
  1285. }
  1286. }
  1287. visitTownIfAny(h); //in case hero is just sitting in town
  1288. }
  1289. void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal)
  1290. {
  1291. if(goal->invalid())
  1292. {
  1293. vstd::erase_if_present(lockedHeroes, h);
  1294. }
  1295. else
  1296. {
  1297. lockedHeroes[h] = goal;
  1298. goal->setisElementar(false); //Force always evaluate goals before realizing
  1299. }
  1300. }
  1301. void VCAI::evaluateGoal(HeroPtr h)
  1302. {
  1303. if(vstd::contains(lockedHeroes, h))
  1304. fh->setPriority(lockedHeroes[h]);
  1305. }
  1306. void VCAI::completeGoal(Goals::TSubgoal goal)
  1307. {
  1308. if (goal->goalType == Goals::WIN) //we can never complete this goal - unless we already won
  1309. return;
  1310. logAi->debug("Completing goal: %s", goal->name());
  1311. //notify Managers
  1312. ah->notifyGoalCompleted(goal);
  1313. //notify mainLoop()
  1314. goalsToRemove.push_back(goal); //will be removed from mainLoop() goals
  1315. for (auto basicGoal : basicGoals) //we could luckily fulfill any of our goals
  1316. {
  1317. if (basicGoal->fulfillsMe(goal))
  1318. goalsToRemove.push_back(basicGoal);
  1319. }
  1320. //unreserve heroes
  1321. if(const CGHeroInstance * h = goal->hero.get(true))
  1322. {
  1323. auto it = lockedHeroes.find(h);
  1324. if(it != lockedHeroes.end())
  1325. {
  1326. if(it->second == goal || it->second->fulfillsMe(goal)) //FIXME this is overspecified, fulfillsMe should be complete
  1327. {
  1328. logAi->debug(goal->completeMessage());
  1329. lockedHeroes.erase(it); //goal fulfilled, free hero
  1330. }
  1331. }
  1332. }
  1333. else //complete goal for all heroes maybe?
  1334. {
  1335. vstd::erase_if(lockedHeroes, [goal](std::pair<HeroPtr, Goals::TSubgoal> p)
  1336. {
  1337. if(p.second == goal || p.second->fulfillsMe(goal)) //we could have fulfilled goals of other heroes by chance
  1338. {
  1339. logAi->debug(p.second->completeMessage());
  1340. return true;
  1341. }
  1342. return false;
  1343. });
  1344. }
  1345. }
  1346. void VCAI::battleStart(const BattleID & battleID, const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, BattleSide side, bool replayAllowed)
  1347. {
  1348. NET_EVENT_HANDLER;
  1349. assert(!playerID.isValidPlayer() || status.getBattle() == UPCOMING_BATTLE);
  1350. status.setBattle(ONGOING_BATTLE);
  1351. 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
  1352. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->getNameTranslated() : "a army") % (presumedEnemy ? presumedEnemy->getObjectName() : "unknown enemy") % tile.toString());
  1353. CAdventureAI::battleStart(battleID, army1, army2, tile, hero1, hero2, side, replayAllowed);
  1354. }
  1355. void VCAI::battleEnd(const BattleID & battleID, const BattleResult * br, QueryID queryID)
  1356. {
  1357. NET_EVENT_HANDLER;
  1358. assert(status.getBattle() == ONGOING_BATTLE);
  1359. status.setBattle(ENDING_BATTLE);
  1360. bool won = br->winner == myCb->getBattle(battleID)->battleGetMySide();
  1361. logAi->debug("Player %d (%s): I %s the %s!", playerID, playerID.toString(), (won ? "won" : "lost"), battlename);
  1362. battlename.clear();
  1363. CAdventureAI::battleEnd(battleID, br, queryID);
  1364. }
  1365. void VCAI::waitTillFree()
  1366. {
  1367. auto unlock = vstd::makeUnlockSharedGuard(CGameState::mutex);
  1368. status.waitTillFree();
  1369. }
  1370. void VCAI::markObjectVisited(const CGObjectInstance * obj)
  1371. {
  1372. if(!obj)
  1373. return;
  1374. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj)) //we may want to visit it with another hero
  1375. {
  1376. if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_HERO) //we may want to visit it with another hero
  1377. return;
  1378. if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_BONUS) //or another time
  1379. return;
  1380. }
  1381. if(obj->ID == Obj::MONSTER)
  1382. return;
  1383. alreadyVisited.insert(obj);
  1384. }
  1385. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance * obj)
  1386. {
  1387. reservedObjs.insert(obj);
  1388. reservedHeroesMap[h].insert(obj);
  1389. logAi->debug("reserved object id=%d; address=%p; name=%s", obj->id, obj, obj->getObjectName());
  1390. }
  1391. void VCAI::unreserveObject(HeroPtr h, const CGObjectInstance * obj)
  1392. {
  1393. vstd::erase_if_present(reservedObjs, obj); //unreserve objects
  1394. vstd::erase_if_present(reservedHeroesMap[h], obj);
  1395. }
  1396. void VCAI::markHeroUnableToExplore(HeroPtr h)
  1397. {
  1398. heroesUnableToExplore.insert(h);
  1399. }
  1400. void VCAI::markHeroAbleToExplore(HeroPtr h)
  1401. {
  1402. vstd::erase_if_present(heroesUnableToExplore, h);
  1403. }
  1404. bool VCAI::isAbleToExplore(HeroPtr h)
  1405. {
  1406. return !vstd::contains(heroesUnableToExplore, h);
  1407. }
  1408. void VCAI::clearPathsInfo()
  1409. {
  1410. heroesUnableToExplore.clear();
  1411. }
  1412. void VCAI::validateVisitableObjs()
  1413. {
  1414. std::string errorMsg;
  1415. auto shouldBeErased = [&](const CGObjectInstance * obj) -> bool
  1416. {
  1417. if(obj)
  1418. return !cb->getObj(obj->id, false); // no verbose output needed as we check object visibility
  1419. else
  1420. return true;
  1421. };
  1422. //errorMsg is captured by ref so lambda will take the new text
  1423. errorMsg = " shouldn't be on the visitable objects list!";
  1424. vstd::erase_if(visitableObjs, shouldBeErased);
  1425. //FIXME: how comes our own heroes become inaccessible?
  1426. vstd::erase_if(reservedHeroesMap, [](std::pair<HeroPtr, std::set<const CGObjectInstance *>> hp) -> bool
  1427. {
  1428. return !hp.first.get(true);
  1429. });
  1430. for(auto & p : reservedHeroesMap)
  1431. {
  1432. errorMsg = " shouldn't be on list for hero " + p.first->getNameTranslated() + "!";
  1433. vstd::erase_if(p.second, shouldBeErased);
  1434. }
  1435. errorMsg = " shouldn't be on the reserved objs list!";
  1436. vstd::erase_if(reservedObjs, shouldBeErased);
  1437. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1438. errorMsg = " shouldn't be on the already visited objs list!";
  1439. vstd::erase_if(alreadyVisited, shouldBeErased);
  1440. }
  1441. void VCAI::retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned) const
  1442. {
  1443. foreach_tile_pos([&](const int3 & pos)
  1444. {
  1445. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1446. {
  1447. if(includeOwned || obj->tempOwner != playerID)
  1448. out.push_back(obj);
  1449. }
  1450. });
  1451. }
  1452. void VCAI::retrieveVisitableObjs()
  1453. {
  1454. foreach_tile_pos([&](const int3 & pos)
  1455. {
  1456. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1457. {
  1458. if(obj->tempOwner != playerID)
  1459. addVisitableObj(obj);
  1460. }
  1461. });
  1462. }
  1463. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1464. {
  1465. std::vector<const CGObjectInstance *> ret;
  1466. for(const CGObjectInstance * obj : visitableObjs)
  1467. {
  1468. if(obj->tempOwner == playerID)
  1469. ret.push_back(obj);
  1470. }
  1471. return ret;
  1472. }
  1473. void VCAI::addVisitableObj(const CGObjectInstance * obj)
  1474. {
  1475. if(obj->ID == Obj::EVENT)
  1476. return;
  1477. visitableObjs.insert(obj);
  1478. // All teleport objects seen automatically assigned to appropriate channels
  1479. auto teleportObj = dynamic_cast<const CGTeleport *>(obj);
  1480. if(teleportObj)
  1481. CGTeleport::addToChannel(knownTeleportChannels, teleportObj);
  1482. }
  1483. const CGObjectInstance * VCAI::lookForArt(ArtifactID aid) const
  1484. {
  1485. for(const CGObjectInstance * obj : ai->visitableObjs)
  1486. {
  1487. if(obj->ID == Obj::ARTIFACT && dynamic_cast<const CGArtifact *>(obj)->getArtifact() == aid)
  1488. return obj;
  1489. }
  1490. return nullptr;
  1491. //TODO what if more than one artifact is available? return them all or some selection criteria
  1492. }
  1493. bool VCAI::isAccessible(const int3 & pos) const
  1494. {
  1495. //TODO precalculate for speed
  1496. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1497. {
  1498. if(isAccessibleForHero(pos, h))
  1499. return true;
  1500. }
  1501. return false;
  1502. }
  1503. HeroPtr VCAI::getHeroWithGrail() const
  1504. {
  1505. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1506. {
  1507. if(h->hasArt(ArtifactID::GRAIL))
  1508. return h;
  1509. }
  1510. return nullptr;
  1511. }
  1512. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate)
  1513. {
  1514. //TODO smarter definition of unvisited
  1515. for(const CGObjectInstance * obj : visitableObjs)
  1516. {
  1517. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1518. return obj;
  1519. }
  1520. return nullptr;
  1521. }
  1522. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies) const
  1523. {
  1524. // Don't visit tile occupied by allied hero
  1525. if(!includeAllies)
  1526. {
  1527. for(auto obj : cb->getVisitableObjs(pos))
  1528. {
  1529. if(obj->ID == Obj::HERO && cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES)
  1530. {
  1531. if(obj != h.get())
  1532. return false;
  1533. }
  1534. }
  1535. }
  1536. return cb->getPathsInfo(h.get())->getPathInfo(pos)->reachable();
  1537. }
  1538. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1539. {
  1540. //TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
  1541. auto afterMovementCheck = [&]() -> void
  1542. {
  1543. waitTillFree(); //movement may cause battle or blocking dialog
  1544. if(!h)
  1545. {
  1546. lostHero(h);
  1547. teleportChannelProbingList.clear();
  1548. if(status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
  1549. status.setChannelProbing(false);
  1550. throw cannotFulfillGoalException("Hero was lost!");
  1551. }
  1552. };
  1553. logAi->debug("Moving hero %s to tile %s", h->getNameTranslated(), dst.toString());
  1554. int3 startHpos = h->visitablePos();
  1555. bool ret = false;
  1556. if(startHpos == dst)
  1557. {
  1558. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  1559. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1560. cb->moveHero(*h, h->convertFromVisitablePos(dst), false);
  1561. afterMovementCheck(); // TODO: is it feasible to hero get killed there if game work properly?
  1562. // If revisiting, teleport probing is never done, and so the entries into the list would remain unused and uncleared
  1563. teleportChannelProbingList.clear();
  1564. // not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
  1565. ret = true;
  1566. }
  1567. else
  1568. {
  1569. CGPath path;
  1570. cb->getPathsInfo(h.get())->getPath(path, dst);
  1571. if(path.nodes.empty())
  1572. {
  1573. logAi->error("Hero %s cannot reach %s.", h->getNameTranslated(), dst.toString());
  1574. throw goalFulfilledException(sptr(Goals::VisitTile(dst).sethero(h)));
  1575. }
  1576. int i = (int)path.nodes.size() - 1;
  1577. auto getObj = [&](int3 coord, bool ignoreHero)
  1578. {
  1579. auto tile = cb->getTile(coord, false);
  1580. assert(tile);
  1581. return tile->topVisitableObj(ignoreHero);
  1582. //return cb->getTile(coord,false)->topVisitableObj(ignoreHero);
  1583. };
  1584. auto isTeleportAction = [&](EPathNodeAction action) -> bool
  1585. {
  1586. if(action != EPathNodeAction::TELEPORT_NORMAL && action != EPathNodeAction::TELEPORT_BLOCKING_VISIT)
  1587. {
  1588. if(action != EPathNodeAction::TELEPORT_BATTLE)
  1589. {
  1590. return false;
  1591. }
  1592. }
  1593. return true;
  1594. };
  1595. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1596. {
  1597. if(CGTeleport::isConnected(currentObject, nextObjectTop))
  1598. return nextObjectTop;
  1599. if(nextObjectTop && nextObjectTop->ID == Obj::HERO)
  1600. {
  1601. if(CGTeleport::isConnected(currentObject, nextObject))
  1602. return nextObject;
  1603. }
  1604. return nullptr;
  1605. };
  1606. auto doMovement = [&](int3 dst, bool transit)
  1607. {
  1608. cb->moveHero(*h, h->convertFromVisitablePos(dst), transit);
  1609. };
  1610. auto doTeleportMovement = [&](ObjectInstanceID exitId, int3 exitPos)
  1611. {
  1612. destinationTeleport = exitId;
  1613. if(exitPos.valid())
  1614. destinationTeleportPos = exitPos;
  1615. cb->moveHero(*h, h->pos, false);
  1616. destinationTeleport = ObjectInstanceID();
  1617. destinationTeleportPos = int3(-1);
  1618. afterMovementCheck();
  1619. };
  1620. auto doChannelProbing = [&]() -> void
  1621. {
  1622. auto currentPos = h->visitablePos();
  1623. auto currentExit = getObj(currentPos, true)->id;
  1624. status.setChannelProbing(true);
  1625. for(auto exit : teleportChannelProbingList)
  1626. doTeleportMovement(exit, int3(-1));
  1627. teleportChannelProbingList.clear();
  1628. status.setChannelProbing(false);
  1629. doTeleportMovement(currentExit, currentPos);
  1630. };
  1631. for(; i > 0; i--)
  1632. {
  1633. int3 currentCoord = path.nodes[i].coord;
  1634. int3 nextCoord = path.nodes[i - 1].coord;
  1635. auto currentObject = getObj(currentCoord, currentCoord == h->visitablePos());
  1636. auto nextObjectTop = getObj(nextCoord, false);
  1637. auto nextObject = getObj(nextCoord, true);
  1638. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  1639. if(isTeleportAction(path.nodes[i - 1].action) && destTeleportObj != nullptr)
  1640. {
  1641. //we use special login if hero standing on teleporter it's mean we need
  1642. doTeleportMovement(destTeleportObj->id, nextCoord);
  1643. if(teleportChannelProbingList.size())
  1644. doChannelProbing();
  1645. markObjectVisited(destTeleportObj); //FIXME: Monoliths are not correctly visited
  1646. continue;
  1647. }
  1648. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1649. if(path.nodes[i - 1].turns)
  1650. {
  1651. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1652. break;
  1653. }
  1654. int3 endpos = path.nodes[i - 1].coord;
  1655. if(endpos == h->visitablePos())
  1656. continue;
  1657. bool isConnected = false;
  1658. bool isNextObjectTeleport = false;
  1659. // Check there is node after next one; otherwise transit is pointless
  1660. if(i - 2 >= 0)
  1661. {
  1662. isConnected = CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i - 2].coord, false));
  1663. isNextObjectTeleport = CGTeleport::isTeleport(nextObjectTop);
  1664. }
  1665. if(isConnected || isNextObjectTeleport)
  1666. {
  1667. // Hero should be able to go through object if it's allow transit
  1668. doMovement(endpos, true);
  1669. }
  1670. else if(path.nodes[i - 1].layer == EPathfindingLayer::AIR)
  1671. {
  1672. doMovement(endpos, true);
  1673. }
  1674. else
  1675. {
  1676. doMovement(endpos, false);
  1677. }
  1678. afterMovementCheck();
  1679. if(teleportChannelProbingList.size())
  1680. doChannelProbing();
  1681. }
  1682. if(path.nodes[0].action == EPathNodeAction::BLOCKING_VISIT)
  1683. {
  1684. ret = h && i == 0; // when we take resource we do not reach its position. We even might not move
  1685. }
  1686. }
  1687. if(h)
  1688. {
  1689. if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1690. {
  1691. if(visitedObject != *h)
  1692. performObjectInteraction(visitedObject, h);
  1693. }
  1694. }
  1695. if(h) //we could have lost hero after last move
  1696. {
  1697. completeGoal(sptr(Goals::VisitTile(dst).sethero(h))); //we stepped on some tile, anyway
  1698. completeGoal(sptr(Goals::ClearWayTo(dst).sethero(h)));
  1699. ret = ret || (dst == h->visitablePos());
  1700. if(!ret) //reserve object we are heading towards
  1701. {
  1702. auto obj = vstd::frontOrNull(cb->getVisitableObjs(dst));
  1703. if(obj && obj != *h)
  1704. reserveObject(h, obj);
  1705. }
  1706. if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1707. {
  1708. vstd::erase_if_present(lockedHeroes, h); //hero seemingly is confused or has only 95mp which is not enough to move
  1709. invalidPathHeroes.insert(h);
  1710. throw cannotFulfillGoalException("Invalid path found!");
  1711. }
  1712. evaluateGoal(h); //new hero position means new game situation
  1713. logAi->debug("Hero %s moved from %s to %s. Returning %d.", h->getNameTranslated(), startHpos.toString(), h->visitablePos().toString(), ret);
  1714. }
  1715. return ret;
  1716. }
  1717. void VCAI::buildStructure(const CGTownInstance * t, BuildingID building)
  1718. {
  1719. auto name = t->getTown()->buildings.at(building)->getNameTranslated();
  1720. logAi->debug("Player %d will build %s in town of %s at %s", ai->playerID, name, t->getNameTranslated(), t->anchorPos().toString());
  1721. cb->buildBuilding(t, building); //just do this;
  1722. }
  1723. void VCAI::tryRealize(Goals::Explore & g)
  1724. {
  1725. throw cannotFulfillGoalException("EXPLORE is not an elementar goal!");
  1726. }
  1727. void VCAI::tryRealize(Goals::RecruitHero & g)
  1728. {
  1729. if(cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST)
  1730. throw cannotFulfillGoalException("Not enough gold to recruit hero!");
  1731. if(const CGTownInstance * t = findTownWithTavern())
  1732. {
  1733. recruitHero(t, true);
  1734. //TODO try to free way to blocked town
  1735. //TODO: adventure map tavern or prison?
  1736. }
  1737. else
  1738. {
  1739. throw cannotFulfillGoalException("No town to recruit hero!");
  1740. }
  1741. }
  1742. void VCAI::tryRealize(Goals::VisitTile & g)
  1743. {
  1744. if(!g.hero->movementPointsRemaining())
  1745. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1746. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1747. {
  1748. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->getNameTranslated(), g.tile.toString());
  1749. throw goalFulfilledException(sptr(g));
  1750. }
  1751. if(ai->moveHeroToTile(g.tile, g.hero.get()))
  1752. {
  1753. throw goalFulfilledException(sptr(g));
  1754. }
  1755. }
  1756. void VCAI::tryRealize(Goals::VisitObj & g)
  1757. {
  1758. auto position = g.tile;
  1759. if(!g.hero->movementPointsRemaining())
  1760. throw cannotFulfillGoalException("Cannot visit object: hero is out of MPs!");
  1761. if(position == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1762. {
  1763. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->getNameTranslated(), g.tile.toString());
  1764. throw goalFulfilledException(sptr(g));
  1765. }
  1766. if(ai->moveHeroToTile(position, g.hero.get()))
  1767. {
  1768. throw goalFulfilledException(sptr(g));
  1769. }
  1770. }
  1771. void VCAI::tryRealize(Goals::VisitHero & g)
  1772. {
  1773. if(!g.hero->movementPointsRemaining())
  1774. throw cannotFulfillGoalException("Cannot visit target hero: hero is out of MPs!");
  1775. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid));
  1776. if(obj)
  1777. {
  1778. if(ai->moveHeroToTile(obj->visitablePos(), g.hero.get()))
  1779. {
  1780. throw goalFulfilledException(sptr(g));
  1781. }
  1782. }
  1783. else
  1784. {
  1785. throw cannotFulfillGoalException("Cannot visit hero: object not found!");
  1786. }
  1787. }
  1788. void VCAI::tryRealize(Goals::BuildThis & g)
  1789. {
  1790. auto b = BuildingID(g.bid);
  1791. auto t = g.town;
  1792. if (t)
  1793. {
  1794. if (cb->canBuildStructure(t, b) == EBuildingState::ALLOWED)
  1795. {
  1796. logAi->debug("Player %d will build %s in town of %s at %s",
  1797. playerID, t->getTown()->buildings.at(b)->getNameTranslated(), t->getNameTranslated(), t->anchorPos().toString());
  1798. cb->buildBuilding(t, b);
  1799. throw goalFulfilledException(sptr(g));
  1800. }
  1801. }
  1802. throw cannotFulfillGoalException("Cannot build a given structure!");
  1803. }
  1804. void VCAI::tryRealize(Goals::DigAtTile & g)
  1805. {
  1806. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1807. if(g.hero->diggingStatus() == EDiggingStatus::CAN_DIG)
  1808. {
  1809. cb->dig(g.hero.get());
  1810. completeGoal(sptr(g)); // finished digging
  1811. }
  1812. else
  1813. {
  1814. ai->lockedHeroes[g.hero] = sptr(g); //hero who tries to dig shouldn't do anything else
  1815. throw cannotFulfillGoalException("A hero can't dig!\n");
  1816. }
  1817. }
  1818. void VCAI::tryRealize(Goals::Trade & g) //trade
  1819. {
  1820. if(ah->freeResources()[g.resID] >= g.value) //goal is already fulfilled. Why we need this check, anyway?
  1821. throw goalFulfilledException(sptr(g));
  1822. int acquiredResources = 0;
  1823. if(const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1824. {
  1825. if(const auto * m = dynamic_cast<const IMarket*>(obj))
  1826. {
  1827. auto freeRes = ah->freeResources(); //trade only resources which are not reserved
  1828. for(auto it = ResourceSet::nziterator(freeRes); it.valid(); it++)
  1829. {
  1830. auto res = it->resType;
  1831. if(res.getNum() == g.resID) //sell any other resource
  1832. continue;
  1833. int toGive;
  1834. int toGet;
  1835. m->getOffer(res, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1836. toGive = static_cast<int>(toGive * (it->resVal / toGive)); //round down
  1837. //TODO trade only as much as needed
  1838. if (toGive) //don't try to sell 0 resources
  1839. {
  1840. cb->trade(m->getObjInstanceID(), EMarketMode::RESOURCE_RESOURCE, res, GameResID(g.resID), toGive);
  1841. acquiredResources = static_cast<int>(toGet * (it->resVal / toGive));
  1842. logAi->debug("Traded %d of %s for %d of %s at %s", toGive, res, acquiredResources, g.resID, obj->getObjectName());
  1843. }
  1844. if (ah->freeResources()[g.resID] >= g.value)
  1845. throw goalFulfilledException(sptr(g)); //we traded all we needed
  1846. }
  1847. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1848. }
  1849. else
  1850. {
  1851. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1852. }
  1853. }
  1854. else
  1855. {
  1856. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1857. }
  1858. }
  1859. void VCAI::tryRealize(Goals::BuyArmy & g)
  1860. {
  1861. auto t = g.town;
  1862. ui64 valueBought = 0;
  1863. //buy the stacks with largest AI value
  1864. makePossibleUpgrades(t);
  1865. while (valueBought < g.value)
  1866. {
  1867. auto res = ah->allResources();
  1868. std::vector<creInfo> creaturesInDwellings;
  1869. for (int i = 0; i < t->creatures.size(); i++)
  1870. {
  1871. auto ci = infoFromDC(t->creatures[i]);
  1872. if(!ci.count
  1873. || ci.creID == CreatureID::NONE
  1874. || (g.objid != -1 && ci.creID.getNum() != g.objid)
  1875. || t->getUpperArmy()->getSlotFor(ci.creID) == SlotID())
  1876. continue;
  1877. vstd::amin(ci.count, res / ci.cre->getFullRecruitCost()); //max count we can afford
  1878. if(!ci.count)
  1879. continue;
  1880. ci.level = i; //this is important for Dungeon Summoning Portal
  1881. creaturesInDwellings.push_back(ci);
  1882. }
  1883. if (creaturesInDwellings.empty())
  1884. throw cannotFulfillGoalException("Can't buy any more creatures!");
  1885. creInfo ci =
  1886. *boost::max_element(creaturesInDwellings, [](const creInfo & lhs, const creInfo & rhs)
  1887. {
  1888. //max value of creatures we can buy with our res
  1889. int value1 = lhs.cre->getAIValue() * lhs.count;
  1890. int value2 = rhs.cre->getAIValue() * rhs.count;
  1891. return value1 < value2;
  1892. });
  1893. cb->recruitCreatures(t, t->getUpperArmy(), ci.creID, ci.count, ci.level);
  1894. valueBought += ci.count * ci.cre->getAIValue();
  1895. }
  1896. throw goalFulfilledException(sptr(g)); //we bought as many creatures as we wanted
  1897. }
  1898. void VCAI::tryRealize(Goals::Invalid & g)
  1899. {
  1900. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1901. }
  1902. void VCAI::tryRealize(Goals::AbstractGoal & g)
  1903. {
  1904. logAi->debug("Attempting realizing goal with code %s", g.name());
  1905. throw cannotFulfillGoalException("Unknown type of goal !");
  1906. }
  1907. const CGTownInstance * VCAI::findTownWithTavern() const
  1908. {
  1909. for(const CGTownInstance * t : cb->getTownsInfo())
  1910. if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
  1911. return t;
  1912. return nullptr;
  1913. }
  1914. Goals::TSubgoal VCAI::getGoal(HeroPtr h) const
  1915. {
  1916. auto it = lockedHeroes.find(h);
  1917. if(it != lockedHeroes.end())
  1918. return it->second;
  1919. else
  1920. return sptr(Goals::Invalid());
  1921. }
  1922. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1923. {
  1924. std::vector<HeroPtr> ret;
  1925. for(auto h : cb->getHeroesInfo())
  1926. {
  1927. //&& !vstd::contains(lockedHeroes, h)
  1928. //at this point we assume heroes exhausted their locked goals
  1929. if(canAct(h))
  1930. ret.push_back(h);
  1931. }
  1932. return ret;
  1933. }
  1934. bool VCAI::canAct(HeroPtr h) const
  1935. {
  1936. auto mission = lockedHeroes.find(h);
  1937. if(mission != lockedHeroes.end())
  1938. {
  1939. //FIXME: I'm afraid there can be other conditions when heroes can act but not move :?
  1940. if(mission->second->goalType == Goals::DIG_AT_TILE && !mission->second->isElementar)
  1941. return false;
  1942. }
  1943. return h->movementPointsRemaining();
  1944. }
  1945. HeroPtr VCAI::primaryHero() const
  1946. {
  1947. auto hs = cb->getHeroesInfo();
  1948. if (hs.empty())
  1949. return nullptr;
  1950. else
  1951. return *boost::max_element(hs, compareHeroStrength);
  1952. }
  1953. void VCAI::endTurn()
  1954. {
  1955. logAi->info("Player %d (%s) ends turn", playerID, playerID.toString());
  1956. if(!status.haveTurn())
  1957. {
  1958. logAi->error("Not having turn at the end of turn???");
  1959. }
  1960. logAi->debug("Resources at the end of turn: %s", cb->getResourceAmount().toString());
  1961. do
  1962. {
  1963. cb->endTurn();
  1964. }
  1965. 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
  1966. logGlobal->info("Player %d (%s) ended turn", playerID, playerID.toString());
  1967. }
  1968. void VCAI::striveToGoal(Goals::TSubgoal basicGoal)
  1969. {
  1970. //TODO: this function is deprecated and should be dropped altogether
  1971. auto goalToDecompose = basicGoal;
  1972. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  1973. int maxAbstractGoals = 10;
  1974. while (!elementarGoal->isElementar && maxAbstractGoals)
  1975. {
  1976. try
  1977. {
  1978. elementarGoal = decomposeGoal(goalToDecompose);
  1979. }
  1980. catch (goalFulfilledException & e)
  1981. {
  1982. //it is impossible to continue some goals (like exploration, for example)
  1983. completeGoal(e.goal); //put in goalsToRemove
  1984. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  1985. return;
  1986. }
  1987. catch (std::exception & e)
  1988. {
  1989. goalsToRemove.push_back(basicGoal);
  1990. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  1991. return;
  1992. }
  1993. if (elementarGoal->isAbstract) //we can decompose it further
  1994. {
  1995. goalsToAdd.push_back(elementarGoal);
  1996. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  1997. goalToDecompose = elementarGoal;
  1998. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  1999. maxAbstractGoals--;
  2000. }
  2001. else if (elementarGoal->isElementar) //should be
  2002. {
  2003. logAi->debug("Found elementar goal %s", elementarGoal->name());
  2004. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  2005. break;
  2006. }
  2007. else //should never be here
  2008. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  2009. }
  2010. //realize best goal
  2011. if (!elementarGoal->invalid())
  2012. {
  2013. logAi->debug("Trying to realize %s (value %2.3f)", elementarGoal->name(), elementarGoal->priority);
  2014. try
  2015. {
  2016. boost::this_thread::interruption_point();
  2017. elementarGoal->accept(this); //visitor pattern
  2018. boost::this_thread::interruption_point();
  2019. }
  2020. catch (boost::thread_interrupted & e)
  2021. {
  2022. (void)e;
  2023. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  2024. throw; //rethrow, we want to truly end this thread
  2025. }
  2026. catch (goalFulfilledException & e)
  2027. {
  2028. //the sub-goal was completed successfully
  2029. completeGoal(e.goal);
  2030. //local goal was also completed
  2031. completeGoal(elementarGoal);
  2032. }
  2033. catch (std::exception & e)
  2034. {
  2035. logAi->debug("Failed to realize subgoal of type %s, I will stop.", elementarGoal->name());
  2036. logAi->debug("The error message was: %s", e.what());
  2037. //erase base goal if we failed to execute decomposed goal
  2038. for (auto basicGoalToRemove : ultimateGoalsFromBasic[elementarGoal])
  2039. goalsToRemove.push_back(basicGoalToRemove);
  2040. }
  2041. }
  2042. }
  2043. Goals::TSubgoal VCAI::decomposeGoal(Goals::TSubgoal ultimateGoal)
  2044. {
  2045. if(ultimateGoal->isElementar)
  2046. {
  2047. logAi->warn("Trying to decompose elementar goal %s", ultimateGoal->name());
  2048. return ultimateGoal;
  2049. }
  2050. const int searchDepth = 30;
  2051. Goals::TSubgoal goal = ultimateGoal;
  2052. logAi->debug("Decomposing goal %s", ultimateGoal->name());
  2053. int maxGoals = searchDepth; //preventing deadlock for mutually dependent goals
  2054. while (maxGoals)
  2055. {
  2056. boost::this_thread::interruption_point();
  2057. goal = goal->whatToDoToAchieve(); //may throw if decomposition fails
  2058. --maxGoals;
  2059. if (goal == ultimateGoal) //compare objects by value
  2060. if (goal->isElementar == ultimateGoal->isElementar)
  2061. throw cannotFulfillGoalException((boost::format("Goal dependency loop detected for %s!")
  2062. % ultimateGoal->name()).str());
  2063. if (goal->isAbstract || goal->isElementar)
  2064. return goal;
  2065. else
  2066. logAi->debug("Considering: %s", goal->name());
  2067. }
  2068. throw cannotFulfillGoalException("Too many subgoals, don't know what to do");
  2069. }
  2070. void VCAI::performTypicalActions()
  2071. {
  2072. for(auto h : getUnblockedHeroes())
  2073. {
  2074. if(!h) //hero might be lost. getUnblockedHeroes() called once on start of turn
  2075. continue;
  2076. logAi->debug("Hero %s started wandering, MP=%d", h->getNameTranslated(), h->movementPointsRemaining());
  2077. makePossibleUpgrades(*h);
  2078. pickBestArtifacts(*h);
  2079. try
  2080. {
  2081. wander(h);
  2082. }
  2083. catch(std::exception & e)
  2084. {
  2085. logAi->debug("Cannot use this hero anymore, received exception: %s", e.what());
  2086. continue;
  2087. }
  2088. }
  2089. }
  2090. void VCAI::buildArmyIn(const CGTownInstance * t)
  2091. {
  2092. makePossibleUpgrades(t->visitingHero);
  2093. makePossibleUpgrades(t);
  2094. recruitCreatures(t, t->getUpperArmy());
  2095. moveCreaturesToHero(t);
  2096. }
  2097. void VCAI::checkHeroArmy(HeroPtr h)
  2098. {
  2099. auto it = lockedHeroes.find(h);
  2100. if(it != lockedHeroes.end())
  2101. {
  2102. if(it->second->goalType == Goals::GATHER_ARMY && it->second->value <= h->getArmyStrength())
  2103. completeGoal(sptr(Goals::GatherArmy(it->second->value).sethero(h)));
  2104. }
  2105. }
  2106. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2107. {
  2108. logAi->debug("Trying to recruit a hero in %s at %s", t->getNameTranslated(), t->visitablePos().toString());
  2109. auto heroes = cb->getAvailableHeroes(t);
  2110. if(heroes.size())
  2111. {
  2112. auto hero = heroes[0];
  2113. if(heroes.size() >= 2) //makes sense to recruit two heroes with starting amries in first week
  2114. {
  2115. if(heroes[1]->getTotalStrength() > hero->getTotalStrength())
  2116. hero = heroes[1];
  2117. }
  2118. cb->recruitHero(t, hero);
  2119. throw goalFulfilledException(sptr(Goals::RecruitHero().settown(t)));
  2120. }
  2121. else if(throwing)
  2122. {
  2123. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2124. }
  2125. }
  2126. void VCAI::finish()
  2127. {
  2128. //we want to lock to avoid multiple threads from calling makingTurn->join() at same time
  2129. boost::lock_guard<boost::mutex> multipleCleanupGuard(turnInterruptionMutex);
  2130. if(makingTurn)
  2131. {
  2132. makingTurn->interrupt();
  2133. makingTurn->join();
  2134. makingTurn.reset();
  2135. }
  2136. }
  2137. void VCAI::requestActionASAP(std::function<void()> whatToDo)
  2138. {
  2139. boost::thread newThread([this, whatToDo]()
  2140. {
  2141. setThreadName("VCAI::requestActionASAP::whatToDo");
  2142. SET_GLOBAL_STATE(this);
  2143. boost::shared_lock gsLock(CGameState::mutex);
  2144. whatToDo();
  2145. });
  2146. newThread.detach();
  2147. }
  2148. void VCAI::lostHero(HeroPtr h)
  2149. {
  2150. logAi->debug("I lost my hero %s. It's best to forget and move on.", h.name);
  2151. vstd::erase_if_present(lockedHeroes, h);
  2152. for(auto obj : reservedHeroesMap[h])
  2153. {
  2154. vstd::erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2155. }
  2156. vstd::erase_if_present(reservedHeroesMap, h);
  2157. vstd::erase_if_present(visitedHeroes, h);
  2158. for (auto heroVec : visitedHeroes)
  2159. {
  2160. vstd::erase_if_present(heroVec.second, h);
  2161. }
  2162. //remove goals with removed hero assigned from main loop
  2163. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  2164. {
  2165. if(x.first->hero == h)
  2166. return true;
  2167. else
  2168. return false;
  2169. });
  2170. auto removedHeroGoalPredicate = [&](const Goals::TSubgoal & x) ->bool
  2171. {
  2172. if(x->hero == h)
  2173. return true;
  2174. else
  2175. return false;
  2176. };
  2177. vstd::erase_if(basicGoals, removedHeroGoalPredicate);
  2178. vstd::erase_if(goalsToAdd, removedHeroGoalPredicate);
  2179. vstd::erase_if(goalsToRemove, removedHeroGoalPredicate);
  2180. for(auto goal : ultimateGoalsFromBasic)
  2181. vstd::erase_if(goal.second, removedHeroGoalPredicate);
  2182. }
  2183. void VCAI::answerQuery(QueryID queryID, int selection)
  2184. {
  2185. logAi->debug("I'll answer the query %d giving the choice %d", queryID, selection);
  2186. if(queryID != QueryID(-1))
  2187. {
  2188. cb->selectionMade(selection, queryID);
  2189. }
  2190. else
  2191. {
  2192. logAi->debug("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  2193. //do nothing
  2194. }
  2195. }
  2196. void VCAI::requestSent(const CPackForServer * pack, int requestID)
  2197. {
  2198. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2199. if(auto reply = dynamic_cast<const QueryReply *>(pack))
  2200. {
  2201. status.attemptedAnsweringQuery(reply->qid, requestID);
  2202. }
  2203. }
  2204. std::string VCAI::getBattleAIName() const
  2205. {
  2206. if(settings["server"]["enemyAI"].getType() == JsonNode::JsonType::DATA_STRING)
  2207. return settings["server"]["enemyAI"].String();
  2208. else
  2209. return "BattleAI";
  2210. }
  2211. void VCAI::validateObject(const CGObjectInstance * obj)
  2212. {
  2213. validateObject(obj->id);
  2214. }
  2215. void VCAI::validateObject(ObjectIdRef obj)
  2216. {
  2217. auto matchesId = [&](const CGObjectInstance * hlpObj) -> bool
  2218. {
  2219. return hlpObj->id == obj.id;
  2220. };
  2221. if(!obj)
  2222. {
  2223. vstd::erase_if(visitableObjs, matchesId);
  2224. for(auto & p : reservedHeroesMap)
  2225. vstd::erase_if(p.second, matchesId);
  2226. vstd::erase_if(reservedObjs, matchesId);
  2227. }
  2228. }
  2229. AIStatus::AIStatus()
  2230. {
  2231. battle = NO_BATTLE;
  2232. havingTurn = false;
  2233. ongoingHeroMovement = false;
  2234. ongoingChannelProbing = false;
  2235. }
  2236. AIStatus::~AIStatus()
  2237. {
  2238. }
  2239. void AIStatus::setBattle(BattleState BS)
  2240. {
  2241. boost::unique_lock<boost::mutex> lock(mx);
  2242. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  2243. battle = BS;
  2244. cv.notify_all();
  2245. }
  2246. BattleState AIStatus::getBattle()
  2247. {
  2248. boost::unique_lock<boost::mutex> lock(mx);
  2249. return battle;
  2250. }
  2251. void AIStatus::addQuery(QueryID ID, std::string description)
  2252. {
  2253. if(ID == QueryID(-1))
  2254. {
  2255. logAi->debug("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID, description);
  2256. return;
  2257. }
  2258. assert(ID.getNum() >= 0);
  2259. boost::unique_lock<boost::mutex> lock(mx);
  2260. assert(!vstd::contains(remainingQueries, ID));
  2261. remainingQueries[ID] = description;
  2262. cv.notify_all();
  2263. logAi->debug("Adding query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2264. }
  2265. void AIStatus::removeQuery(QueryID ID)
  2266. {
  2267. boost::unique_lock<boost::mutex> lock(mx);
  2268. assert(vstd::contains(remainingQueries, ID));
  2269. std::string description = remainingQueries[ID];
  2270. remainingQueries.erase(ID);
  2271. cv.notify_all();
  2272. logAi->debug("Removing query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2273. }
  2274. int AIStatus::getQueriesCount()
  2275. {
  2276. boost::unique_lock<boost::mutex> lock(mx);
  2277. return static_cast<int>(remainingQueries.size());
  2278. }
  2279. void AIStatus::startedTurn()
  2280. {
  2281. boost::unique_lock<boost::mutex> lock(mx);
  2282. havingTurn = true;
  2283. cv.notify_all();
  2284. }
  2285. void AIStatus::madeTurn()
  2286. {
  2287. boost::unique_lock<boost::mutex> lock(mx);
  2288. havingTurn = false;
  2289. cv.notify_all();
  2290. }
  2291. void AIStatus::waitTillFree()
  2292. {
  2293. boost::unique_lock<boost::mutex> lock(mx);
  2294. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  2295. cv.wait_for(lock, boost::chrono::milliseconds(100));
  2296. }
  2297. bool AIStatus::haveTurn()
  2298. {
  2299. boost::unique_lock<boost::mutex> lock(mx);
  2300. return havingTurn;
  2301. }
  2302. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  2303. {
  2304. boost::unique_lock<boost::mutex> lock(mx);
  2305. assert(vstd::contains(remainingQueries, queryID));
  2306. std::string description = remainingQueries[queryID];
  2307. logAi->debug("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID, description, answerRequestID);
  2308. requestToQueryID[answerRequestID] = queryID;
  2309. }
  2310. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2311. {
  2312. QueryID query;
  2313. {
  2314. boost::unique_lock<boost::mutex> lock(mx);
  2315. assert(vstd::contains(requestToQueryID, answerRequestID));
  2316. query = requestToQueryID[answerRequestID];
  2317. assert(vstd::contains(remainingQueries, query));
  2318. requestToQueryID.erase(answerRequestID);
  2319. }
  2320. if(result)
  2321. {
  2322. removeQuery(query);
  2323. }
  2324. else
  2325. {
  2326. logAi->error("Something went really wrong, failed to answer query %d : %s", query.getNum(), remainingQueries[query]);
  2327. //TODO safely retry
  2328. }
  2329. }
  2330. void AIStatus::heroVisit(const CGObjectInstance * obj, bool started)
  2331. {
  2332. boost::unique_lock<boost::mutex> lock(mx);
  2333. if(started)
  2334. {
  2335. objectsBeingVisited.push_back(obj);
  2336. }
  2337. else
  2338. {
  2339. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  2340. // causing visit to hero on the other side.
  2341. // However, we are guaranteed that start/end visit notification maintain stack order.
  2342. assert(!objectsBeingVisited.empty());
  2343. objectsBeingVisited.pop_back();
  2344. }
  2345. cv.notify_all();
  2346. }
  2347. void AIStatus::setMove(bool ongoing)
  2348. {
  2349. boost::unique_lock<boost::mutex> lock(mx);
  2350. ongoingHeroMovement = ongoing;
  2351. cv.notify_all();
  2352. }
  2353. void AIStatus::setChannelProbing(bool ongoing)
  2354. {
  2355. boost::unique_lock<boost::mutex> lock(mx);
  2356. ongoingChannelProbing = ongoing;
  2357. cv.notify_all();
  2358. }
  2359. bool AIStatus::channelProbing()
  2360. {
  2361. return ongoingChannelProbing;
  2362. }
  2363. bool isWeeklyRevisitable(const CGObjectInstance * obj)
  2364. {
  2365. //TODO: allow polling of remaining creatures in dwelling
  2366. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
  2367. return rewardable->configuration.getResetDuration() == 7;
  2368. if(dynamic_cast<const CGDwelling *>(obj))
  2369. return true;
  2370. switch(obj->ID)
  2371. {
  2372. case Obj::STABLES:
  2373. case Obj::MAGIC_WELL:
  2374. case Obj::HILL_FORT:
  2375. return true;
  2376. case Obj::BORDER_GATE:
  2377. case Obj::BORDERGUARD:
  2378. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID); //FIXME: they could be revisited sooner than in a week
  2379. }
  2380. return false;
  2381. }
  2382. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2383. {
  2384. switch(obj->ID)
  2385. {
  2386. case Obj::TOWN:
  2387. case Obj::HERO: //never visit our heroes at random
  2388. return obj->tempOwner != h->tempOwner; //do not visit our towns at random
  2389. case Obj::BORDER_GATE:
  2390. {
  2391. for(auto q : ai->myCb->getMyQuests())
  2392. {
  2393. if(q.obj == obj)
  2394. {
  2395. return false; // do not visit guards or gates when wandering
  2396. }
  2397. }
  2398. return true; //we don't have this quest yet
  2399. }
  2400. case Obj::BORDERGUARD: //open borderguard if possible
  2401. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID);
  2402. case Obj::SEER_HUT:
  2403. case Obj::QUEST_GUARD:
  2404. {
  2405. for(auto q : ai->myCb->getMyQuests())
  2406. {
  2407. if(q.obj == obj)
  2408. {
  2409. if(q.quest->checkQuest(h.h))
  2410. return true; //we completed the quest
  2411. else
  2412. return false; //we can't complete this quest
  2413. }
  2414. }
  2415. return true; //we don't have this quest yet
  2416. }
  2417. case Obj::CREATURE_GENERATOR1:
  2418. {
  2419. if(obj->tempOwner != h->tempOwner)
  2420. return true; //flag just in case
  2421. bool canRecruitCreatures = false;
  2422. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2423. for(auto level : d->creatures)
  2424. {
  2425. for(auto c : level.second)
  2426. {
  2427. if(h->getSlotFor(CreatureID(c)) != SlotID())
  2428. canRecruitCreatures = true;
  2429. }
  2430. }
  2431. return canRecruitCreatures;
  2432. }
  2433. case Obj::HILL_FORT:
  2434. {
  2435. for(auto slot : h->Slots())
  2436. {
  2437. if(slot.second->getType()->hasUpgrades())
  2438. return true; //TODO: check price?
  2439. }
  2440. return false;
  2441. }
  2442. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  2443. case Obj::MONOLITH_ONE_WAY_EXIT:
  2444. case Obj::MONOLITH_TWO_WAY:
  2445. case Obj::WHIRLPOOL:
  2446. return false;
  2447. case Obj::SCHOOL_OF_MAGIC:
  2448. case Obj::SCHOOL_OF_WAR:
  2449. {
  2450. if (ai->ah->freeGold() < 1000)
  2451. return false;
  2452. break;
  2453. }
  2454. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2455. if(h->level < 12)
  2456. return false;
  2457. break;
  2458. case Obj::TREE_OF_KNOWLEDGE:
  2459. {
  2460. TResources myRes = ai->ah->freeResources();
  2461. if(myRes[EGameResID::GOLD] < 2000 || myRes[EGameResID::GEMS] < 10)
  2462. return false;
  2463. break;
  2464. }
  2465. case Obj::MAGIC_WELL:
  2466. return h->mana < h->manaLimit();
  2467. case Obj::PRISON:
  2468. return ai->myCb->getHeroesInfo().size() < cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP);
  2469. case Obj::TAVERN:
  2470. {
  2471. //TODO: make AI actually recruit heroes
  2472. //TODO: only on request
  2473. if(ai->myCb->getHeroesInfo().size() >= cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  2474. return false;
  2475. else if(ai->ah->freeGold() < GameConstants::HERO_GOLD_COST)
  2476. return false;
  2477. break;
  2478. }
  2479. case Obj::BOAT:
  2480. return false;
  2481. //Boats are handled by pathfinder
  2482. case Obj::EYE_OF_MAGI:
  2483. return false; //this object is useless to visit, but could be visited indefinitely
  2484. }
  2485. if(obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  2486. return false;
  2487. return true;
  2488. }
  2489. std::optional<BattleAction> VCAI::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  2490. {
  2491. return std::nullopt;
  2492. }