VCAI.cpp 93 KB

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