VCAI.cpp 112 KB

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