VCAI.cpp 88 KB

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