VCAI.cpp 95 KB

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