VCAI.cpp 88 KB

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