VCAI.cpp 93 KB

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