VCAI.cpp 79 KB

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