VCAI.cpp 102 KB

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