VCAI.cpp 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988
  1. #include "StdInc.h"
  2. #include "VCAI.h"
  3. #include "../../lib/UnlockGuard.h"
  4. #include "../../lib/CObjectHandler.h"
  5. #include "../../lib/CConfigHandler.h"
  6. #include "../../lib/CHeroHandler.h"
  7. #define I_AM_ELEMENTAR return CGoal(*this).setisElementar(true)
  8. CLogger &aiLogger = tlog6;
  9. extern FuzzyHelper *fh;
  10. class CGVisitableOPW;
  11. const int ACTUAL_RESOURCE_COUNT = 7;
  12. const double SAFE_ATTACK_CONSTANT = 1.5;
  13. using namespace vstd;
  14. //one thread may be turn of AI and another will be handling a side effect for AI2
  15. boost::thread_specific_ptr<CCallback> cb;
  16. boost::thread_specific_ptr<VCAI> ai;
  17. //std::map<int, std::map<int, int> > HeroView::infosCount;
  18. // CCallback *cb;
  19. // VCAI *ai;
  20. //helper RAII to manage global ai/cb ptrs
  21. struct SetGlobalState
  22. {
  23. SetGlobalState(VCAI * AI)
  24. {
  25. assert(!ai.get());
  26. assert(!cb.get());
  27. ai.reset(AI);
  28. cb.reset(AI->myCb);
  29. }
  30. ~SetGlobalState()
  31. {
  32. ai.release();
  33. cb.release();
  34. }
  35. };
  36. template <typename Container>
  37. typename Container::value_type backOrNull(const Container &c) //returns last element of container or NULL if it is empty (to be used with containers of pointers)
  38. {
  39. if(c.size())
  40. return c.back();
  41. else
  42. return NULL;
  43. }
  44. template <typename Container>
  45. typename Container::value_type frontOrNull(const Container &c) //returns first element of container or NULL if it is empty (to be used with containers of pointers)
  46. {
  47. if(c.size())
  48. return c.front();
  49. else
  50. return NULL;
  51. }
  52. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  53. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  54. #define MAKING_TURN SET_GLOBAL_STATE(this)
  55. 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)
  56. const int HERO_GOLD_COST = 2500;
  57. const int ALLOWED_ROAMING_HEROES = 8;
  58. const int GOLD_MINE_PRODUCTION = 1000, WOOD_ORE_MINE_PRODUCTION = 2, RESOURCE_MINE_PRODUCTION = 1;
  59. std::string CGoal::name() const
  60. {
  61. switch (goalType)
  62. {
  63. case INVALID:
  64. return "INVALID";
  65. case WIN:
  66. return "WIN";
  67. case DO_NOT_LOSE:
  68. return "DO NOT LOOSE";
  69. case CONQUER:
  70. return "CONQUER";
  71. case BUILD:
  72. return "BUILD";
  73. case EXPLORE:
  74. return "EXPLORE";
  75. case GATHER_ARMY:
  76. return "GATHER ARMY";
  77. case BOOST_HERO:
  78. return "BOOST_HERO (unsupported)";
  79. case RECRUIT_HERO:
  80. return "RECRUIT HERO";
  81. case BUILD_STRUCTURE:
  82. return "BUILD STRUCTURE";
  83. case COLLECT_RES:
  84. return "COLLECT RESOURCE";
  85. case GATHER_TROOPS:
  86. return "GATHER TROOPS";
  87. case GET_OBJ:
  88. return "GET OBJECT " + boost::lexical_cast<std::string>(objid);
  89. case FIND_OBJ:
  90. return "FIND OBJECT " + boost::lexical_cast<std::string>(objid);
  91. case VISIT_HERO:
  92. return "VISIT HERO " + boost::lexical_cast<std::string>(objid);
  93. case GET_ART_TYPE:
  94. return "GET ARTIFACT OF TYPE " + VLC->arth->artifacts[aid]->Name();
  95. case ISSUE_COMMAND:
  96. return "ISSUE COMMAND (unsupported)";
  97. case VISIT_TILE:
  98. return "VISIT TILE " + tile();
  99. case CLEAR_WAY_TO:
  100. return "CLEAR WAY TO " + tile();
  101. case DIG_AT_TILE:
  102. return "DIG AT TILE " + tile();
  103. default:
  104. return boost::lexical_cast<std::string>(goalType);
  105. }
  106. }
  107. bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
  108. {
  109. return h1->getTotalStrength() < h2->getTotalStrength();
  110. }
  111. bool compareArmyStrength(const CArmedInstance *a1, const CArmedInstance *a2)
  112. {
  113. return a1->getArmyStrength() < a2->getArmyStrength();
  114. }
  115. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  116. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  117. struct AILogger
  118. {
  119. AILogger()
  120. {
  121. lvl = 0;
  122. }
  123. int lvl;
  124. struct Tab
  125. {
  126. Tab();
  127. ~Tab();
  128. };
  129. } logger;
  130. AILogger::Tab::Tab()
  131. {
  132. logger.lvl++;
  133. }
  134. AILogger::Tab::~Tab()
  135. {
  136. logger.lvl--;
  137. }
  138. struct TimeCheck
  139. {
  140. CStopWatch time;
  141. std::string txt;
  142. TimeCheck(crstring TXT) : txt(TXT)
  143. {
  144. }
  145. ~TimeCheck()
  146. {
  147. BNLOG("Time of %s was %d ms.", txt % time.getDiff());
  148. }
  149. };
  150. template<typename T>
  151. void removeDuplicates(std::vector<T> &vec)
  152. {
  153. boost::sort(vec);
  154. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  155. }
  156. struct AtScopeExit
  157. {
  158. boost::function<void()> foo;
  159. AtScopeExit(const boost::function<void()> &FOO) : foo(FOO)
  160. {}
  161. ~AtScopeExit()
  162. {
  163. foo();
  164. }
  165. };
  166. void foreach_tile_pos(boost::function<void(const int3& pos)> foo)
  167. {
  168. for(int i = 0; i < cb->getMapSize().x; i++)
  169. for(int j = 0; j < cb->getMapSize().y; j++)
  170. for(int k = 0; k < cb->getMapSize().z; k++)
  171. foo(int3(i,j,k));
  172. }
  173. void foreach_neighbour(const int3 &pos, boost::function<void(const int3& pos)> foo)
  174. {
  175. BOOST_FOREACH(const int3 &dir, dirs)
  176. {
  177. const int3 n = pos + dir;
  178. if(cb->isInTheMap(n))
  179. foo(pos+dir);
  180. }
  181. }
  182. unsigned char &retreiveTileN(std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  183. {
  184. return vectors[pos.x][pos.y][pos.z];
  185. }
  186. const unsigned char &retreiveTileN(const std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  187. {
  188. return vectors[pos.x][pos.y][pos.z];
  189. }
  190. void foreach_tile(std::vector< std::vector< std::vector<unsigned char> > > &vectors, boost::function<void(unsigned char &in)> foo)
  191. {
  192. for(auto i = vectors.begin(); i != vectors.end(); i++)
  193. for(auto j = i->begin(); j != i->end(); j++)
  194. for(auto z = j->begin(); z != j->end(); z++)
  195. foo(*z);
  196. }
  197. struct ObjInfo
  198. {
  199. int3 pos;
  200. std::string name;
  201. ObjInfo(){}
  202. ObjInfo(const CGObjectInstance *obj)
  203. {
  204. pos = obj->pos;
  205. name = obj->getHoverText();
  206. }
  207. };
  208. std::map<const CGObjectInstance *, ObjInfo> helperObjInfo;
  209. template <typename Container, typename Item>
  210. bool remove_if_present(Container &c, const Item &item)
  211. {
  212. auto i = std::find(c.begin(), c.end(), item);
  213. if (i != c.end())
  214. {
  215. c.erase(i);
  216. return true;
  217. }
  218. return false;
  219. }
  220. template <typename V, typename Item, typename Item2>
  221. bool remove_if_present(std::map<Item,V> & c, const Item2 &item)
  222. {
  223. auto i = c.find(item);
  224. if (i != c.end())
  225. {
  226. c.erase(i);
  227. return true;
  228. }
  229. return false;
  230. }
  231. template <typename Container, typename Pred>
  232. void erase(Container &c, Pred pred)
  233. {
  234. c.erase(boost::remove_if(c, pred), c.end());
  235. }
  236. bool isReachable(const CGObjectInstance *obj)
  237. {
  238. return cb->getPathInfo(obj->visitablePos())->turns < 255;
  239. }
  240. ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance *t)
  241. {
  242. ui64 ret = 0;
  243. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  244. std::vector<const CStackInstance *> toMove;
  245. BOOST_FOREACH(auto const slot, t->Slots())
  246. {
  247. //can be merged woth another stack?
  248. TSlot dst = h->getSlotFor(slot.second->getCreatureID());
  249. if(h->hasStackAtSlot(dst))
  250. ret += t->getPower(slot.first);
  251. else
  252. toMove.push_back(slot.second);
  253. }
  254. boost::sort(toMove, [](const CStackInstance *lhs, const CStackInstance *rhs)
  255. {
  256. return lhs->getPower() < rhs->getPower();
  257. });
  258. BOOST_REVERSE_FOREACH(const CStackInstance *stack, toMove)
  259. {
  260. if(freeHeroSlots)
  261. {
  262. ret += stack->getPower();
  263. freeHeroSlots--;
  264. }
  265. else
  266. break;
  267. }
  268. return ret;
  269. }
  270. std::string strFromInt3(int3 pos)
  271. {
  272. std::ostringstream oss;
  273. oss << pos;
  274. return oss.str();
  275. }
  276. bool isCloser(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  277. {
  278. const CGPathNode *ln = cb->getPathInfo(lhs->visitablePos()), *rn = cb->getPathInfo(rhs->visitablePos());
  279. if(ln->turns != rn->turns)
  280. return ln->turns < rn->turns;
  281. return (ln->moveRemains > rn->moveRemains);
  282. }
  283. bool compareMovement(HeroPtr lhs, HeroPtr rhs)
  284. {
  285. return lhs->movement > rhs->movement;
  286. }
  287. ui64 evaluateDanger(const CGObjectInstance *obj);
  288. ui64 evaluateDanger(crint3 tile)
  289. {
  290. const TerrainTile *t = cb->getTile(tile, false);
  291. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  292. return 190000000; //MUCH
  293. ui64 objectDanger = 0, guardDanger = 0;
  294. auto visObjs = cb->getVisitableObjs(tile);
  295. if(visObjs.size())
  296. objectDanger = evaluateDanger(visObjs.back());
  297. int3 guardPos = cb->guardingCreaturePosition(tile);
  298. if(guardPos.x >= 0 && guardPos != tile)
  299. guardDanger = evaluateDanger(guardPos);
  300. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  301. return std::max(objectDanger, guardDanger);
  302. return 0;
  303. }
  304. ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor)
  305. {
  306. const TerrainTile *t = cb->getTile(tile, false);
  307. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  308. return 190000000; //MUCH
  309. ui64 objectDanger = 0, guardDanger = 0;
  310. auto visitableObjects = cb->getVisitableObjs(tile);
  311. // in some scenarios hero happens to be "under" the object (eg town). Then we consider ONLY the hero.
  312. if(vstd::contains_if(visitableObjects, objWithID<Obj::HERO>))
  313. erase_if(visitableObjects, ! boost::bind(objWithID<Obj::HERO>, _1));
  314. if(const CGObjectInstance * dangerousObject = backOrNull(visitableObjects))
  315. {
  316. objectDanger = evaluateDanger(dangerousObject); //unguarded objects can also be dangerous or unhandled
  317. if (objectDanger)
  318. {
  319. //TODO: don't downcast objects AI shouldnt know about!
  320. auto armedObj = dynamic_cast<const CArmedInstance*>(dangerousObject);
  321. if(armedObj)
  322. objectDanger *= fh->getTacticalAdvantage(visitor, armedObj); //this line tends to go infinite for allied towns (?)
  323. }
  324. }
  325. auto guards = cb->getGuardingCreatures(tile);
  326. BOOST_FOREACH (auto cre, guards)
  327. {
  328. amax (guardDanger, evaluateDanger(cre) * fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance*>(cre))); //we are interested in strongest monster around
  329. }
  330. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  331. return std::max(objectDanger, guardDanger);
  332. }
  333. ui64 evaluateDanger(const CGObjectInstance *obj)
  334. {
  335. if(obj->tempOwner < GameConstants::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID) != PlayerRelations::ENEMIES) //owned or allied objects don't pose any threat
  336. return 0;
  337. switch(obj->ID)
  338. {
  339. case Obj::HERO:
  340. {
  341. InfoAboutHero iah;
  342. cb->getHeroInfo(obj, iah);
  343. return iah.army.getStrength();
  344. }
  345. case Obj::TOWN:
  346. case Obj::GARRISON: case Obj::GARRISON2: //garrison
  347. {
  348. InfoAboutTown iat;
  349. cb->getTownInfo(obj, iat);
  350. return iat.army.getStrength();
  351. }
  352. case Obj::MONSTER:
  353. {
  354. //TODO!!!!!!!!
  355. const CGCreature *cre = dynamic_cast<const CGCreature*>(obj);
  356. return cre->getArmyStrength();
  357. }
  358. case Obj::CREATURE_GENERATOR1:
  359. {
  360. const CGDwelling *d = dynamic_cast<const CGDwelling*>(obj);
  361. return d->getArmyStrength();
  362. }
  363. case Obj::MINE:
  364. case Obj::ABANDONED_MINE:
  365. {
  366. const CArmedInstance * a = dynamic_cast<const CArmedInstance*>(obj);
  367. return a->getArmyStrength();
  368. }
  369. case Obj::CRYPT: //crypt
  370. case Obj::CREATURE_BANK: //crebank
  371. case Obj::DRAGON_UTOPIA:
  372. case Obj::SHIPWRECK: //shipwreck
  373. case Obj::DERELICT_SHIP: //derelict ship
  374. // case Obj::PYRAMID:
  375. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  376. case Obj::PYRAMID:
  377. {
  378. if(obj->subID == 0)
  379. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  380. else
  381. return 0;
  382. }
  383. default:
  384. return 0;
  385. }
  386. }
  387. bool compareDanger(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  388. {
  389. return evaluateDanger(lhs) < evaluateDanger(rhs);
  390. }
  391. VCAI::VCAI(void)
  392. {
  393. LOG_ENTRY;
  394. myCb = NULL;
  395. makingTurn = NULL;
  396. }
  397. VCAI::~VCAI(void)
  398. {
  399. LOG_ENTRY;
  400. }
  401. void VCAI::availableCreaturesChanged(const CGDwelling *town)
  402. {
  403. NET_EVENT_HANDLER;
  404. LOG_ENTRY;
  405. }
  406. void VCAI::heroMoved(const TryMoveHero & details)
  407. {
  408. NET_EVENT_HANDLER;
  409. LOG_ENTRY;
  410. if(details.result == TryMoveHero::TELEPORTATION)
  411. {
  412. const int3 from = CGHeroInstance::convertPosition(details.start, false),
  413. to = CGHeroInstance::convertPosition(details.end, false);
  414. const CGObjectInstance *o1 = frontOrNull(cb->getVisitableObjs(from)),
  415. *o2 = frontOrNull(cb->getVisitableObjs(to));
  416. if(o1 && o2 && o1->ID == Obj::SUBTERRANEAN_GATE && o2->ID == Obj::SUBTERRANEAN_GATE)
  417. {
  418. knownSubterraneanGates[o1] = o2;
  419. knownSubterraneanGates[o2] = o1;
  420. BNLOG("Found a pair of subterranean gates between %s and %s!", from % to);
  421. }
  422. }
  423. }
  424. void VCAI::stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute)
  425. {
  426. NET_EVENT_HANDLER;
  427. LOG_ENTRY;
  428. }
  429. void VCAI::heroInGarrisonChange(const CGTownInstance *town)
  430. {
  431. NET_EVENT_HANDLER;
  432. LOG_ENTRY;
  433. }
  434. void VCAI::centerView(int3 pos, int focusTime)
  435. {
  436. NET_EVENT_HANDLER;
  437. LOG_ENTRY;
  438. }
  439. void VCAI::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  440. {
  441. NET_EVENT_HANDLER;
  442. LOG_ENTRY;
  443. }
  444. void VCAI::artifactAssembled(const ArtifactLocation &al)
  445. {
  446. NET_EVENT_HANDLER;
  447. LOG_ENTRY;
  448. }
  449. void VCAI::showTavernWindow(const CGObjectInstance *townOrTavern)
  450. {
  451. NET_EVENT_HANDLER;
  452. LOG_ENTRY;
  453. }
  454. void VCAI::showThievesGuildWindow (const CGObjectInstance * obj)
  455. {
  456. NET_EVENT_HANDLER;
  457. LOG_ENTRY;
  458. }
  459. void VCAI::playerBlocked(int reason)
  460. {
  461. NET_EVENT_HANDLER;
  462. LOG_ENTRY;
  463. if (reason == PlayerBlocked::UPCOMING_BATTLE)
  464. status.setBattle(UPCOMING_BATTLE);
  465. }
  466. void VCAI::showPuzzleMap()
  467. {
  468. NET_EVENT_HANDLER;
  469. LOG_ENTRY;
  470. }
  471. void VCAI::showShipyardDialog(const IShipyard *obj)
  472. {
  473. NET_EVENT_HANDLER;
  474. LOG_ENTRY;
  475. }
  476. void VCAI::gameOver(ui8 player, bool victory)
  477. {
  478. NET_EVENT_HANDLER;
  479. LOG_ENTRY;
  480. BNLOG("Player %d: I heard that player %d %s.", playerID % (int)player % (victory ? "won" : "lost"));
  481. if(player == playerID)
  482. {
  483. if(victory)
  484. {
  485. tlog0 << "VCAI: I won! Incredible!\n";
  486. tlog0 << "Turn nr " << myCb->getDate() << std::endl;
  487. }
  488. else
  489. {
  490. tlog0 << "VCAI: Player " << (int)player << " lost. It's me. What a disappointment! :(\n";
  491. }
  492. // //let's make Impossible difficulty finally standing to its name :>
  493. // if(myCb->getStartInfo()->difficulty == 4 && !victory)
  494. // {
  495. // //play dirty: crash the whole engine to avoid lose
  496. // //that way AI is unbeatable!
  497. // *(int*)NULL = 666;
  498. // }
  499. // TODO - at least write some insults on stdout
  500. finish();
  501. }
  502. }
  503. void VCAI::artifactPut(const ArtifactLocation &al)
  504. {
  505. NET_EVENT_HANDLER;
  506. LOG_ENTRY;
  507. }
  508. void VCAI::artifactRemoved(const ArtifactLocation &al)
  509. {
  510. NET_EVENT_HANDLER;
  511. LOG_ENTRY;
  512. }
  513. void VCAI::stacksErased(const StackLocation &location)
  514. {
  515. NET_EVENT_HANDLER;
  516. LOG_ENTRY;
  517. }
  518. void VCAI::artifactDisassembled(const ArtifactLocation &al)
  519. {
  520. NET_EVENT_HANDLER;
  521. LOG_ENTRY;
  522. }
  523. void VCAI::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  524. {
  525. NET_EVENT_HANDLER;
  526. LOG_ENTRY;
  527. if (start)
  528. {
  529. visitedObject = const_cast<CGObjectInstance *>(visitedObj); // remember the object and wait for return
  530. markObjectVisited (visitedObj);
  531. remove_if_present(reservedObjs, visitedObj); //unreserve objects
  532. remove_if_present(reservedHeroesMap[visitor], visitedObj);
  533. completeGoal (CGoal(GET_OBJ).sethero(visitor)); //we don't need to visit in anymore
  534. }
  535. }
  536. void VCAI::availableArtifactsChanged(const CGBlackMarket *bm /*= NULL*/)
  537. {
  538. NET_EVENT_HANDLER;
  539. LOG_ENTRY;
  540. }
  541. void VCAI::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  542. {
  543. NET_EVENT_HANDLER;
  544. LOG_ENTRY;
  545. //buildArmyIn(town);
  546. //moveCreaturesToHero(town);
  547. }
  548. void VCAI::tileHidden(const boost::unordered_set<int3, ShashInt3> &pos)
  549. {
  550. NET_EVENT_HANDLER;
  551. LOG_ENTRY;
  552. // BOOST_FOREACH(int3 tile, pos)
  553. // BOOST_FOREACH(const CGObjectInstance *obj, cb->getVisitableObjs(tile))
  554. // remove_if_present(visitableObjs, obj);
  555. visitableObjs.erase(boost::remove_if(visitableObjs, [&](const CGObjectInstance *obj){return !myCb->getObj(obj->id);}), visitableObjs.end());
  556. }
  557. void VCAI::tileRevealed(const boost::unordered_set<int3, ShashInt3> &pos)
  558. {
  559. NET_EVENT_HANDLER;
  560. LOG_ENTRY;
  561. BOOST_FOREACH(int3 tile, pos)
  562. BOOST_FOREACH(const CGObjectInstance *obj, myCb->getVisitableObjs(tile))
  563. addVisitableObj(obj);
  564. }
  565. void VCAI::heroExchangeStarted(si32 hero1, si32 hero2)
  566. {
  567. NET_EVENT_HANDLER;
  568. LOG_ENTRY;
  569. auto firstHero = cb->getHero(hero1);
  570. auto secondHero = cb->getHero(hero2);
  571. requestActionASAP([=]()
  572. {
  573. if (firstHero->getHeroStrength() > secondHero->getHeroStrength() && canGetArmy (firstHero, secondHero))
  574. pickBestCreatures (firstHero, secondHero);
  575. else if (canGetArmy (secondHero, firstHero))
  576. pickBestCreatures (secondHero, firstHero);
  577. completeGoal(CGoal(VISIT_HERO).sethero(firstHero)); //TODO: what if we were visited by other hero in the meantime?
  578. completeGoal(CGoal(VISIT_HERO).sethero(secondHero));
  579. //TODO: exchange artifacts
  580. });
  581. }
  582. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  583. {
  584. NET_EVENT_HANDLER;
  585. LOG_ENTRY;
  586. }
  587. void VCAI::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  588. {
  589. NET_EVENT_HANDLER;
  590. LOG_ENTRY;
  591. }
  592. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  593. {
  594. NET_EVENT_HANDLER;
  595. LOG_ENTRY;
  596. }
  597. void VCAI::stackChangedType(const StackLocation &location, const CCreature &newType)
  598. {
  599. NET_EVENT_HANDLER;
  600. LOG_ENTRY;
  601. }
  602. void VCAI::stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count)
  603. {
  604. NET_EVENT_HANDLER;
  605. LOG_ENTRY;
  606. }
  607. void VCAI::newObject(const CGObjectInstance * obj)
  608. {
  609. NET_EVENT_HANDLER;
  610. LOG_ENTRY;
  611. if(obj->isVisitable())
  612. addVisitableObj(obj);
  613. }
  614. void VCAI::objectRemoved(const CGObjectInstance *obj)
  615. {
  616. NET_EVENT_HANDLER;
  617. LOG_ENTRY;
  618. if(remove_if_present(visitableObjs, obj))
  619. assert(obj->isVisitable());
  620. BOOST_FOREACH(auto &p, reservedHeroesMap)
  621. remove_if_present(p.second, obj);
  622. //TODO
  623. //there are other places where CGObjectinstance ptrs are stored...
  624. //
  625. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  626. {
  627. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is killed just before actual deletion
  628. }
  629. }
  630. void VCAI::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  631. {
  632. NET_EVENT_HANDLER;
  633. LOG_ENTRY;
  634. requestActionASAP([=]()
  635. {
  636. makePossibleUpgrades(visitor);
  637. });
  638. }
  639. void VCAI::playerBonusChanged(const Bonus &bonus, bool gain)
  640. {
  641. NET_EVENT_HANDLER;
  642. LOG_ENTRY;
  643. }
  644. void VCAI::newStackInserted(const StackLocation &location, const CStackInstance &stack)
  645. {
  646. NET_EVENT_HANDLER;
  647. LOG_ENTRY;
  648. }
  649. void VCAI::heroCreated(const CGHeroInstance*)
  650. {
  651. NET_EVENT_HANDLER;
  652. LOG_ENTRY;
  653. }
  654. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  655. {
  656. NET_EVENT_HANDLER;
  657. LOG_ENTRY;
  658. }
  659. void VCAI::showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID)
  660. {
  661. NET_EVENT_HANDLER;
  662. LOG_ENTRY;
  663. }
  664. void VCAI::requestRealized(PackageApplied *pa)
  665. {
  666. NET_EVENT_HANDLER;
  667. LOG_ENTRY;
  668. if(status.haveTurn())
  669. {
  670. if(pa->packType == typeList.getTypeID<EndTurn>())
  671. if(pa->result)
  672. status.madeTurn();
  673. }
  674. if(pa->packType == typeList.getTypeID<QueryReply>())
  675. {
  676. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  677. }
  678. }
  679. void VCAI::receivedResource(int type, int val)
  680. {
  681. NET_EVENT_HANDLER;
  682. LOG_ENTRY;
  683. }
  684. void VCAI::stacksSwapped(const StackLocation &loc1, const StackLocation &loc2)
  685. {
  686. NET_EVENT_HANDLER;
  687. LOG_ENTRY;
  688. }
  689. void VCAI::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  690. {
  691. NET_EVENT_HANDLER;
  692. LOG_ENTRY;
  693. }
  694. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  695. {
  696. NET_EVENT_HANDLER;
  697. LOG_ENTRY;
  698. }
  699. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  700. {
  701. NET_EVENT_HANDLER;
  702. LOG_ENTRY;
  703. }
  704. void VCAI::battleResultsApplied()
  705. {
  706. NET_EVENT_HANDLER;
  707. LOG_ENTRY;
  708. assert(status.getBattle() == ENDING_BATTLE);
  709. status.setBattle(NO_BATTLE);
  710. }
  711. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  712. {
  713. NET_EVENT_HANDLER;
  714. LOG_ENTRY;
  715. if(sop->what == ObjProperty::OWNER)
  716. {
  717. if(sop->val == playerID)
  718. remove_if_present(visitableObjs, myCb->getObj(sop->id));
  719. //TODO restore lost obj
  720. }
  721. }
  722. void VCAI::buildChanged(const CGTownInstance *town, int buildingID, int what)
  723. {
  724. NET_EVENT_HANDLER;
  725. LOG_ENTRY;
  726. }
  727. void VCAI::heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain)
  728. {
  729. NET_EVENT_HANDLER;
  730. LOG_ENTRY;
  731. }
  732. void VCAI::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  733. {
  734. NET_EVENT_HANDLER;
  735. LOG_ENTRY;
  736. }
  737. void VCAI::init(CCallback * CB)
  738. {
  739. myCb = CB;
  740. cbc = CB;
  741. NET_EVENT_HANDLER;
  742. LOG_ENTRY;
  743. playerID = myCb->getMyColor();
  744. myCb->waitTillRealize = true;
  745. myCb->unlockGsWhenWaiting = true;
  746. if(!fh)
  747. fh = new FuzzyHelper();
  748. retreiveVisitableObjs(visitableObjs);
  749. }
  750. void VCAI::yourTurn()
  751. {
  752. NET_EVENT_HANDLER;
  753. LOG_ENTRY;
  754. status.startedTurn();
  755. makingTurn = new boost::thread(&VCAI::makeTurn, this);
  756. }
  757. void VCAI::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill::SecondarySkill> &skills, int queryID)
  758. {
  759. NET_EVENT_HANDLER;
  760. LOG_ENTRY;
  761. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->name % hero->level));
  762. requestActionASAP([=]{ answerQuery(queryID, 0); });
  763. }
  764. void VCAI::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, int queryID)
  765. {
  766. NET_EVENT_HANDLER;
  767. LOG_ENTRY;
  768. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  769. requestActionASAP([=]{ answerQuery(queryID, 0); });
  770. }
  771. void VCAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, ui32 askID, const int soundID, bool selection, bool cancel)
  772. {
  773. NET_EVENT_HANDLER;
  774. LOG_ENTRY;
  775. int sel = 0;
  776. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  777. % components.size() % text));
  778. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  779. sel = components.size();
  780. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  781. sel = 1;
  782. requestActionASAP([=]()
  783. {
  784. answerQuery(askID, sel);
  785. });
  786. }
  787. void VCAI::showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, int queryID)
  788. {
  789. NET_EVENT_HANDLER;
  790. LOG_ENTRY;
  791. std::string s1 = up ? up->nodeName() : "NONE";
  792. std::string s2 = down ? down->nodeName() : "NONE";
  793. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  794. //you can't request action from action-response thread
  795. requestActionASAP([=]()
  796. {
  797. pickBestCreatures (down, up);
  798. answerQuery(queryID, 0);
  799. });
  800. }
  801. void VCAI::serialize(COSer<CSaveFile> &h, const int version)
  802. {
  803. NET_EVENT_HANDLER;
  804. LOG_ENTRY;
  805. }
  806. void VCAI::serialize(CISer<CLoadFile> &h, const int version)
  807. {
  808. NET_EVENT_HANDLER;
  809. LOG_ENTRY;
  810. }
  811. void makePossibleUpgrades(const CArmedInstance *obj)
  812. {
  813. if(!obj)
  814. return;
  815. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  816. {
  817. if(const CStackInstance *s = obj->getStackPtr(i))
  818. {
  819. UpgradeInfo ui;
  820. cb->getUpgradeInfo(obj, i, ui);
  821. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  822. {
  823. cb->upgradeCreature(obj, i, ui.newID[0]);
  824. }
  825. }
  826. }
  827. }
  828. void VCAI::makeTurn()
  829. {
  830. MAKING_TURN;
  831. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  832. setThreadName("VCAI::makeTurn");
  833. BNLOG("Player %d starting turn", playerID);
  834. INDENT;
  835. switch(cb->getDate(Date::DAY_OF_WEEK))
  836. {
  837. case 1:
  838. {
  839. townVisitsThisWeek.clear();
  840. std::vector<const CGObjectInstance *> objs;
  841. retreiveVisitableObjs(objs, true);
  842. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  843. {
  844. if (isWeeklyRevisitable(obj))
  845. {
  846. if (!vstd::contains(visitableObjs, obj))
  847. visitableObjs.push_back(obj);
  848. auto o = std::find (alreadyVisited.begin(), alreadyVisited.end(), obj);
  849. if (o != alreadyVisited.end())
  850. alreadyVisited.erase(o);
  851. }
  852. }
  853. }
  854. break;
  855. case 7: //reconsider strategy
  856. {
  857. if(auto h = primaryHero()) //check if our primary hero can handle danger
  858. {
  859. ui64 totalDanger = 0;
  860. int dangerousObjects = 0;
  861. std::vector<const CGObjectInstance *> objs;
  862. retreiveVisitableObjs(objs, false);
  863. BOOST_FOREACH (auto obj, objs)
  864. {
  865. if (evaluateDanger(obj)) //potentilaly dnagerous
  866. {
  867. totalDanger += evaluateDanger(obj->visitablePos(), *h);
  868. ++dangerousObjects;
  869. }
  870. }
  871. ui64 averageDanger = totalDanger / std::max(dangerousObjects, 1);
  872. if (dangerousObjects && averageDanger > h->getHeroStrength())
  873. {
  874. setGoal (h, CGoal(GATHER_ARMY).sethero(h).setvalue(averageDanger * SAFE_ATTACK_CONSTANT).setisAbstract(true));
  875. }
  876. }
  877. }
  878. break;
  879. }
  880. if(cb->getSelectedHero())
  881. cb->recalculatePaths();
  882. makeTurnInternal();
  883. vstd::clear_pointer(makingTurn);
  884. return;
  885. }
  886. void VCAI::makeTurnInternal()
  887. {
  888. saving = 0;
  889. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  890. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  891. moveCreaturesToHero(t);
  892. try
  893. {
  894. //Pick objects reserved in previous turn - we expect only nerby objects there
  895. auto reservedHeroesCopy = reservedHeroesMap; //work on copy => the map may be changed while iterating (eg because hero died when attempting a goal)
  896. BOOST_FOREACH (auto hero, reservedHeroesCopy)
  897. {
  898. cb->setSelection(hero.first.get());
  899. boost::sort (hero.second, isCloser);
  900. BOOST_FOREACH (auto obj, hero.second)
  901. {
  902. striveToGoal (CGoal(VISIT_TILE).sethero(hero.first).settile(obj->visitablePos()));
  903. }
  904. }
  905. //now try to win
  906. striveToGoal(CGoal(WIN));
  907. //finally, continue our abstract long-term goals
  908. //heroes tend to die in the process and loose their goals, unsafe to iterate it
  909. std::vector<std::pair<HeroPtr, CGoal> > safeCopy;
  910. boost::copy(lockedHeroes, std::back_inserter(safeCopy));
  911. typedef std::pair<HeroPtr, CGoal> TItrType;
  912. auto lockedHeroesSorter = [](TItrType h1, TItrType h2) -> bool
  913. {
  914. return compareMovement (h1.first, h2.first);
  915. };
  916. boost::sort(safeCopy, lockedHeroesSorter);
  917. while (safeCopy.size()) //continue our goals
  918. {
  919. auto it = safeCopy.begin();
  920. if (it->first && it->first->tempOwner == playerID && vstd::contains(lockedHeroes, it->first)) //make sure hero still has his goal
  921. {
  922. cb->setSelection(*it->first);
  923. striveToGoal (it->second);
  924. }
  925. safeCopy.erase(it);
  926. }
  927. auto quests = myCb->getMyQuests();
  928. BOOST_FOREACH (auto quest, quests)
  929. {
  930. striveToQuest (quest);
  931. }
  932. striveToGoal(CGoal(BUILD)); //TODO: smarter building management
  933. }
  934. catch(boost::thread_interrupted &e)
  935. {
  936. tlog0 << "Making turn thread has been interrupted. We'll end without calling endTurn.\n";
  937. return;
  938. }
  939. catch(std::exception &e)
  940. {
  941. tlog0 << "Making turn thread has caught an exception: " << e.what() << "\n";
  942. }
  943. endTurn();
  944. }
  945. bool VCAI::goVisitObj(const CGObjectInstance * obj, HeroPtr h)
  946. {
  947. int3 dst = obj->visitablePos();
  948. BNLOG("%s will try to visit %s at (%s)", h->name % obj->getHoverText() % strFromInt3(dst));
  949. return moveHeroToTile(dst, h);
  950. }
  951. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  952. {
  953. switch (obj->ID)
  954. {
  955. case Obj::CREATURE_GENERATOR1:
  956. recruitCreatures (dynamic_cast<const CGDwelling *>(obj));
  957. checkHeroArmy (h);
  958. break;
  959. case Obj::TOWN:
  960. moveCreaturesToHero (dynamic_cast<const CGTownInstance *>(obj));
  961. if (h->visitedTown) //we are inside, not just attacking
  962. {
  963. townVisitsThisWeek[h].push_back(h->visitedTown);
  964. if (!h->hasSpellbook() && cb->getResourceAmount(Res::GOLD) >= GameConstants::SPELLBOOK_GOLD_COST + saving[Res::GOLD] &&
  965. h->visitedTown->hasBuilt (EBuilding::MAGES_GUILD_1))
  966. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  967. }
  968. break;
  969. }
  970. }
  971. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  972. {
  973. if(t->visitingHero && t->armedGarrison())
  974. {
  975. pickBestCreatures (t->visitingHero, t);
  976. }
  977. }
  978. bool VCAI::canGetArmy (const CGHeroInstance * army, const CGHeroInstance * source)
  979. { //TODO: merge with pickBestCreatures
  980. const CArmedInstance *armies[] = {army, source};
  981. int armySize = 0;
  982. //we calculate total strength for each creature type available in armies
  983. std::map<const CCreature*, int> creToPower;
  984. BOOST_FOREACH(auto armyPtr, armies)
  985. BOOST_FOREACH(auto &i, armyPtr->Slots())
  986. {
  987. ++armySize;//TODO: allow splitting stacks?
  988. creToPower[i.second->type] += i.second->getPower();
  989. }
  990. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  991. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  992. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  993. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  994. {
  995. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  996. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  997. {
  998. return lhs.second < rhs.second;
  999. });
  1000. bestArmy.push_back(creIt->first);
  1001. creToPower.erase(creIt);
  1002. if(creToPower.empty())
  1003. break;
  1004. }
  1005. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  1006. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  1007. {
  1008. BOOST_FOREACH(auto armyPtr, armies)
  1009. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  1010. {
  1011. if(armyPtr->getCreature(j) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  1012. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1 && armyPtr != army)) //can't take away last creature
  1013. return true; //at least one exchange will be performed
  1014. }
  1015. }
  1016. return false;
  1017. }
  1018. void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source)
  1019. {
  1020. //TODO - what if source is a hero (the last stack problem) -> it'd good to create a single stack of weakest cre
  1021. const CArmedInstance *armies[] = {army, source};
  1022. int armySize = 0;
  1023. //we calculate total strength for each creature type available in armies
  1024. std::map<const CCreature*, int> creToPower;
  1025. BOOST_FOREACH(auto armyPtr, armies)
  1026. BOOST_FOREACH(auto &i, armyPtr->Slots())
  1027. {
  1028. ++armySize;//TODO: allow splitting stacks?
  1029. creToPower[i.second->type] += i.second->getPower();
  1030. }
  1031. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  1032. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  1033. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  1034. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  1035. {
  1036. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  1037. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  1038. {
  1039. return lhs.second < rhs.second;
  1040. });
  1041. bestArmy.push_back(creIt->first);
  1042. creToPower.erase(creIt);
  1043. if(creToPower.empty())
  1044. break;
  1045. }
  1046. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  1047. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  1048. {
  1049. BOOST_FOREACH(auto armyPtr, armies)
  1050. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  1051. {
  1052. if(armyPtr->getCreature(j) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  1053. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1 && armyPtr != army))
  1054. cb->mergeOrSwapStacks(armyPtr, army, j, i);
  1055. }
  1056. }
  1057. //TODO - having now strongest possible army, we may want to think about arranging stacks
  1058. auto hero = dynamic_cast<const CGHeroInstance *>(army);
  1059. if (hero)
  1060. {
  1061. checkHeroArmy (hero);
  1062. }
  1063. }
  1064. void VCAI::recruitCreatures(const CGDwelling * d)
  1065. {
  1066. for(int i = 0; i < d->creatures.size(); i++)
  1067. {
  1068. if(!d->creatures[i].second.size())
  1069. continue;
  1070. int count = d->creatures[i].first;
  1071. CreatureID::CreatureID creID = d->creatures[i].second.back();
  1072. // const CCreature *c = VLC->creh->creatures[creID];
  1073. // if(containsSavedRes(c->cost))
  1074. // continue;
  1075. TResources myRes = cb->getResourceAmount();
  1076. myRes[Res::GOLD] -= GOLD_RESERVE;
  1077. amin(count, myRes / VLC->creh->creatures[creID]->cost);
  1078. if(count > 0)
  1079. cb->recruitCreatures(d, creID, count, i);
  1080. }
  1081. }
  1082. bool VCAI::tryBuildStructure(const CGTownInstance * t, int building, unsigned int maxDays)
  1083. {
  1084. if (!vstd::contains(t->town->buildings, building))
  1085. return false; // no such building in town
  1086. if (t->hasBuilt(building)) //Already built? Shouldn't happen in general
  1087. return true;
  1088. std::set<int> toBuild = cb->getBuildingRequiments(t, building);
  1089. //erase all already built buildings
  1090. for (auto buildIter = toBuild.begin(); buildIter != toBuild.end();)
  1091. {
  1092. if (t->hasBuilt(*buildIter))
  1093. toBuild.erase(buildIter++);
  1094. else
  1095. buildIter++;
  1096. }
  1097. toBuild.insert(building);
  1098. BOOST_FOREACH(int buildID, toBuild)
  1099. {
  1100. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  1101. if (canBuild == EBuildingState::HAVE_CAPITAL
  1102. || canBuild == EBuildingState::FORBIDDEN
  1103. || canBuild == EBuildingState::NO_WATER)
  1104. return false; //we won't be able to build this
  1105. }
  1106. if (maxDays && toBuild.size() > maxDays)
  1107. return false;
  1108. TResources currentRes = cb->getResourceAmount();
  1109. TResources income = estimateIncome();
  1110. //TODO: calculate if we have enough resources to build it in maxDays
  1111. BOOST_FOREACH(int buildID, toBuild)
  1112. {
  1113. const CBuilding *b = t->town->buildings[buildID];
  1114. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  1115. if(canBuild == EBuildingState::ALLOWED)
  1116. {
  1117. if(!containsSavedRes(b->resources))
  1118. {
  1119. BNLOG("Player %d will build %s in town of %s at %s", playerID % b->Name() % t->name % t->pos);
  1120. cb->buildBuilding(t, buildID);
  1121. return true;
  1122. }
  1123. continue;
  1124. }
  1125. else if(canBuild == EBuildingState::NO_RESOURCES)
  1126. {
  1127. TResources cost = t->town->buildings[buildID]->resources;
  1128. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1129. {
  1130. int diff = currentRes[i] - cost[i] + income[i];
  1131. if(diff < 0)
  1132. saving[i] = 1;
  1133. }
  1134. continue;
  1135. }
  1136. }
  1137. return false;
  1138. }
  1139. bool VCAI::tryBuildAnyStructure(const CGTownInstance * t, std::vector<int> buildList, unsigned int maxDays)
  1140. {
  1141. BOOST_FOREACH(int building, buildList)
  1142. {
  1143. if(t->hasBuilt(building))
  1144. continue;
  1145. if (tryBuildStructure(t, building, maxDays))
  1146. return true;
  1147. }
  1148. return false; //Can't build anything
  1149. }
  1150. bool VCAI::tryBuildNextStructure(const CGTownInstance * t, std::vector<int> buildList, unsigned int maxDays)
  1151. {
  1152. BOOST_FOREACH(int building, buildList)
  1153. {
  1154. if(t->hasBuilt(building))
  1155. continue;
  1156. return tryBuildStructure(t, building, maxDays);
  1157. }
  1158. return false;//Nothing to build
  1159. }
  1160. void VCAI::buildStructure(const CGTownInstance * t)
  1161. {
  1162. using namespace EBuilding;
  1163. //TODO make *real* town development system
  1164. //TODO: faction-specific development: use special buildings, build dwellings in better order, etc
  1165. //TODO: build resource silo, defences when needed
  1166. //Possible - allow "locking" on specific building (build prerequisites and then building itself)
  1167. //Set of buildings for different goals. Does not include any prerequisites.
  1168. const int essential[] = {TAVERN, TOWN_HALL};
  1169. const int goldSource[] = {TOWN_HALL, CITY_HALL, CAPITOL};
  1170. const int unitsSource[] = { 30, 31, 32, 33, 34, 35, 36};
  1171. const int unitsUpgrade[] = { 37, 38, 39, 40, 41, 42, 43};
  1172. const int unitGrowth[] = { FORT, CITADEL, CASTLE, HORDE_1, HORDE_1_UPGR, HORDE_2, HORDE_2_UPGR};
  1173. const int spells[] = {MAGES_GUILD_1, MAGES_GUILD_2, MAGES_GUILD_3, MAGES_GUILD_4, MAGES_GUILD_5};
  1174. const int extra[] = {RESOURCE_SILO, SPECIAL_1, SPECIAL_2, SPECIAL_3, SPECIAL_4, SHIPYARD}; // all remaining buildings
  1175. TResources currentRes = cb->getResourceAmount();
  1176. TResources income = estimateIncome();
  1177. if (tryBuildAnyStructure(t, std::vector<int>(essential, essential + ARRAY_COUNT(essential))))
  1178. return;
  1179. //we're running out of gold - try to build something gold-producing. Multiplier can be tweaked, 6 is minimum due to buildings costs
  1180. if (currentRes[Res::GOLD] < income[Res::GOLD] * 6)
  1181. if (tryBuildNextStructure(t, std::vector<int>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1182. return;
  1183. if (cb->getDate(Date::DAY_OF_WEEK) > 6)// last 2 days of week - try to focus on growth
  1184. {
  1185. if (tryBuildNextStructure(t, std::vector<int>(unitGrowth, unitGrowth + ARRAY_COUNT(unitGrowth)), 2))
  1186. return;
  1187. }
  1188. // first in-game week or second half of any week: try build dwellings
  1189. if (cb->getDate(Date::DAY) < 7 || cb->getDate(Date::DAY_OF_WEEK) > 3)
  1190. if (tryBuildAnyStructure(t, std::vector<int>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK)))
  1191. return;
  1192. //try to upgrade dwelling
  1193. for(int i = 0; i < ARRAY_COUNT(unitsUpgrade); i++)
  1194. {
  1195. if (t->hasBuilt(unitsSource[i]) && !t->hasBuilt(unitsUpgrade[i]))
  1196. {
  1197. if (tryBuildStructure(t, unitsUpgrade[i]))
  1198. return;
  1199. }
  1200. }
  1201. //remaining tasks
  1202. if (tryBuildNextStructure(t, std::vector<int>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1203. return;
  1204. if (tryBuildNextStructure(t, std::vector<int>(spells, spells + ARRAY_COUNT(spells))))
  1205. return;
  1206. if (tryBuildAnyStructure(t, std::vector<int>(extra, extra + ARRAY_COUNT(extra))))
  1207. return;
  1208. }
  1209. bool isSafeToVisit(HeroPtr h, crint3 tile)
  1210. {
  1211. const ui64 heroStrength = h->getTotalStrength(),
  1212. dangerStrength = evaluateDanger(tile, *h);
  1213. if(dangerStrength)
  1214. {
  1215. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  1216. {
  1217. BNLOG("It's, safe for %s to visit tile %s", h->name % tile);
  1218. return true;
  1219. }
  1220. else
  1221. return false;
  1222. }
  1223. return true; //there's no danger
  1224. }
  1225. std::vector<const CGObjectInstance *> VCAI::getPossibleDestinations(HeroPtr h)
  1226. {
  1227. validateVisitableObjs();
  1228. std::vector<const CGObjectInstance *> possibleDestinations;
  1229. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1230. {
  1231. if(cb->getPathInfo(obj->visitablePos())->reachable() && !obj->wasVisited(playerID) &&
  1232. (obj->tempOwner != playerID || isWeeklyRevisitable(obj))) //flag or get weekly resources / creatures
  1233. possibleDestinations.push_back(obj);
  1234. }
  1235. boost::sort(possibleDestinations, isCloser);
  1236. possibleDestinations.erase(boost::remove_if(possibleDestinations, [&](const CGObjectInstance *obj) -> bool
  1237. {
  1238. const int3 pos = obj->visitablePos();
  1239. if(vstd::contains(alreadyVisited, obj))
  1240. return true;
  1241. if(!isSafeToVisit(h, pos))
  1242. return true;
  1243. if (!shouldVisit(h, obj))
  1244. return true;
  1245. if (vstd::contains(reservedObjs, obj)) //does checking for our own reserved objects make sense? here?
  1246. return true;
  1247. const CGObjectInstance *topObj = cb->getVisitableObjs(pos).back(); //it may be hero visiting this obj
  1248. //we don't try visiting object on which allied or owned hero stands
  1249. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1250. if(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  1251. return true;
  1252. return false;
  1253. }),possibleDestinations.end());
  1254. return possibleDestinations;
  1255. }
  1256. void VCAI::wander(HeroPtr h)
  1257. {
  1258. while(1)
  1259. {
  1260. std::vector <ObjectIdRef> dests;
  1261. range::copy(reservedHeroesMap[h], std::back_inserter(dests));
  1262. if (!dests.size())
  1263. range::copy(getPossibleDestinations(h), std::back_inserter(dests));
  1264. if(!dests.size())
  1265. {
  1266. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  1267. {
  1268. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  1269. };
  1270. std::vector<const CGTownInstance *> townsReachable;
  1271. std::vector<const CGTownInstance *> townsNotReachable;
  1272. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1273. {
  1274. if(!t->visitingHero && howManyReinforcementsCanGet(h,t) && !vstd::contains(townVisitsThisWeek[h], t))
  1275. {
  1276. if(isReachable(t))
  1277. townsReachable.push_back(t);
  1278. else
  1279. townsNotReachable.push_back(t);
  1280. }
  1281. }
  1282. if(townsReachable.size())
  1283. {
  1284. boost::sort(townsReachable, compareReinforcements);
  1285. dests.emplace_back(townsReachable.back());
  1286. }
  1287. else if(townsNotReachable.size())
  1288. {
  1289. boost::sort(townsNotReachable, compareReinforcements);
  1290. //TODO pick the truly best
  1291. const CGTownInstance *t = townsNotReachable.back();
  1292. BNLOG("%s can't reach any town, we'll try to make our way to %s at %s", h->name % t->name % t->visitablePos());
  1293. int3 pos1 = h->pos;
  1294. striveToGoal(CGoal(CLEAR_WAY_TO).settile(t->visitablePos()).sethero(h));
  1295. if (pos1 == h->pos && h == primaryHero()) //hero can't move
  1296. {
  1297. if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST && cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES && cb->getAvailableHeroes(t).size())
  1298. recruitHero(t);
  1299. }
  1300. break;
  1301. }
  1302. else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST)
  1303. {
  1304. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1305. erase_if(towns, [](const CGTownInstance *t) -> bool
  1306. {
  1307. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1308. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1309. return true;
  1310. return false;
  1311. });
  1312. boost::sort(towns, compareArmyStrength);
  1313. if(towns.size())
  1314. recruitHero(towns.back());
  1315. break;
  1316. }
  1317. else
  1318. {
  1319. PNLOG("Nowhere more to go...\n");
  1320. break;
  1321. }
  1322. }
  1323. const ObjectIdRef&dest = dests.front();
  1324. if(!goVisitObj(dest, h))
  1325. {
  1326. if(!dest)
  1327. {
  1328. BNLOG("Visit attempt made the object (id=%d) gone...", dest.id);
  1329. }
  1330. else
  1331. {
  1332. BNLOG("Hero %s apparently used all MPs (%d left)\n", h->name % h->movement);
  1333. reserveObject(h, dest); //reserve that object - we predict it will be reached soon
  1334. //removed - do not forget abstract goal so easily
  1335. //setGoal(h, CGoal(VISIT_TILE).sethero(h).settile(dest->visitablePos()));
  1336. }
  1337. break;
  1338. }
  1339. if(h->visitedTown)
  1340. {
  1341. townVisitsThisWeek[h].push_back(h->visitedTown);
  1342. buildArmyIn(h->visitedTown);
  1343. break;
  1344. }
  1345. }
  1346. }
  1347. void VCAI::setGoal(HeroPtr h, const CGoal goal)
  1348. { //TODO: check for presence?
  1349. if (goal.goalType == EGoals::INVALID)
  1350. remove_if_present(lockedHeroes, h);
  1351. else
  1352. lockedHeroes[h] = CGoal(goal).setisElementar(false); //always evaluate goals before realizing
  1353. }
  1354. void VCAI::setGoal(HeroPtr h, EGoals goalType)
  1355. {
  1356. if (goalType == EGoals::INVALID)
  1357. remove_if_present(lockedHeroes, h);
  1358. else
  1359. lockedHeroes[h] = CGoal(goalType).setisElementar(false); //always evaluate goals before realizing;
  1360. }
  1361. void VCAI::completeGoal (const CGoal goal)
  1362. {
  1363. if (const CGHeroInstance * h = goal.hero.get(true))
  1364. {
  1365. auto it = lockedHeroes.find(h);
  1366. if (it != lockedHeroes.end())
  1367. if (it->second.goalType == goal.goalType)
  1368. lockedHeroes.erase(it); //goal fulfilled, free hero
  1369. }
  1370. }
  1371. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  1372. {
  1373. NET_EVENT_HANDLER;
  1374. assert(playerID > GameConstants::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1375. status.setBattle(ONGOING_BATTLE);
  1376. const CGObjectInstance *presumedEnemy = backOrNull(cb->getVisitableObjs(tile)); //may be NULL in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit
  1377. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->hoverName : "unknown enemy") % tile);
  1378. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1379. }
  1380. void VCAI::battleEnd(const BattleResult *br)
  1381. {
  1382. NET_EVENT_HANDLER;
  1383. assert(status.getBattle() == ONGOING_BATTLE);
  1384. status.setBattle(ENDING_BATTLE);
  1385. bool won = br->winner == myCb->battleGetMySide();
  1386. BNLOG("Player %d: I %s the %s!", playerID % (won ? "won" : "lost") % battlename);
  1387. battlename.clear();
  1388. CAdventureAI::battleEnd(br);
  1389. }
  1390. void VCAI::waitTillFree()
  1391. {
  1392. auto unlock = vstd::makeUnlockSharedGuard(cb->getGsMutex());
  1393. status.waitTillFree();
  1394. }
  1395. void VCAI::markObjectVisited (const CGObjectInstance *obj)
  1396. {
  1397. if(dynamic_cast<const CGVisitableOPH *>(obj) || //we may want to wisit it with another hero
  1398. dynamic_cast<const CGBonusingObject *>(obj) || //or another time
  1399. (obj->ID == Obj::MONSTER))
  1400. return;
  1401. alreadyVisited.push_back(obj);
  1402. }
  1403. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance *obj)
  1404. {
  1405. reservedObjs.push_back(obj);
  1406. reservedHeroesMap[h].push_back(obj);
  1407. }
  1408. void VCAI::validateVisitableObjs()
  1409. {
  1410. std::vector<const CGObjectInstance *> hlp;
  1411. retreiveVisitableObjs(hlp, true);
  1412. start:
  1413. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1414. if(!vstd::contains(hlp, obj))
  1415. {
  1416. tlog1 << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << " shouldn't be on list!\n";
  1417. remove_if_present(visitableObjs, obj);
  1418. goto start;
  1419. }
  1420. }
  1421. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1422. {
  1423. foreach_tile_pos([&](const int3 &pos)
  1424. {
  1425. BOOST_FOREACH(const CGObjectInstance *obj, myCb->getVisitableObjs(pos, false))
  1426. {
  1427. if(includeOwned || obj->tempOwner != playerID)
  1428. out.push_back(obj);
  1429. }
  1430. });
  1431. }
  1432. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1433. {
  1434. std::vector<const CGObjectInstance *> ret;
  1435. retreiveVisitableObjs(ret, true);
  1436. erase_if(ret, [](const CGObjectInstance *obj)
  1437. {
  1438. return obj->tempOwner != ai->playerID;
  1439. });
  1440. return ret;
  1441. }
  1442. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  1443. {
  1444. visitableObjs.push_back(obj);
  1445. helperObjInfo[obj] = ObjInfo(obj);
  1446. }
  1447. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1448. {
  1449. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  1450. {
  1451. if(obj->ID == 5 && obj->subID == aid)
  1452. return obj;
  1453. }
  1454. return NULL;
  1455. //TODO what if more than one artifact is available? return them all or some slection criteria
  1456. }
  1457. bool VCAI::isAccessible(const int3 &pos)
  1458. {
  1459. //TODO precalculate for speed
  1460. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1461. {
  1462. if(isAccessibleForHero(pos, h))
  1463. return true;
  1464. }
  1465. return false;
  1466. }
  1467. HeroPtr VCAI::getHeroWithGrail() const
  1468. {
  1469. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1470. if(h->hasArt(2)) //grail
  1471. return h;
  1472. return NULL;
  1473. }
  1474. const CGObjectInstance * VCAI::getUnvisitedObj(const boost::function<bool(const CGObjectInstance *)> &predicate)
  1475. {
  1476. //TODO smarter definition of unvisited
  1477. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1478. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1479. return obj;
  1480. return NULL;
  1481. }
  1482. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies /*= false*/) const
  1483. {
  1484. cb->setSelection(*h);
  1485. if (!includeAllies)
  1486. { //don't visit tile occupied by allied hero
  1487. BOOST_FOREACH (auto obj, cb->getVisitableObjs(pos))
  1488. {
  1489. if (obj->ID == Obj::HERO && obj->tempOwner == h->tempOwner && obj != h)
  1490. return false;
  1491. }
  1492. }
  1493. return cb->getPathInfo(pos)->reachable();
  1494. }
  1495. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1496. {
  1497. visitedObject = NULL;
  1498. int3 startHpos = h->visitablePos();
  1499. bool ret = false;
  1500. if(startHpos == dst)
  1501. {
  1502. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1503. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1504. waitTillFree(); //movement may cause battle or blocking dialog
  1505. ret = true;
  1506. }
  1507. else
  1508. {
  1509. CGPath path;
  1510. cb->getPath2(dst, path);
  1511. if(path.nodes.empty())
  1512. {
  1513. tlog1 << "Hero " << h->name << " cannot reach " << dst << std::endl;
  1514. //setGoal(h, INVALID);
  1515. completeGoal (CGoal(VISIT_TILE).sethero(h));
  1516. cb->recalculatePaths();
  1517. throw std::runtime_error("Wrong move order!");
  1518. }
  1519. int i=path.nodes.size()-1;
  1520. for(; i>0; i--)
  1521. {
  1522. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1523. if(path.nodes[i-1].turns)
  1524. {
  1525. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1526. break;
  1527. }
  1528. int3 endpos = path.nodes[i-1].coord;
  1529. if(endpos == h->visitablePos())
  1530. //if (endpos == h->pos)
  1531. continue;
  1532. // if(i > 1)
  1533. // {
  1534. // int3 afterEndPos = path.nodes[i-2].coord;
  1535. // if(afterEndPos.z != endpos.z)
  1536. //
  1537. // }
  1538. //tlog0 << "Moving " << h->name << " from " << h->getPosition() << " to " << endpos << std::endl;
  1539. cb->moveHero(*h, CGHeroInstance::convertPosition(endpos, true));
  1540. waitTillFree(); //movement may cause battle or blocking dialog
  1541. boost::this_thread::interruption_point();
  1542. if(!h) //we lost hero - remove all tasks assigned to him/her
  1543. {
  1544. lostHero(h);
  1545. //we need to throw, otherwise hero will be assigned to sth again
  1546. throw std::runtime_error("Hero was lost!");
  1547. break;
  1548. }
  1549. }
  1550. ret = !i;
  1551. }
  1552. if (visitedObject) //we step into something interesting
  1553. {
  1554. performObjectInteraction (visitedObject, h);
  1555. //BNLOG("Hero %s moved from %s to %s at %s", h->name % startHpos % visitedObject->hoverName % h->visitablePos());
  1556. //throw goalFulfilledException (CGoal(GET_OBJ).setobjid(visitedObject->id));
  1557. }
  1558. if(h) //we could have lost hero after last move
  1559. {
  1560. cb->recalculatePaths();
  1561. if (startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1562. {
  1563. throw cannotFulfillGoalException("Invalid path found!");
  1564. }
  1565. }
  1566. BNLOG("Hero %s moved from %s to %s", h->name % startHpos % h->visitablePos());
  1567. return ret;
  1568. }
  1569. int howManyTilesWillBeDiscovered(const int3 &pos, int radious)
  1570. { //TODO: do not explore dead-end boundaries
  1571. int ret = 0;
  1572. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  1573. {
  1574. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  1575. {
  1576. int3 npos = int3(x,y,pos.z);
  1577. if(cb->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cb->isVisible(npos))
  1578. {
  1579. if (!boundaryBetweenTwoPoints (pos, npos))
  1580. ret++;
  1581. }
  1582. }
  1583. }
  1584. return ret;
  1585. }
  1586. bool boundaryBetweenTwoPoints (int3 pos1, int3 pos2) //determines if two points are separated by known barrier
  1587. {
  1588. int xMin = std::min (pos1.x, pos2.x);
  1589. int xMax = std::max (pos1.x, pos2.x);
  1590. int yMin = std::min (pos1.y, pos2.y);
  1591. int yMax = std::max (pos1.y, pos2.y);
  1592. for (int x = xMin; x <= xMax; ++x)
  1593. {
  1594. for (int y = yMin; y <= yMax; ++y)
  1595. {
  1596. int3 tile = int3(x, y, pos1.z); //use only on same level, ofc
  1597. if (abs(pos1.dist2d(tile) - pos2.dist2d(tile)) < 1.5)
  1598. {
  1599. if (!(cb->isVisible(tile) && cb->getTile(tile)->blocked)) //if there's invisible or unblocked tile inbetween, it's good
  1600. return false;
  1601. }
  1602. }
  1603. }
  1604. return true; //if all are visible and blocked, we're at dead end
  1605. }
  1606. int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
  1607. {
  1608. return howManyTilesWillBeDiscovered(pos + dir, radious);
  1609. }
  1610. void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
  1611. {
  1612. BOOST_FOREACH(const int3 &tile, tiles)
  1613. {
  1614. foreach_neighbour(tile, [&](int3 neighbour)
  1615. {
  1616. if(cb->isVisible(neighbour))
  1617. out.push_back(neighbour);
  1618. });
  1619. }
  1620. }
  1621. void VCAI::tryRealize(CGoal g)
  1622. {
  1623. BNLOG("Attempting realizing goal with code %s", g.name());
  1624. switch(g.goalType)
  1625. {
  1626. case EXPLORE:
  1627. {
  1628. throw cannotFulfillGoalException("EXPLORE is not a elementar goal!");
  1629. }
  1630. break;
  1631. case RECRUIT_HERO:
  1632. {
  1633. if(const CGTownInstance *t = findTownWithTavern())
  1634. {
  1635. recruitHero(t, true);
  1636. //TODO jezeli miasto jest zablokowane, sprobowac oczyscic wejscie
  1637. }
  1638. //TODO karkolomna alternatywa - tawerna na mapie przygod lub wiezienie (nie wiem, czy warto?)
  1639. }
  1640. break;
  1641. case VISIT_TILE:
  1642. {
  1643. //cb->recalculatePaths();
  1644. if(!g.hero->movement)
  1645. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1646. //if(!g.isBlockedBorderGate(g.tile))
  1647. //{
  1648. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1649. {
  1650. throw goalFulfilledException (g);
  1651. }
  1652. //}
  1653. //else
  1654. // throw cannotFulfillGoalException("There's a blocked gate!, we should never be here"); //CLEAR_WAY_TO should get keymaster tent
  1655. }
  1656. break;
  1657. case VISIT_HERO:
  1658. {
  1659. if(!g.hero->movement)
  1660. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1661. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1662. {
  1663. throw goalFulfilledException (g);
  1664. }
  1665. }
  1666. break;
  1667. case BUILD_STRUCTURE:
  1668. {
  1669. const CGTownInstance *t = g.town;
  1670. if(!t && g.hero)
  1671. t = g.hero->visitedTown;
  1672. if(!t)
  1673. {
  1674. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1675. {
  1676. switch(cb->canBuildStructure(t, g.bid))
  1677. {
  1678. case EBuildingState::ALLOWED:
  1679. cb->buildBuilding(t, g.bid);
  1680. return;
  1681. default:
  1682. break;
  1683. }
  1684. }
  1685. }
  1686. else if(cb->canBuildStructure(t, g.bid) == EBuildingState::ALLOWED)
  1687. {
  1688. cb->buildBuilding(t, g.bid);
  1689. return;
  1690. }
  1691. throw cannotFulfillGoalException("Cannot build a given structure!");
  1692. }
  1693. break;
  1694. case DIG_AT_TILE:
  1695. {
  1696. assert(g.hero->visitablePos() == g.tile);
  1697. if (g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1698. {
  1699. cb->dig(g.hero.get());
  1700. setGoal(g.hero, INVALID); // finished digging
  1701. }
  1702. else
  1703. {
  1704. ai->lockedHeroes[g.hero] = g; //hero who tries to dig shouldn't do anything else
  1705. throw cannotFulfillGoalException("A hero can't dig!\n");
  1706. }
  1707. }
  1708. break;
  1709. case COLLECT_RES: //TODO: use piles and mines?
  1710. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1711. throw cannotFulfillGoalException("Goal is already fulfilled!");
  1712. if(const CGObjectInstance *obj = cb->getObj(g.objid, false))
  1713. {
  1714. if(const IMarket *m = IMarket::castFrom(obj, false))
  1715. {
  1716. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  1717. {
  1718. if(i == g.resID) continue;
  1719. int toGive, toGet;
  1720. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1721. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1722. //TODO trade only as much as needed
  1723. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1724. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1725. return;
  1726. }
  1727. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1728. }
  1729. else
  1730. {
  1731. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1732. }
  1733. }
  1734. else
  1735. {
  1736. saving[g.resID] = 1;
  1737. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1738. }
  1739. case CONQUER:
  1740. case GATHER_ARMY:
  1741. case BOOST_HERO:
  1742. // TODO: conquer??
  1743. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1744. case BUILD:
  1745. performTypicalActions(); //TODO: separate build and wander
  1746. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1747. case INVALID:
  1748. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1749. default:
  1750. throw cannotFulfillGoalException("Unknown type of goal !");
  1751. }
  1752. }
  1753. const CGTownInstance * VCAI::findTownWithTavern() const
  1754. {
  1755. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1756. if(t->hasBuilt(EBuilding::TAVERN) && !t->visitingHero)
  1757. return t;
  1758. return NULL;
  1759. }
  1760. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1761. {
  1762. std::vector<HeroPtr> ret;
  1763. boost::copy(cb->getHeroesInfo(), std::back_inserter(ret));
  1764. BOOST_FOREACH(auto h, lockedHeroes)
  1765. {
  1766. //if (!h.second.invalid()) //we can use heroes without valid goal
  1767. if (h.second.goalType == DIG_AT_TILE || !h.first->movement) //experiment: use all heroes that have movement left, TODO: unlock heroes that couldn't realize their goals
  1768. remove_if_present(ret, h.first);
  1769. }
  1770. return ret;
  1771. }
  1772. HeroPtr VCAI::primaryHero() const
  1773. {
  1774. auto hs = cb->getHeroesInfo();
  1775. boost::sort(hs, compareHeroStrength);
  1776. if(hs.empty())
  1777. return NULL;
  1778. return hs.back();
  1779. }
  1780. void VCAI::endTurn()
  1781. {
  1782. tlog4 << "Player " << playerID << " ends turn\n";
  1783. if(!status.haveTurn())
  1784. {
  1785. tlog1 << "Not having turn at the end of turn???\n";
  1786. }
  1787. do
  1788. {
  1789. cb->endTurn();
  1790. } 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
  1791. tlog4 << "Player " << playerID << " ended turn\n";
  1792. }
  1793. bool VCAI::fulfillsGoal (CGoal &goal, CGoal &mainGoal)
  1794. {
  1795. if (mainGoal.goalType == GET_OBJ && goal.goalType == VISIT_TILE) //deduce that GET_OBJ was completed by visiting object's tile
  1796. { //TODO: more universal mechanism
  1797. if (cb->getObj(mainGoal.objid)->visitablePos() == goal.tile)
  1798. return true;
  1799. }
  1800. return false;
  1801. }
  1802. bool VCAI::fulfillsGoal (CGoal &goal, const CGoal &mainGoal)
  1803. {
  1804. if (mainGoal.goalType == GET_OBJ && goal.goalType == VISIT_TILE) //deduce that GET_OBJ was completed by visiting object's tile
  1805. { //TODO: more universal mechanism
  1806. if (cb->getObj(mainGoal.objid)->visitablePos() == goal.tile)
  1807. return true;
  1808. }
  1809. return false;
  1810. }
  1811. void VCAI::striveToGoal(const CGoal &ultimateGoal)
  1812. {
  1813. if (ultimateGoal.invalid())
  1814. return;
  1815. CGoal abstractGoal;
  1816. while(1)
  1817. {
  1818. CGoal goal = ultimateGoal;
  1819. BNLOG("Striving to goal of type %s", ultimateGoal.name());
  1820. int maxGoals = 100; //preventing deadlock for mutually dependent goals
  1821. while(!goal.isElementar && !goal.isAbstract && maxGoals)
  1822. {
  1823. INDENT;
  1824. BNLOG("Considering goal %s", goal.name());
  1825. try
  1826. {
  1827. boost::this_thread::interruption_point();
  1828. goal = goal.whatToDoToAchieve();
  1829. --maxGoals;
  1830. }
  1831. catch(std::exception &e)
  1832. {
  1833. BNLOG("Goal %s decomposition failed: %s", goal.name() % e.what());
  1834. //setGoal (goal.hero, INVALID); //test: if we don't know how to realize goal, we should abandon it for now
  1835. return;
  1836. }
  1837. }
  1838. try
  1839. {
  1840. boost::this_thread::interruption_point();
  1841. if (goal.hero) //lock this hero to fulfill ultimate goal
  1842. {
  1843. if (maxGoals)
  1844. {
  1845. setGoal(goal.hero, goal);
  1846. }
  1847. else
  1848. {
  1849. setGoal(goal.hero, INVALID); // we seemingly don't know what to do with hero
  1850. }
  1851. }
  1852. if (goal.isAbstract)
  1853. {
  1854. abstractGoal = goal; //allow only one abstract goal per call
  1855. BNLOG("Choosing abstract goal %s", goal.name());
  1856. break;
  1857. }
  1858. else
  1859. tryRealize(goal);
  1860. boost::this_thread::interruption_point();
  1861. }
  1862. catch(boost::thread_interrupted &e)
  1863. {
  1864. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1865. throw; //rethrow, we want to truly end this thread
  1866. }
  1867. catch(goalFulfilledException &e)
  1868. {
  1869. completeGoal (goal);
  1870. if (fulfillsGoal (goal, ultimateGoal) || maxGoals > 98) //completed goal was main goal //TODO: find better condition
  1871. return;
  1872. }
  1873. catch(std::exception &e)
  1874. {
  1875. BNLOG("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.", goal.name() % ultimateGoal.name());
  1876. BNLOG("The error message was: %s", e.what());
  1877. break;
  1878. }
  1879. }
  1880. //TODO: save abstract goals not related to hero
  1881. if (!abstractGoal.invalid()) //try to realize our one goal
  1882. {
  1883. while (1)
  1884. {
  1885. CGoal goal = CGoal(abstractGoal).setisAbstract(false);
  1886. int maxGoals = 50;
  1887. while (!goal.isElementar && maxGoals) //find elementar goal and fulfill it
  1888. {
  1889. try
  1890. {
  1891. boost::this_thread::interruption_point();
  1892. goal = goal.whatToDoToAchieve();
  1893. --maxGoals;
  1894. }
  1895. catch(std::exception &e)
  1896. {
  1897. BNLOG("Goal %s decomposition failed: %s", goal.name() % e.what());
  1898. //setGoal (goal.hero, INVALID);
  1899. return;
  1900. }
  1901. }
  1902. try
  1903. {
  1904. boost::this_thread::interruption_point();
  1905. tryRealize(goal);
  1906. boost::this_thread::interruption_point();
  1907. }
  1908. catch(boost::thread_interrupted &e)
  1909. {
  1910. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1911. throw; //rethrow, we want to truly end this thread
  1912. }
  1913. catch(goalFulfilledException &e)
  1914. {
  1915. completeGoal (goal); //FIXME: deduce that we have realized GET_OBJ goal
  1916. if (fulfillsGoal (goal, abstractGoal) || maxGoals > 98) //completed goal was main goal
  1917. return;
  1918. }
  1919. catch(std::exception &e)
  1920. {
  1921. BNLOG("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.", goal.name() % ultimateGoal.name());
  1922. BNLOG("The error message was: %s", e.what());
  1923. break;
  1924. }
  1925. }
  1926. }
  1927. }
  1928. void VCAI::striveToQuest (const QuestInfo &q)
  1929. {
  1930. if (q.quest->missionType && q.quest->progress != CQuest::COMPLETE) //FIXME: quests are never synchronized. Pointer handling needed
  1931. {
  1932. MetaString ms;
  1933. q.quest->getRolloverText(ms, false);
  1934. BNLOG ("Trying to realize quest: %s", ms.toString());
  1935. auto heroes = cb->getHeroesInfo();
  1936. switch (q.quest->missionType)
  1937. {
  1938. case CQuest::MISSION_ART:
  1939. {
  1940. BOOST_FOREACH (auto hero, heroes) //TODO: remove duplicated code?
  1941. {
  1942. if (q.quest->checkQuest(hero))
  1943. {
  1944. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  1945. return;
  1946. }
  1947. }
  1948. BOOST_FOREACH (auto art, q.quest->m5arts)
  1949. {
  1950. striveToGoal (CGoal(GET_ART_TYPE).setaid(art)); //TODO: transport?
  1951. }
  1952. break;
  1953. }
  1954. case CQuest::MISSION_HERO:
  1955. {
  1956. //striveToGoal (CGoal(RECRUIT_HERO));
  1957. BOOST_FOREACH (auto hero, heroes)
  1958. {
  1959. if (q.quest->checkQuest(hero))
  1960. {
  1961. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  1962. return;
  1963. }
  1964. }
  1965. striveToGoal (CGoal(FIND_OBJ).setobjid(Obj::PRISON)); //rule of a thumb - quest heroes usually are locked in prisons
  1966. //BNLOG ("Don't know how to recruit hero with id %d\n", q.quest->m13489val);
  1967. break;
  1968. }
  1969. case CQuest::MISSION_ARMY:
  1970. {
  1971. BOOST_FOREACH (auto hero, heroes)
  1972. {
  1973. if (q.quest->checkQuest(hero)) //veyr bad info - stacks can be split between multiple heroes :(
  1974. {
  1975. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  1976. return;
  1977. }
  1978. }
  1979. BOOST_FOREACH (auto creature, q.quest->m6creatures)
  1980. {
  1981. striveToGoal (CGoal(GATHER_TROOPS).setobjid(creature.type->idNumber).setvalue(creature.count));
  1982. }
  1983. //TODO: exchange armies... oh my
  1984. //BNLOG ("Don't know how to recruit %d of %s\n", (int)(creature.count) % creature.type->namePl);
  1985. break;
  1986. }
  1987. case CQuest::MISSION_RESOURCES:
  1988. {
  1989. if (heroes.size())
  1990. {
  1991. if (q.quest->checkQuest(heroes.front())) //it doesn't matter which hero it is
  1992. {
  1993. striveToGoal (CGoal(VISIT_TILE).settile(q.tile));
  1994. }
  1995. else
  1996. {
  1997. for (int i = 0; i < q.quest->m7resources.size(); ++i)
  1998. {
  1999. if (q.quest->m7resources[i])
  2000. striveToGoal (CGoal(COLLECT_RES).setresID(i).setvalue(q.quest->m7resources[i]));
  2001. }
  2002. }
  2003. }
  2004. else
  2005. striveToGoal (CGoal(RECRUIT_HERO)); //FIXME: checkQuest requires any hero belonging to player :(
  2006. break;
  2007. }
  2008. case CQuest::MISSION_KILL_HERO:
  2009. case CQuest::MISSION_KILL_CREATURE:
  2010. {
  2011. auto obj = cb->getObjByQuestIdentifier(q.quest->m13489val);
  2012. if (obj)
  2013. striveToGoal (CGoal(GET_OBJ).setobjid(obj->id));
  2014. else
  2015. striveToGoal (CGoal(VISIT_TILE).settile(q.tile)); //visit seer hut
  2016. break;
  2017. }
  2018. case CQuest::MISSION_PRIMARY_STAT:
  2019. {
  2020. auto heroes = cb->getHeroesInfo();
  2021. BOOST_FOREACH (auto hero, heroes)
  2022. {
  2023. if (q.quest->checkQuest(hero))
  2024. {
  2025. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  2026. return;
  2027. }
  2028. }
  2029. for (int i = 0; i < q.quest->m2stats.size(); ++i)
  2030. {
  2031. BNLOG ("Don't know how to increase primary stat %d\n", i);
  2032. }
  2033. break;
  2034. }
  2035. case CQuest::MISSION_LEVEL:
  2036. {
  2037. auto heroes = cb->getHeroesInfo();
  2038. BOOST_FOREACH (auto hero, heroes)
  2039. {
  2040. if (q.quest->checkQuest(hero))
  2041. {
  2042. striveToGoal (CGoal(VISIT_TILE).settile(q.tile).sethero(hero)); //TODO: causes infinite loop :/
  2043. return;
  2044. }
  2045. }
  2046. BNLOG ("Don't know how to reach hero level %d\n", q.quest->m13489val);
  2047. break;
  2048. }
  2049. case CQuest::MISSION_PLAYER:
  2050. {
  2051. if (playerID != q.quest->m13489val)
  2052. BNLOG ("Can't be player of color %d\n", q.quest->m13489val);
  2053. break;
  2054. }
  2055. case CQuest::MISSION_KEYMASTER:
  2056. {
  2057. striveToGoal (CGoal(FIND_OBJ).setobjid(Obj::KEYMASTER).setresID(q.obj->subID));
  2058. break;
  2059. }
  2060. }
  2061. }
  2062. }
  2063. void VCAI::performTypicalActions()
  2064. {
  2065. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2066. {
  2067. BNLOG("Looking into %s", t->name);
  2068. buildStructure(t);
  2069. buildArmyIn(t);
  2070. if(!ai->primaryHero() ||
  2071. (t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero())))
  2072. {
  2073. recruitHero(t);
  2074. buildArmyIn(t);
  2075. }
  2076. }
  2077. BOOST_FOREACH(auto h, getUnblockedHeroes())
  2078. {
  2079. BNLOG("Looking into %s, MP=%d", h->name.c_str() % h->movement);
  2080. INDENT;
  2081. makePossibleUpgrades(*h);
  2082. cb->setSelection(*h);
  2083. try
  2084. {
  2085. wander(h);
  2086. }
  2087. catch(std::exception &e)
  2088. {
  2089. BNLOG("Cannot use this hero anymore, received exception: %s", e.what());
  2090. continue;
  2091. }
  2092. }
  2093. }
  2094. void VCAI::buildArmyIn(const CGTownInstance * t)
  2095. {
  2096. makePossibleUpgrades(t->visitingHero);
  2097. makePossibleUpgrades(t);
  2098. recruitCreatures(t);
  2099. moveCreaturesToHero(t);
  2100. }
  2101. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h)
  2102. {
  2103. TimeCheck tc("looking for best exploration neighbour");
  2104. std::map<int3, int> dstToRevealedTiles;
  2105. BOOST_FOREACH(crint3 dir, dirs)
  2106. if(cb->isInTheMap(hpos+dir))
  2107. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir) * isSafeToVisit(h, hpos + dir);
  2108. auto best = dstToRevealedTiles.begin();
  2109. best->second *= cb->getPathInfo(best->first)->reachable();
  2110. best->second *= cb->getPathInfo(best->first)->accessible == CGPathNode::ACCESSIBLE;
  2111. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  2112. {
  2113. const CGPathNode *pn = cb->getPathInfo(i->first);
  2114. //const TerrainTile *t = cb->getTile(i->first);
  2115. if(best->second < i->second && i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  2116. best = i;
  2117. }
  2118. if(best->second)
  2119. return best->first;
  2120. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  2121. }
  2122. int3 VCAI::explorationNewPoint(int radius, HeroPtr h, std::vector<std::vector<int3> > &tiles)
  2123. {
  2124. TimeCheck tc("looking for new exploration point");
  2125. PNLOG("Looking for an another place for exploration...");
  2126. tiles.resize(radius);
  2127. foreach_tile_pos([&](const int3 &pos)
  2128. {
  2129. if(!cb->isVisible(pos))
  2130. tiles[0].push_back(pos);
  2131. });
  2132. for (int i = 1; i < radius; i++)
  2133. {
  2134. getVisibleNeighbours(tiles[i-1], tiles[i]);
  2135. removeDuplicates(tiles[i]);
  2136. BOOST_FOREACH(const int3 &tile, tiles[i])
  2137. {
  2138. if(cb->getPathInfo(tile)->reachable() && isSafeToVisit(h, tile) && howManyTilesWillBeDiscovered(tile, radius) && !isBlockedBorderGate(tile))
  2139. {
  2140. return tile;
  2141. }
  2142. }
  2143. }
  2144. throw cannotFulfillGoalException("No accessible tile will bring discoveries!");
  2145. }
  2146. TResources VCAI::estimateIncome() const
  2147. {
  2148. TResources ret;
  2149. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2150. {
  2151. ret[Res::GOLD] += t->dailyIncome();
  2152. //TODO duplikuje newturn
  2153. if(t->hasBuilt(EBuilding::RESOURCE_SILO)) //there is resource silo
  2154. {
  2155. if(t->town->primaryRes == 127) //we'll give wood and ore
  2156. {
  2157. ret[Res::WOOD] ++;
  2158. ret[Res::ORE] ++;
  2159. }
  2160. else
  2161. {
  2162. ret[t->town->primaryRes] ++;
  2163. }
  2164. }
  2165. }
  2166. BOOST_FOREACH(const CGObjectInstance *obj, getFlaggedObjects())
  2167. {
  2168. if(obj->ID == Obj::MINE)
  2169. {
  2170. switch(obj->subID)
  2171. {
  2172. case Res::WOOD:
  2173. case Res::ORE:
  2174. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  2175. break;
  2176. case Res::GOLD:
  2177. case 7: //abandoned mine -> also gold
  2178. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  2179. break;
  2180. default:
  2181. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  2182. break;
  2183. }
  2184. }
  2185. }
  2186. return ret;
  2187. }
  2188. bool VCAI::containsSavedRes(const TResources &cost) const
  2189. {
  2190. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  2191. {
  2192. if(saving[i] && cost[i])
  2193. return true;
  2194. }
  2195. return false;
  2196. }
  2197. void VCAI::checkHeroArmy (HeroPtr h)
  2198. {
  2199. auto it = lockedHeroes.find(h);
  2200. if (it != lockedHeroes.end())
  2201. {
  2202. if (it->second.goalType == GATHER_ARMY && it->second.value <= h->getArmyStrength())
  2203. completeGoal(CGoal (GATHER_ARMY).sethero(h));
  2204. }
  2205. }
  2206. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2207. {
  2208. BNLOG("Trying to recruit a hero in %s at %s", t->name % t->visitablePos())
  2209. if(auto availableHero = frontOrNull(cb->getAvailableHeroes(t)))
  2210. cb->recruitHero(t, availableHero);
  2211. else if(throwing)
  2212. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2213. }
  2214. void VCAI::finish()
  2215. {
  2216. if(makingTurn)
  2217. makingTurn->interrupt();
  2218. }
  2219. void VCAI::requestActionASAP(boost::function<void()> whatToDo)
  2220. {
  2221. // static boost::mutex m;
  2222. // boost::unique_lock<boost::mutex> mylock(m);
  2223. boost::barrier b(2);
  2224. boost::thread newThread([&b,this,whatToDo]()
  2225. {
  2226. setThreadName("VCAI::requestActionASAP::helper");
  2227. SET_GLOBAL_STATE(this);
  2228. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  2229. b.wait();
  2230. whatToDo();
  2231. });
  2232. b.wait();
  2233. }
  2234. void VCAI::lostHero(HeroPtr h)
  2235. {
  2236. BNLOG("I lost my hero %s. It's best to forget and move on.\n", h.name);
  2237. remove_if_present(lockedHeroes, h);
  2238. BOOST_FOREACH(auto obj, reservedHeroesMap[h])
  2239. {
  2240. remove_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2241. }
  2242. remove_if_present(reservedHeroesMap, h);
  2243. }
  2244. void VCAI::answerQuery(int queryID, int selection)
  2245. {
  2246. BNLOG("I'll answer the query %d giving the choice %d", queryID % selection);
  2247. if(queryID != -1)
  2248. {
  2249. cb->selectionMade(selection, queryID);
  2250. }
  2251. else
  2252. {
  2253. BNLOG("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  2254. //do nothing
  2255. }
  2256. }
  2257. void VCAI::requestSent(const CPackForServer *pack, int requestID)
  2258. {
  2259. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2260. if(auto reply = dynamic_cast<const QueryReply*>(pack))
  2261. {
  2262. status.attemptedAnsweringQuery(reply->qid, requestID);
  2263. }
  2264. }
  2265. std::string VCAI::getBattleAIName() const
  2266. {
  2267. if(settings["server"]["neutralAI"].getType() == JsonNode::DATA_STRING)
  2268. return settings["server"]["neutralAI"].String();
  2269. else
  2270. return "StupidAI";
  2271. }
  2272. AIStatus::AIStatus()
  2273. {
  2274. battle = NO_BATTLE;
  2275. havingTurn = false;
  2276. }
  2277. AIStatus::~AIStatus()
  2278. {
  2279. }
  2280. void AIStatus::setBattle(BattleState BS)
  2281. {
  2282. boost::unique_lock<boost::mutex> lock(mx);
  2283. battle = BS;
  2284. cv.notify_all();
  2285. }
  2286. BattleState AIStatus::getBattle()
  2287. {
  2288. boost::unique_lock<boost::mutex> lock(mx);
  2289. return battle;
  2290. }
  2291. void AIStatus::addQuery(int ID, std::string description)
  2292. {
  2293. boost::unique_lock<boost::mutex> lock(mx);
  2294. if(ID == -1)
  2295. {
  2296. BNLOG("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID % description);
  2297. return;
  2298. }
  2299. assert(!vstd::contains(remainingQueries, ID));
  2300. assert(ID >= 0);
  2301. remainingQueries[ID] = description;
  2302. cv.notify_all();
  2303. BNLOG("Adding query %d - %s. Total queries count: %d", ID % description % remainingQueries.size());
  2304. }
  2305. void AIStatus::removeQuery(int ID)
  2306. {
  2307. boost::unique_lock<boost::mutex> lock(mx);
  2308. assert(vstd::contains(remainingQueries, ID));
  2309. std::string description = remainingQueries[ID];
  2310. remainingQueries.erase(ID);
  2311. cv.notify_all();
  2312. BNLOG("Removing query %d - %s. Total queries count: %d", ID % description % remainingQueries.size());
  2313. }
  2314. int AIStatus::getQueriesCount()
  2315. {
  2316. boost::unique_lock<boost::mutex> lock(mx);
  2317. return remainingQueries.size();
  2318. }
  2319. void AIStatus::startedTurn()
  2320. {
  2321. boost::unique_lock<boost::mutex> lock(mx);
  2322. havingTurn = true;
  2323. cv.notify_all();
  2324. }
  2325. void AIStatus::madeTurn()
  2326. {
  2327. boost::unique_lock<boost::mutex> lock(mx);
  2328. havingTurn = false;
  2329. cv.notify_all();
  2330. }
  2331. void AIStatus::waitTillFree()
  2332. {
  2333. boost::unique_lock<boost::mutex> lock(mx);
  2334. while(battle != NO_BATTLE || remainingQueries.size())
  2335. cv.wait(lock);
  2336. }
  2337. bool AIStatus::haveTurn()
  2338. {
  2339. boost::unique_lock<boost::mutex> lock(mx);
  2340. return havingTurn;
  2341. }
  2342. void AIStatus::attemptedAnsweringQuery(int queryID, int answerRequestID)
  2343. {
  2344. boost::unique_lock<boost::mutex> lock(mx);
  2345. assert(vstd::contains(remainingQueries, queryID));
  2346. std::string description = remainingQueries[queryID];
  2347. BNLOG("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID % description % answerRequestID);
  2348. requestToQueryID[answerRequestID] = queryID;
  2349. }
  2350. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2351. {
  2352. assert(vstd::contains(requestToQueryID, answerRequestID));
  2353. int query = requestToQueryID[answerRequestID];
  2354. assert(vstd::contains(remainingQueries, query));
  2355. requestToQueryID.erase(answerRequestID);
  2356. if(result)
  2357. {
  2358. removeQuery(query);
  2359. }
  2360. else
  2361. {
  2362. tlog1 << "Something went really wrong, failed to answer query " << query << ": " << remainingQueries[query];
  2363. //TODO safely retry
  2364. }
  2365. }
  2366. int3 whereToExplore(HeroPtr h)
  2367. {
  2368. //TODO it's stupid and ineffective, write sth better
  2369. cb->setSelection(*h);
  2370. int radius = h->getSightRadious();
  2371. int3 hpos = h->visitablePos();
  2372. //look for nearby objs -> visit them if they're close enouh
  2373. const int DIST_LIMIT = 3;
  2374. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  2375. BOOST_FOREACH(const CGObjectInstance *obj, ai->getPossibleDestinations(h))
  2376. {
  2377. int3 op = obj->visitablePos();
  2378. CGPath p;
  2379. cb->getPath2(op, p);
  2380. if(p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  2381. nearbyVisitableObjs.push_back(obj);
  2382. }
  2383. boost::sort(nearbyVisitableObjs, isCloser);
  2384. if(nearbyVisitableObjs.size())
  2385. return nearbyVisitableObjs.back()->visitablePos();
  2386. try
  2387. {
  2388. return ai->explorationBestNeighbour(hpos, radius, h);
  2389. }
  2390. catch(cannotFulfillGoalException &e)
  2391. {
  2392. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow]
  2393. try
  2394. {
  2395. return ai->explorationNewPoint(radius, h, tiles);
  2396. }
  2397. catch(cannotFulfillGoalException &e)
  2398. {
  2399. std::map<int, std::vector<int3> > profits;
  2400. {
  2401. TimeCheck tc("Evaluating exploration possibilities");
  2402. tiles[0].clear(); //we can't reach FoW anyway
  2403. BOOST_FOREACH(auto &vt, tiles)
  2404. BOOST_FOREACH(auto &tile, vt)
  2405. profits[howManyTilesWillBeDiscovered(tile, radius)].push_back(tile);
  2406. }
  2407. if(profits.empty())
  2408. return int3 (-1,-1,-1);
  2409. auto bestDest = profits.end();
  2410. bestDest--;
  2411. return bestDest->second.front(); //TODO which is the real best tile?
  2412. }
  2413. }
  2414. }
  2415. TSubgoal CGoal::whatToDoToAchieve()
  2416. {
  2417. BNLOG("Decomposing goal of type %s", name());
  2418. INDENT;
  2419. switch(goalType)
  2420. {
  2421. case WIN:
  2422. {
  2423. const VictoryCondition &vc = cb->getMapHeader()->victoryCondition;
  2424. EVictoryConditionType::EVictoryConditionType cond = vc.condition;
  2425. if(!vc.appliesToAI)
  2426. {
  2427. //TODO deduce victory from human loss condition
  2428. cond = EVictoryConditionType::WINSTANDARD;
  2429. }
  2430. switch(cond)
  2431. {
  2432. case EVictoryConditionType::ARTIFACT:
  2433. return CGoal(GET_ART_TYPE).setaid(vc.objectId);
  2434. case EVictoryConditionType::BEATHERO:
  2435. return CGoal(GET_OBJ).setobjid(vc.obj->id);
  2436. case EVictoryConditionType::BEATMONSTER:
  2437. return CGoal(GET_OBJ).setobjid(vc.obj->id);
  2438. case EVictoryConditionType::BUILDCITY:
  2439. //TODO build castle/capitol
  2440. break;
  2441. case EVictoryConditionType::BUILDGRAIL:
  2442. {
  2443. if(auto h = ai->getHeroWithGrail())
  2444. {
  2445. //hero is in a town that can host Grail
  2446. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, EBuilding::GRAIL))
  2447. {
  2448. const CGTownInstance *t = h->visitedTown;
  2449. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::GRAIL).settown(t);
  2450. }
  2451. else
  2452. {
  2453. auto towns = cb->getTownsInfo();
  2454. towns.erase(boost::remove_if(towns,
  2455. [](const CGTownInstance *t) -> bool
  2456. {
  2457. return vstd::contains(t->forbiddenBuildings, EBuilding::GRAIL);
  2458. }),
  2459. towns.end());
  2460. boost::sort(towns, isCloser);
  2461. if(towns.size())
  2462. {
  2463. return CGoal(VISIT_TILE).sethero(h).settile(towns.front()->visitablePos());
  2464. }
  2465. }
  2466. }
  2467. double ratio = 0;
  2468. int3 grailPos = cb->getGrailPos(ratio);
  2469. if(ratio > 0.99)
  2470. {
  2471. return CGoal(DIG_AT_TILE).settile(grailPos);
  2472. } //TODO: use FIND_OBJ
  2473. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  2474. {
  2475. return CGoal(GET_OBJ).setobjid(obj->id);
  2476. }
  2477. else
  2478. return CGoal(EXPLORE);
  2479. }
  2480. break;
  2481. case EVictoryConditionType::CAPTURECITY:
  2482. return CGoal(GET_OBJ).setobjid(vc.obj->id);
  2483. case EVictoryConditionType::GATHERRESOURCE:
  2484. return CGoal(COLLECT_RES).setresID(static_cast<Res::ERes>(vc.objectId)).setvalue(vc.count);
  2485. //TODO mines? piles? marketplace?
  2486. //save?
  2487. break;
  2488. case EVictoryConditionType::GATHERTROOP:
  2489. return CGoal(GATHER_TROOPS).setobjid(vc.objectId).setvalue(vc.count);
  2490. break;
  2491. case EVictoryConditionType::TAKEDWELLINGS:
  2492. break;
  2493. case EVictoryConditionType::TAKEMINES:
  2494. break;
  2495. case EVictoryConditionType::TRANSPORTITEM:
  2496. break;
  2497. case EVictoryConditionType::WINSTANDARD:
  2498. return CGoal(CONQUER);
  2499. default:
  2500. assert(0);
  2501. }
  2502. }
  2503. break;
  2504. case FIND_OBJ:
  2505. {
  2506. const CGObjectInstance * o = NULL;
  2507. if (resID > -1) //specified
  2508. {
  2509. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  2510. {
  2511. if(obj->ID == objid && obj->subID == resID)
  2512. {
  2513. o = obj;
  2514. break; //TODO: consider multiple objects and choose best
  2515. }
  2516. }
  2517. }
  2518. else
  2519. {
  2520. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  2521. {
  2522. if(obj->ID == objid)
  2523. {
  2524. o = obj;
  2525. break; //TODO: consider multiple objects and choose best
  2526. }
  2527. }
  2528. }
  2529. if (o && isReachable(o))
  2530. return CGoal(GET_OBJ).setobjid(o->id);
  2531. else
  2532. return CGoal(EXPLORE);
  2533. }
  2534. break;
  2535. case GET_OBJ:
  2536. {
  2537. const CGObjectInstance * obj = cb->getObj(objid);
  2538. if(!obj)
  2539. return CGoal(EXPLORE);
  2540. int3 pos = obj->visitablePos();
  2541. return CGoal(VISIT_TILE).settile(pos);
  2542. }
  2543. break;
  2544. case VISIT_HERO:
  2545. {
  2546. const CGObjectInstance * obj = cb->getObj(objid);
  2547. if(!obj)
  2548. return CGoal(EXPLORE);
  2549. int3 pos = obj->visitablePos();
  2550. if (hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  2551. return CGoal(*this).settile(pos).setisElementar(true);
  2552. }
  2553. break;
  2554. case GET_ART_TYPE:
  2555. {
  2556. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  2557. if(alternativeWay.invalid())
  2558. return CGoal(FIND_OBJ).setobjid(Obj::ARTIFACT).setresID(aid);
  2559. }
  2560. break;
  2561. case CLEAR_WAY_TO:
  2562. {
  2563. assert(tile.x >= 0); //set tile
  2564. if(!cb->isVisible(tile))
  2565. {
  2566. tlog1 << "Clear way should be used with visible tiles!\n";
  2567. return CGoal(EXPLORE);
  2568. }
  2569. HeroPtr h = hero ? hero : ai->primaryHero();
  2570. if(!h)
  2571. return CGoal(RECRUIT_HERO);
  2572. cb->setSelection(*h);
  2573. SectorMap sm;
  2574. bool dropToFile = false;
  2575. if(dropToFile) //for debug purposes
  2576. sm.write("test.txt");
  2577. int3 tileToHit = sm.firstTileToGet(h, tile);
  2578. //if(isSafeToVisit(h, tileToHit))
  2579. if(isBlockedBorderGate(tileToHit))
  2580. { //FIXME: this way we'll not visit gate and activate quest :?
  2581. return CGoal(FIND_OBJ).setobjid(Obj::KEYMASTER).setresID(cb->getTile(tileToHit)->visitableObjects.back()->subID);
  2582. }
  2583. //FIXME: this code shouldn't be necessary
  2584. if(tileToHit == tile)
  2585. {
  2586. tlog1 << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  2587. % tileToHit % tile % h->name % h->visitablePos();
  2588. throw cannotFulfillGoalException("Retrieving first tile to hit failed (probably)!");
  2589. }
  2590. auto topObj = backOrNull(cb->getVisitableObjs(tileToHit));
  2591. if(topObj && topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  2592. {
  2593. std::string problem = boost::str(boost::format("%s stands in the way of %s.\n") % topObj->getHoverText() % h->getHoverText());
  2594. throw cannotFulfillGoalException(problem);
  2595. }
  2596. return CGoal(VISIT_TILE).settile(tileToHit).sethero(h); //FIXME:: attempts to visit completely unreachable tile with hero results in stall
  2597. //TODO czy istnieje lepsza droga?
  2598. }
  2599. throw cannotFulfillGoalException("Cannot reach given tile!");
  2600. case EXPLORE:
  2601. {
  2602. auto objs = ai->visitableObjs; //try to use buildings that uncover map
  2603. erase_if(objs, [&](const CGObjectInstance *obj) -> bool
  2604. {
  2605. if (vstd::contains(ai->alreadyVisited, obj))
  2606. return true;
  2607. switch (obj->ID)
  2608. {
  2609. case Obj::REDWOOD_OBSERVATORY:
  2610. case Obj::PILLAR_OF_FIRE:
  2611. case Obj::CARTOGRAPHER:
  2612. case Obj::SUBTERRANEAN_GATE: //TODO: check ai->knownSubterraneanGates
  2613. //case Obj::MONOLITH1:
  2614. //case obj::MONOLITH2:
  2615. //case obj::MONOLITH3:
  2616. //case Obj::WHIRLPOOL:
  2617. return false; //do not erase
  2618. break;
  2619. default:
  2620. return true;
  2621. }
  2622. });
  2623. if (objs.size())
  2624. {
  2625. if (hero.get(true))
  2626. {
  2627. BOOST_FOREACH (auto obj, objs)
  2628. {
  2629. auto pos = obj->visitablePos();
  2630. //FIXME: this confition fails if everything but guarded subterranen gate was explored. in this case we should gather army for hero
  2631. if (isSafeToVisit(hero, pos) && ai->isAccessibleForHero(pos, hero))
  2632. return CGoal(VISIT_TILE).settile(pos).sethero(hero);
  2633. }
  2634. }
  2635. else
  2636. {
  2637. BOOST_FOREACH (auto obj, objs)
  2638. {
  2639. auto pos = obj->visitablePos();
  2640. if (ai->isAccessible (pos)) //TODO: check safety?
  2641. return CGoal(VISIT_TILE).settile(pos).sethero(hero);
  2642. }
  2643. }
  2644. }
  2645. if (hero)
  2646. {
  2647. int3 t = whereToExplore(hero);
  2648. if (t.z == -1) //no safe tile to explore - we need to break!
  2649. {
  2650. erase_if (objs, [&](const CGObjectInstance *obj) -> bool
  2651. {
  2652. switch (obj->ID)
  2653. {
  2654. case Obj::CARTOGRAPHER:
  2655. case Obj::SUBTERRANEAN_GATE:
  2656. //case Obj::MONOLITH1:
  2657. //case obj::MONOLITH2:
  2658. //case obj::MONOLITH3:
  2659. //case Obj::WHIRLPOOL:
  2660. return false; //do not erase
  2661. break;
  2662. default:
  2663. return true;
  2664. }
  2665. });
  2666. if (objs.size())
  2667. {
  2668. return CGoal (VISIT_TILE).settile(objs.front()->visitablePos()).sethero(hero).setisAbstract(true);
  2669. }
  2670. else
  2671. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  2672. }
  2673. return CGoal(VISIT_TILE).settile(t).sethero(hero);
  2674. }
  2675. auto hs = cb->getHeroesInfo();
  2676. int howManyHeroes = hs.size();
  2677. erase(hs, [](const CGHeroInstance *h)
  2678. {
  2679. return contains(ai->lockedHeroes, h);
  2680. });
  2681. if(hs.empty()) //all heroes are busy. buy new one
  2682. {
  2683. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2684. return CGoal(RECRUIT_HERO);
  2685. else //find mobile hero with weakest army
  2686. {
  2687. hs = cb->getHeroesInfo();
  2688. erase_if(hs, [](const CGHeroInstance *h)
  2689. {
  2690. return !h->movement; //only hero with movement are of interest for us
  2691. });
  2692. if (hs.empty())
  2693. {
  2694. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2695. return CGoal(RECRUIT_HERO);
  2696. else
  2697. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2698. }
  2699. boost::sort(hs, compareMovement); //closer to what?
  2700. }
  2701. }
  2702. const CGHeroInstance *h = hs.front();
  2703. return (*this).sethero(h).setisAbstract(true);
  2704. }
  2705. I_AM_ELEMENTAR;
  2706. case RECRUIT_HERO:
  2707. {
  2708. const CGTownInstance *t = ai->findTownWithTavern();
  2709. if(!t)
  2710. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::TAVERN);
  2711. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  2712. return CGoal(COLLECT_RES).setresID(Res::GOLD).setvalue(HERO_GOLD_COST);
  2713. I_AM_ELEMENTAR;
  2714. }
  2715. break;
  2716. case VISIT_TILE:
  2717. {
  2718. if(!cb->isVisible(tile))
  2719. return CGoal(EXPLORE);
  2720. if(hero && !ai->isAccessibleForHero(tile, hero))
  2721. hero = NULL;
  2722. if(!hero)
  2723. {
  2724. if(cb->getHeroesInfo().empty())
  2725. {
  2726. return CGoal(RECRUIT_HERO);
  2727. }
  2728. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  2729. {
  2730. if(ai->isAccessibleForHero(tile, h))
  2731. {
  2732. hero = h;
  2733. break;
  2734. }
  2735. }
  2736. }
  2737. if(hero)
  2738. {
  2739. if(isSafeToVisit(hero, tile))
  2740. return CGoal(*this).setisElementar(true);
  2741. else
  2742. {
  2743. return CGoal(GATHER_ARMY).sethero(hero).setvalue(evaluateDanger(tile, *hero) * SAFE_ATTACK_CONSTANT); //TODO: should it be abstract?
  2744. }
  2745. }
  2746. else //inaccessible for all heroes
  2747. {
  2748. return CGoal(CLEAR_WAY_TO).settile(tile);
  2749. }
  2750. }
  2751. break;
  2752. case DIG_AT_TILE:
  2753. {
  2754. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  2755. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  2756. {
  2757. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  2758. return CGoal(*this).sethero(h).setisElementar(true);
  2759. }
  2760. return CGoal(VISIT_TILE).settile(tile);
  2761. }
  2762. break;
  2763. case BUILD_STRUCTURE:
  2764. //TODO check res
  2765. //look for town
  2766. //prerequisites?
  2767. I_AM_ELEMENTAR;
  2768. case COLLECT_RES:
  2769. {
  2770. std::vector<const IMarket*> markets;
  2771. std::vector<const CGObjectInstance*> visObjs;
  2772. ai->retreiveVisitableObjs(visObjs, true);
  2773. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  2774. {
  2775. if(const IMarket *m = IMarket::castFrom(obj, false))
  2776. {
  2777. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  2778. markets.push_back(m);
  2779. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  2780. markets.push_back(m);
  2781. }
  2782. }
  2783. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  2784. {
  2785. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  2786. });
  2787. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  2788. {
  2789. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  2790. && !ai->isAccessible(market->o->visitablePos());
  2791. }),markets.end());
  2792. if(!markets.size())
  2793. {
  2794. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2795. {
  2796. if(cb->canBuildStructure(t, EBuilding::MARKETPLACE) == EBuildingState::ALLOWED)
  2797. return CGoal(BUILD_STRUCTURE).settown(t).setbid(EBuilding::MARKETPLACE);
  2798. }
  2799. }
  2800. else
  2801. {
  2802. const IMarket *m = markets.back();
  2803. //attempt trade at back (best prices)
  2804. int howManyCanWeBuy = 0;
  2805. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  2806. {
  2807. if(i == resID) continue;
  2808. int toGive = -1, toReceive = -1;
  2809. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  2810. assert(toGive > 0 && toReceive > 0);
  2811. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  2812. }
  2813. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  2814. {
  2815. auto backObj = backOrNull(cb->getVisitableObjs(m->o->visitablePos())); //it'll be a hero if we have one there; otherwise marketplace
  2816. assert(backObj);
  2817. if(backObj->tempOwner != ai->playerID)
  2818. return CGoal(GET_OBJ).setobjid(m->o->id);
  2819. return setobjid(m->o->id).setisElementar(true);
  2820. }
  2821. }
  2822. }
  2823. return CGoal(INVALID);
  2824. case GATHER_TROOPS:
  2825. {
  2826. std::vector<const CGDwelling *> dwellings;
  2827. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2828. {
  2829. auto creature = VLC->creh->creatures[objid];
  2830. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  2831. {
  2832. auto creatures = t->town->creatures[creature->level];
  2833. int upgradeNumber = std::find(creatures.begin(), creatures.end(), creature->idNumber) - creatures.begin();
  2834. int bid = EBuilding::DWELL_FIRST + creature->level + upgradeNumber * GameConstants::CREATURES_PER_TOWN;
  2835. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  2836. {
  2837. dwellings.push_back(t);
  2838. }
  2839. else
  2840. {
  2841. return CGoal (BUILD_STRUCTURE).settown(t).setbid(bid);
  2842. }
  2843. }
  2844. }
  2845. BOOST_FOREACH (auto obj, ai->visitableObjs)
  2846. {
  2847. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  2848. continue;
  2849. auto d = dynamic_cast<const CGDwelling *>(obj);
  2850. BOOST_FOREACH (auto creature, d->creatures)
  2851. {
  2852. if (creature.first) //there are more than 0 creatures avaliabe
  2853. {
  2854. BOOST_FOREACH (auto type, creature.second)
  2855. {
  2856. if (type == objid)
  2857. dwellings.push_back(d);
  2858. }
  2859. }
  2860. }
  2861. }
  2862. if (dwellings.size())
  2863. {
  2864. boost::sort(dwellings, isCloser);
  2865. return CGoal(GET_OBJ).setobjid (dwellings.front()->id); //TODO: consider needed resources
  2866. }
  2867. else
  2868. return CGoal(EXPLORE);
  2869. //TODO: exchange troops between heroes
  2870. }
  2871. break;
  2872. case CONQUER: //TODO: put it into a function?
  2873. {
  2874. auto hs = cb->getHeroesInfo();
  2875. int howManyHeroes = hs.size();
  2876. erase(hs, [](const CGHeroInstance *h)
  2877. {
  2878. return contains(ai->lockedHeroes, h);
  2879. });
  2880. if(hs.empty()) //all heroes are busy. buy new one
  2881. {
  2882. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2883. return CGoal(RECRUIT_HERO);
  2884. else //find mobile hero with weakest army
  2885. {
  2886. hs = cb->getHeroesInfo();
  2887. erase_if(hs, [](const CGHeroInstance *h)
  2888. {
  2889. return !h->movement; //only hero with movement are of interest for us
  2890. });
  2891. if (hs.empty())
  2892. {
  2893. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2894. return CGoal(RECRUIT_HERO);
  2895. else
  2896. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2897. }
  2898. boost::sort(hs, compareHeroStrength);
  2899. }
  2900. }
  2901. const CGHeroInstance *h = hs.back();
  2902. cb->setSelection(h);
  2903. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  2904. ai->retreiveVisitableObjs(objs);
  2905. erase_if(objs, [&](const CGObjectInstance *obj)
  2906. {
  2907. return (obj->ID != Obj::TOWN && obj->ID != Obj::HERO) //not town/hero
  2908. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES;
  2909. });
  2910. if (objs.empty()) //experiment - try to conquer dwellings and mines, it should pay off
  2911. {
  2912. ai->retreiveVisitableObjs(objs);
  2913. erase_if(objs, [&](const CGObjectInstance *obj)
  2914. {
  2915. return (obj->ID != Obj::CREATURE_GENERATOR1 && obj->ID != Obj::MINE) //not dwelling or mine
  2916. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES;
  2917. });
  2918. }
  2919. if(objs.empty())
  2920. return CGoal(EXPLORE); //we need to find an enemy
  2921. erase_if(objs, [&](const CGObjectInstance *obj)
  2922. {
  2923. return !isSafeToVisit(h, obj->visitablePos()) || vstd::contains (ai->reservedObjs, obj); //no need to capture same object twice
  2924. });
  2925. if(objs.empty())
  2926. I_AM_ELEMENTAR;
  2927. boost::sort(objs, isCloser);
  2928. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  2929. {
  2930. if (ai->isAccessibleForHero(obj->visitablePos(), h))
  2931. {
  2932. ai->reserveObject(h, obj); //no one else will capture same object until we fail
  2933. if (obj->ID == Obj::HERO)
  2934. return CGoal(VISIT_HERO).sethero(h).setobjid(obj->id).setisAbstract(true); //track enemy hero
  2935. else
  2936. return CGoal(VISIT_TILE).sethero(h).settile(obj->visitablePos());
  2937. }
  2938. }
  2939. return CGoal(EXPLORE); //enemy is inaccessible
  2940. }
  2941. break;
  2942. case BUILD:
  2943. I_AM_ELEMENTAR;
  2944. case INVALID:
  2945. I_AM_ELEMENTAR;
  2946. case GATHER_ARMY:
  2947. {
  2948. //TODO: find hero if none set
  2949. assert(hero);
  2950. cb->setSelection(*hero);
  2951. auto compareReinforcements = [this](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  2952. {
  2953. return howManyReinforcementsCanGet(hero, lhs) < howManyReinforcementsCanGet(hero, rhs);
  2954. };
  2955. std::vector<const CGTownInstance *> townsReachable;
  2956. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2957. {
  2958. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  2959. {
  2960. if(isReachable(t) && !vstd::contains (ai->townVisitsThisWeek[hero], t))
  2961. townsReachable.push_back(t);
  2962. }
  2963. }
  2964. if(townsReachable.size()) //try towns first
  2965. {
  2966. boost::sort(townsReachable, compareReinforcements);
  2967. return CGoal(VISIT_TILE).sethero(hero).settile(townsReachable.back()->visitablePos());
  2968. }
  2969. else
  2970. {
  2971. if (hero == ai->primaryHero()) //we can get army from other heroes
  2972. {
  2973. auto otherHeroes = cb->getHeroesInfo();
  2974. auto heroDummy = hero;
  2975. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  2976. {
  2977. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true) || !ai->canGetArmy(heroDummy.h, h));
  2978. });
  2979. if (otherHeroes.size())
  2980. {
  2981. boost::sort(otherHeroes, compareArmyStrength); //TODO: check if hero has at least one stack more powerful than ours? not likely to fail
  2982. int primaryPath, secondaryPath;
  2983. auto h = otherHeroes.back();
  2984. cb->setSelection(hero.h);
  2985. primaryPath = cb->getPathInfo(h->visitablePos())->turns;
  2986. cb->setSelection(h);
  2987. secondaryPath = cb->getPathInfo(hero->visitablePos())->turns;
  2988. if (primaryPath < secondaryPath)
  2989. return CGoal(VISIT_HERO).setisAbstract(true).setobjid(h->id).sethero(hero); //go to the other hero if we are faster
  2990. else
  2991. return CGoal(VISIT_HERO).setisAbstract(true).setobjid(hero->id).sethero(h); //let the other hero come to us
  2992. }
  2993. }
  2994. std::vector<const CGObjectInstance *> objs; //here we'll gather all dwellings
  2995. ai->retreiveVisitableObjs(objs);
  2996. erase_if(objs, [&](const CGObjectInstance *obj)
  2997. {
  2998. return (obj->ID != Obj::CREATURE_GENERATOR1);
  2999. });
  3000. if(objs.empty()) //no possible objects, we did eveyrthing already
  3001. return CGoal(EXPLORE).sethero(hero);
  3002. //TODO: check if we can recruit any creatures there, evaluate army
  3003. else
  3004. {
  3005. boost::sort(objs, isCloser);
  3006. HeroPtr h = NULL;
  3007. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  3008. { //find safe dwelling
  3009. auto pos = obj->visitablePos();
  3010. if (shouldVisit (hero, obj)) //creatures fit in army
  3011. h = hero;
  3012. else
  3013. {
  3014. BOOST_FOREACH(auto ourHero, cb->getHeroesInfo()) //make use of multiple heroes
  3015. {
  3016. if (shouldVisit(ourHero, obj))
  3017. h = ourHero;
  3018. }
  3019. }
  3020. if (h && isSafeToVisit(h, pos) && ai->isAccessibleForHero(pos, h))
  3021. return CGoal(VISIT_TILE).sethero(h).settile(pos);
  3022. }
  3023. }
  3024. }
  3025. return CGoal(EXPLORE).sethero(hero); //find dwelling. use current hero to prevent him from doing nothing.
  3026. }
  3027. break;
  3028. default:
  3029. assert(0);
  3030. }
  3031. return CGoal(EXPLORE);
  3032. }
  3033. TSubgoal CGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  3034. {
  3035. if(obj)
  3036. return CGoal(GET_OBJ).setobjid(obj->id);
  3037. else
  3038. return CGoal(EXPLORE);
  3039. }
  3040. TSubgoal CGoal::lookForArtSmart(int aid)
  3041. {
  3042. return CGoal(INVALID);
  3043. }
  3044. bool CGoal::invalid() const
  3045. {
  3046. return goalType == INVALID;
  3047. }
  3048. bool isBlockedBorderGate(int3 tileToHit)
  3049. {
  3050. return cb->getTile(tileToHit)->topVisitableId() == Obj::BORDER_GATE
  3051. && cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
  3052. }
  3053. SectorMap::SectorMap()
  3054. {
  3055. // int3 sizes = cb->getMapSize();
  3056. // sector.resize(sizes.x);
  3057. // BOOST_FOREACH(auto &i, sector)
  3058. // i.resize(sizes.y);
  3059. //
  3060. // BOOST_FOREACH(auto &i, sector)
  3061. // BOOST_FOREACH(auto &j, i)
  3062. // j.resize(sizes.z, 0);
  3063. update();
  3064. }
  3065. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  3066. {
  3067. if(t->blocked && !t->visitable)
  3068. {
  3069. sec = NOT_AVAILABLE;
  3070. return true;
  3071. }
  3072. return false;
  3073. }
  3074. bool markIfBlocked(ui8 &sec, crint3 pos)
  3075. {
  3076. return markIfBlocked(sec, pos, cb->getTile(pos));
  3077. }
  3078. void SectorMap::update()
  3079. {
  3080. clear();
  3081. int curSector = 3; //0 is invisible, 1 is not explored
  3082. foreach_tile_pos([&](crint3 pos)
  3083. {
  3084. if(retreiveTile(pos) == NOT_CHECKED)
  3085. {
  3086. if(!markIfBlocked(retreiveTile(pos), pos))
  3087. exploreNewSector(pos, curSector++);
  3088. }
  3089. });
  3090. valid = true;
  3091. }
  3092. void SectorMap::clear()
  3093. {
  3094. sector = cb->getVisibilityMap();
  3095. valid = false;
  3096. }
  3097. bool canBeEmbarkmentPoint(const TerrainTile *t)
  3098. {
  3099. //tile must be free of with unoccupied boat
  3100. return !t->blocked
  3101. || (t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT);
  3102. }
  3103. void SectorMap::exploreNewSector(crint3 pos, int num)
  3104. {
  3105. Sector &s = infoOnSectors[num];
  3106. s.id = num;
  3107. s.water = cb->getTile(pos)->isWater();
  3108. std::queue<int3> toVisit;
  3109. toVisit.push(pos);
  3110. while(toVisit.size())
  3111. {
  3112. int3 curPos = toVisit.front();
  3113. toVisit.pop();
  3114. ui8 &sec = retreiveTile(curPos);
  3115. if(sec == NOT_CHECKED)
  3116. {
  3117. const TerrainTile *t = cb->getTile(curPos);
  3118. if(!markIfBlocked(sec, curPos, t))
  3119. {
  3120. if(t->isWater() == s.water) //sector is only-water or only-land
  3121. {
  3122. sec = num;
  3123. s.tiles.push_back(curPos);
  3124. foreach_neighbour(curPos, [&](crint3 neighPos)
  3125. {
  3126. if(retreiveTile(neighPos) == NOT_CHECKED)
  3127. {
  3128. toVisit.push(neighPos);
  3129. //parent[neighPos] = curPos;
  3130. }
  3131. const TerrainTile *nt = cb->getTile(neighPos, false);
  3132. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt))
  3133. {
  3134. s.embarkmentPoints.push_back(neighPos);
  3135. }
  3136. });
  3137. if(t->visitable && vstd::contains(ai->knownSubterraneanGates, t->visitableObjects.front()))
  3138. toVisit.push(ai->knownSubterraneanGates[t->visitableObjects.front()]->visitablePos());
  3139. }
  3140. }
  3141. }
  3142. }
  3143. removeDuplicates(s.embarkmentPoints);
  3144. }
  3145. void SectorMap::write(crstring fname)
  3146. {
  3147. std::ofstream out(fname);
  3148. for(int k = 0; k < cb->getMapSize().z; k++)
  3149. {
  3150. for(int j = 0; j < cb->getMapSize().y; j++)
  3151. {
  3152. for(int i = 0; i < cb->getMapSize().x; i++)
  3153. {
  3154. out << (int)sector[i][j][k] << '\t';
  3155. }
  3156. out << std::endl;
  3157. }
  3158. out << std::endl;
  3159. }
  3160. }
  3161. bool isWeeklyRevisitable (const CGObjectInstance * obj)
  3162. { //TODO: allow polling of remaining creatures in dwelling
  3163. if (dynamic_cast<const CGVisitableOPW *>(obj) || //ensures future compatibility, unlike IDs
  3164. dynamic_cast<const CGDwelling *>(obj) ||
  3165. dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  3166. return true;
  3167. switch (obj->ID)
  3168. {
  3169. case Obj::STABLES:
  3170. case Obj::MAGIC_WELL:
  3171. case Obj::HILL_FORT:
  3172. return true;
  3173. break;
  3174. case Obj::BORDER_GATE:
  3175. case Obj::BORDERGUARD:
  3176. return (dynamic_cast <const CGKeys *>(obj))->wasMyColorVisited (ai->playerID); //FIXME: they could be revisited sooner than in a week
  3177. break;
  3178. }
  3179. return false;
  3180. }
  3181. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  3182. {
  3183. switch (obj->ID)
  3184. {
  3185. case Obj::BORDERGUARD:
  3186. case Obj::BORDER_GATE:
  3187. {
  3188. BOOST_FOREACH (auto q, ai->myCb->getMyQuests())
  3189. {
  3190. if (q.obj == obj)
  3191. {
  3192. return false; // do not visit guards or gates when wandering
  3193. }
  3194. }
  3195. return true; //we don't have this quest yet
  3196. break;
  3197. }
  3198. case Obj::SEER_HUT:
  3199. case Obj::QUEST_GUARD:
  3200. {
  3201. BOOST_FOREACH (auto q, ai->myCb->getMyQuests())
  3202. {
  3203. if (q.obj == obj)
  3204. {
  3205. if (q.quest->checkQuest(*h))
  3206. return true; //we completed the quest
  3207. else
  3208. return false; //we can't complete this quest
  3209. }
  3210. }
  3211. return true; //we don't have this quest yet
  3212. break;
  3213. }
  3214. case Obj::CREATURE_GENERATOR1:
  3215. {
  3216. if (obj->tempOwner != h->tempOwner)
  3217. return true; //flag just in case
  3218. bool canRecruitCreatures = false;
  3219. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  3220. BOOST_FOREACH(auto level, d->creatures)
  3221. {
  3222. BOOST_FOREACH(auto c, level.second)
  3223. {
  3224. if (h->getSlotFor(c) != -1)
  3225. canRecruitCreatures = true;
  3226. }
  3227. }
  3228. return canRecruitCreatures;
  3229. break;
  3230. }
  3231. case Obj::HILL_FORT:
  3232. {
  3233. BOOST_FOREACH (auto slot, h->Slots())
  3234. {
  3235. if (slot.second->type->upgrades.size())
  3236. return true; //TODO: check price?
  3237. }
  3238. return false;
  3239. break;
  3240. }
  3241. case Obj::MONOLITH1:
  3242. case Obj::MONOLITH2:
  3243. case Obj::MONOLITH3:
  3244. case Obj::WHIRLPOOL:
  3245. //TODO: mechanism for handling monoliths
  3246. return false;
  3247. break;
  3248. case Obj::SCHOOL_OF_MAGIC:
  3249. case Obj::SCHOOL_OF_WAR:
  3250. {
  3251. TResources myRes = ai->myCb->getResourceAmount();
  3252. if (myRes[Res::GOLD] - GOLD_RESERVE < 1000)
  3253. return false;
  3254. }
  3255. break;
  3256. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  3257. if (h->level < 12)
  3258. return false;
  3259. break;
  3260. case Obj::TREE_OF_KNOWLEDGE:
  3261. {
  3262. TResources myRes = ai->myCb->getResourceAmount();
  3263. if (myRes[Res::GOLD] - GOLD_RESERVE < 2000 || myRes[Res::GEMS] < 10)
  3264. return false;
  3265. }
  3266. break;
  3267. case Obj::MAGIC_WELL:
  3268. return h->mana < h->manaLimit();
  3269. break;
  3270. case Obj::PRISON:
  3271. return ai->myCb->getHeroesInfo().size() < GameConstants::MAX_HEROES_PER_PLAYER;
  3272. break;
  3273. case Obj::BOAT:
  3274. return false;
  3275. //Boats are handled by pathfinder
  3276. }
  3277. if (obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  3278. return false;
  3279. return true;
  3280. }
  3281. int3 SectorMap::firstTileToGet(HeroPtr h, crint3 dst)
  3282. {
  3283. int sourceSector = retreiveTile(h->visitablePos()),
  3284. destinationSector = retreiveTile(dst);
  3285. if(sourceSector != destinationSector)
  3286. {
  3287. const Sector *src = &infoOnSectors[sourceSector],
  3288. *dst = &infoOnSectors[destinationSector];
  3289. std::map<const Sector*, const Sector*> preds;
  3290. std::queue<const Sector *> sq;
  3291. sq.push(src);
  3292. while(!sq.empty())
  3293. {
  3294. const Sector *s = sq.front();
  3295. sq.pop();
  3296. BOOST_FOREACH(int3 ep, s->embarkmentPoints)
  3297. {
  3298. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  3299. //preds[s].push_back(neigh);
  3300. if(!preds[neigh])
  3301. {
  3302. preds[neigh] = s;
  3303. sq.push(neigh);
  3304. }
  3305. }
  3306. //TODO consider other types of connections between sectors?
  3307. }
  3308. if(!preds[dst])
  3309. {
  3310. write("test.txt");
  3311. ai->completeGoal (CGoal(EXPLORE).sethero(h)); //if we can't find the way, seemingly all tiles were explored
  3312. //TODO: more organized way?
  3313. throw cannotFulfillGoalException(str(format("Cannot find connection between sectors %d and %d") % src->id % dst->id));
  3314. }
  3315. std::vector<const Sector*> toTraverse;
  3316. toTraverse.push_back(dst);
  3317. while(toTraverse.back() != src)
  3318. {
  3319. toTraverse.push_back(preds[toTraverse.back()]);
  3320. }
  3321. if(preds[dst])
  3322. {
  3323. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  3324. if(!src->water && sectorToReach->water) //embark
  3325. {
  3326. //embark on ship -> look for an EP with a boat
  3327. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  3328. {
  3329. const TerrainTile *t = cb->getTile(pos);
  3330. return t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT
  3331. && retreiveTile(pos) == sectorToReach->id;
  3332. });
  3333. if(firstEP != src->embarkmentPoints.end())
  3334. {
  3335. return *firstEP;
  3336. }
  3337. else
  3338. {
  3339. //we need to find a shipyard with an access to the desired sector's EP
  3340. //TODO what about Summon Boat spell?
  3341. std::vector<const IShipyard *> shipyards;
  3342. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  3343. {
  3344. if(t->hasBuilt(EBuilding::SHIPYARD))
  3345. shipyards.push_back(t);
  3346. }
  3347. std::vector<const CGObjectInstance*> visObjs;
  3348. ai->retreiveVisitableObjs(visObjs, true);
  3349. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  3350. {
  3351. if(obj->ID != Obj::TOWN) //towns were handled in the previous loop
  3352. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  3353. shipyards.push_back(shipyard);
  3354. }
  3355. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  3356. {
  3357. return shipyard->state() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  3358. }),shipyards.end());
  3359. if(!shipyards.size())
  3360. {
  3361. //TODO consider possibility of building shipyard in a town
  3362. throw cannotFulfillGoalException("There is no known shipyard!");
  3363. }
  3364. //we have only shipyards that possibly can build ships onto the appropriate EP
  3365. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  3366. {
  3367. return s->o->tempOwner == ai->playerID;
  3368. });
  3369. if(ownedGoodShipyard != shipyards.end())
  3370. {
  3371. const IShipyard *s = *ownedGoodShipyard;
  3372. TResources shipCost;
  3373. s->getBoatCost(shipCost);
  3374. if(cb->getResourceAmount().canAfford(shipCost))
  3375. {
  3376. int3 ret = s->bestLocation();
  3377. cb->buildBoat(s);
  3378. return ret;
  3379. }
  3380. else
  3381. {
  3382. //TODO gather res
  3383. throw cannotFulfillGoalException("Not enough resources to build a boat");
  3384. }
  3385. }
  3386. else
  3387. {
  3388. //TODO pick best shipyard to take over
  3389. return shipyards.front()->o->visitablePos();
  3390. }
  3391. }
  3392. }
  3393. else if(src->water && !sectorToReach->water)
  3394. {
  3395. //TODO
  3396. //disembark
  3397. }
  3398. else
  3399. {
  3400. //TODO
  3401. //transition between two land/water sectors. Monolith? Whirlpool? ...
  3402. throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  3403. }
  3404. }
  3405. else
  3406. {
  3407. throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  3408. }
  3409. }
  3410. else
  3411. {
  3412. makeParentBFS(h->visitablePos());
  3413. int3 curtile = dst;
  3414. while(curtile != h->visitablePos())
  3415. {
  3416. if(cb->getPathInfo(curtile)->reachable())
  3417. {
  3418. return curtile;
  3419. }
  3420. else
  3421. {
  3422. auto i = parent.find(curtile);
  3423. if(i != parent.end())
  3424. {
  3425. assert(curtile != i->second);
  3426. curtile = i->second;
  3427. }
  3428. else
  3429. throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  3430. }
  3431. }
  3432. }
  3433. throw cannotFulfillGoalException("Impossible happened.");
  3434. }
  3435. void SectorMap::makeParentBFS(crint3 source)
  3436. {
  3437. parent.clear();
  3438. int mySector = retreiveTile(source);
  3439. std::queue<int3> toVisit;
  3440. toVisit.push(source);
  3441. while(toVisit.size())
  3442. {
  3443. int3 curPos = toVisit.front();
  3444. toVisit.pop();
  3445. ui8 &sec = retreiveTile(curPos);
  3446. assert(sec == mySector); //consider only tiles from the same sector
  3447. //const TerrainTile *t = cb->getTile(curPos);
  3448. foreach_neighbour(curPos, [&](crint3 neighPos)
  3449. {
  3450. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  3451. {
  3452. toVisit.push(neighPos);
  3453. parent[neighPos] = curPos;
  3454. }
  3455. });
  3456. }
  3457. }
  3458. unsigned char & SectorMap::retreiveTile(crint3 pos)
  3459. {
  3460. return retreiveTileN(sector, pos);
  3461. }
  3462. const CGObjectInstance * ObjectIdRef::operator->() const
  3463. {
  3464. return cb->getObj(id, false);
  3465. }
  3466. ObjectIdRef::operator const CGObjectInstance*() const
  3467. {
  3468. return cb->getObj(id, false);
  3469. }
  3470. ObjectIdRef::ObjectIdRef(int _id) : id(_id)
  3471. {
  3472. }
  3473. ObjectIdRef::ObjectIdRef(const CGObjectInstance *obj) : id(obj->id)
  3474. {
  3475. }
  3476. bool ObjectIdRef::operator<(const ObjectIdRef &rhs) const
  3477. {
  3478. return id < rhs.id;
  3479. }
  3480. HeroPtr::HeroPtr(const CGHeroInstance *H)
  3481. {
  3482. if(!H)
  3483. {
  3484. //init from nullptr should equal to default init
  3485. *this = HeroPtr();
  3486. return;
  3487. }
  3488. h = H;
  3489. name = h->name;
  3490. hid = H->id;
  3491. // infosCount[ai->playerID][hid]++;
  3492. }
  3493. HeroPtr::HeroPtr()
  3494. {
  3495. h = nullptr;
  3496. hid = -1;
  3497. }
  3498. HeroPtr::~HeroPtr()
  3499. {
  3500. // if(hid >= 0)
  3501. // infosCount[ai->playerID][hid]--;
  3502. }
  3503. bool HeroPtr::operator<(const HeroPtr &rhs) const
  3504. {
  3505. return hid < rhs.hid;
  3506. }
  3507. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull /*= false*/) const
  3508. {
  3509. //TODO? check if these all assertions every time we get info about hero affect efficiency
  3510. //
  3511. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  3512. assert(doWeExpectNull || h);
  3513. if(h)
  3514. {
  3515. auto obj = cb->getObj(hid);
  3516. const bool owned = obj && obj->tempOwner == ai->playerID;
  3517. if(doWeExpectNull && !owned)
  3518. {
  3519. return nullptr;
  3520. }
  3521. else
  3522. {
  3523. assert(obj);
  3524. assert(owned);
  3525. }
  3526. }
  3527. return h;
  3528. }
  3529. const CGHeroInstance * HeroPtr::operator->() const
  3530. {
  3531. return get();
  3532. }
  3533. bool HeroPtr::validAndSet() const
  3534. {
  3535. return get(true);
  3536. }
  3537. const CGHeroInstance * HeroPtr::operator*() const
  3538. {
  3539. return get();
  3540. }