VCAI.cpp 88 KB

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