VCAI.cpp 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093
  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. if(vstd::contains(alreadyVisited, obj))
  1006. return true;
  1007. if(!isSafeToVisit(h, obj->visitablePos()))
  1008. return true;
  1009. if (!shouldVisit(h, obj))
  1010. return true;
  1011. if (vstd::contains(reservedObjs, obj)) //does checking for our own reserved objects make sense? here?
  1012. return true;
  1013. return false;
  1014. }),possibleDestinations.end());
  1015. return possibleDestinations;
  1016. }
  1017. void VCAI::wander(const CGHeroInstance * h)
  1018. {
  1019. while(1)
  1020. {
  1021. std::vector <ObjectIdRef> dests;
  1022. range::copy(reservedHeroesMap[h], std::back_inserter(dests));
  1023. if (!dests.size())
  1024. range::copy(getPossibleDestinations(h), std::back_inserter(dests));
  1025. if(!dests.size())
  1026. {
  1027. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  1028. {
  1029. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  1030. };
  1031. std::vector<const CGTownInstance *> townsReachable;
  1032. std::vector<const CGTownInstance *> townsNotReachable;
  1033. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1034. {
  1035. if(!t->visitingHero && howManyReinforcementsCanGet(h,t) && !vstd::contains(townVisitsThisWeek[h], t))
  1036. {
  1037. if(isReachable(t))
  1038. townsReachable.push_back(t);
  1039. else
  1040. townsNotReachable.push_back(t);
  1041. }
  1042. }
  1043. if(townsReachable.size())
  1044. {
  1045. boost::sort(townsReachable, compareReinforcements);
  1046. dests.emplace_back(townsReachable.back());
  1047. }
  1048. else if(townsNotReachable.size())
  1049. {
  1050. boost::sort(townsNotReachable, compareReinforcements);
  1051. //TODO pick the truly best
  1052. const CGTownInstance *t = townsNotReachable.back();
  1053. BNLOG("%s can't reach any town, we'll try to make our way to %s at %s", h->name % t->name % t->visitablePos());
  1054. int3 pos1 = h->pos;
  1055. striveToGoal(CGoal(CLEAR_WAY_TO).settile(t->visitablePos()).sethero(h));
  1056. if (pos1 == h->pos && h == primaryHero()) //hero can't move
  1057. {
  1058. if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST && cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES && cb->getAvailableHeroes(t).size())
  1059. recruitHero(t);
  1060. }
  1061. break;
  1062. }
  1063. else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST)
  1064. {
  1065. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1066. erase_if(towns, [](const CGTownInstance *t) -> bool
  1067. {
  1068. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1069. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1070. return true;
  1071. return false;
  1072. });
  1073. boost::sort(towns, compareArmyStrength);
  1074. if(towns.size())
  1075. recruitHero(towns.back());
  1076. break;
  1077. }
  1078. else
  1079. {
  1080. PNLOG("Nowhere more to go...\n");
  1081. break;
  1082. }
  1083. }
  1084. const ObjectIdRef&dest = dests.front();
  1085. if(!goVisitObj(dest, h))
  1086. {
  1087. if(!dest)
  1088. {
  1089. BNLOG("Visit attempt made the object (id=%d) gone...", dest.id);
  1090. }
  1091. else
  1092. {
  1093. BNLOG("Hero %s apparently used all MPs (%d left)\n", h->name % h->movement);
  1094. reserveObject(h, dest); //reserve that object - we predict it will be reached soon
  1095. //removed - do not forget abstract goal so easily
  1096. //setGoal(h, CGoal(VISIT_TILE).sethero(h).settile(dest->visitablePos()));
  1097. }
  1098. break;
  1099. }
  1100. if(h->visitedTown)
  1101. {
  1102. townVisitsThisWeek[h].push_back(h->visitedTown);
  1103. buildArmyIn(h->visitedTown);
  1104. break;
  1105. }
  1106. }
  1107. }
  1108. void VCAI::setGoal (const CGHeroInstance *h, const CGoal goal)
  1109. { //TODO: check for presence?
  1110. if (goal.goalType == EGoals::INVALID)
  1111. remove_if_present(lockedHeroes, h);
  1112. else
  1113. lockedHeroes[h] = CGoal(goal).setisElementar(false); //always evaluate goals before realizing
  1114. }
  1115. void VCAI::setGoal (const CGHeroInstance *h, EGoals goalType)
  1116. {
  1117. if (goalType == EGoals::INVALID)
  1118. remove_if_present(lockedHeroes, h);
  1119. else
  1120. lockedHeroes[h] = CGoal(goalType).setisElementar(false); //always evaluate goals before realizing;
  1121. }
  1122. void VCAI::completeGoal (const CGoal goal)
  1123. {
  1124. if (const CGHeroInstance * h = goal.hero)
  1125. {
  1126. auto it = lockedHeroes.find(h);
  1127. if (it != lockedHeroes.end())
  1128. if (it->second.goalType == goal.goalType)
  1129. lockedHeroes.erase(it); //goal fulfilled, free hero
  1130. }
  1131. }
  1132. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  1133. {
  1134. NET_EVENT_HANDLER;
  1135. assert(playerID > GameConstants::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1136. status.setBattle(ONGOING_BATTLE);
  1137. 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
  1138. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->hoverName : "unknown enemy") % tile);
  1139. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1140. }
  1141. void VCAI::battleEnd(const BattleResult *br)
  1142. {
  1143. NET_EVENT_HANDLER;
  1144. assert(status.getBattle() == ONGOING_BATTLE);
  1145. status.setBattle(ENDING_BATTLE);
  1146. bool won = br->winner == myCb->battleGetMySide();
  1147. BNLOG("Player %d: I %s the %s!", playerID % (won ? "won" : "lost") % battlename);
  1148. battlename.clear();
  1149. CAdventureAI::battleEnd(br);
  1150. }
  1151. void VCAI::waitTillFree()
  1152. {
  1153. auto unlock = vstd::makeUnlockSharedGuard(cb->getGsMutex());
  1154. status.waitTillFree();
  1155. }
  1156. void VCAI::markObjectVisited (const CGObjectInstance *obj)
  1157. {
  1158. if(dynamic_cast<const CGVisitableOPH *>(obj) || //we may want to wisit it with another hero
  1159. dynamic_cast<const CGBonusingObject *>(obj) || //or another time
  1160. (obj->ID == Obj::MONSTER))
  1161. return;
  1162. alreadyVisited.push_back(obj);
  1163. }
  1164. void VCAI::reserveObject (const CGHeroInstance * h, const CGObjectInstance *obj)
  1165. {
  1166. reservedObjs.push_back(obj);
  1167. reservedHeroesMap[h].push_back(obj);
  1168. }
  1169. void VCAI::validateVisitableObjs()
  1170. {
  1171. std::vector<const CGObjectInstance *> hlp;
  1172. retreiveVisitableObjs(hlp, true);
  1173. start:
  1174. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1175. if(!vstd::contains(hlp, obj))
  1176. {
  1177. tlog1 << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << " shouldn't be on list!\n";
  1178. remove_if_present(visitableObjs, obj);
  1179. goto start;
  1180. }
  1181. }
  1182. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1183. {
  1184. foreach_tile_pos([&](const int3 &pos)
  1185. {
  1186. BOOST_FOREACH(const CGObjectInstance *obj, cb->getVisitableObjs(pos, false))
  1187. {
  1188. if(includeOwned || obj->tempOwner != playerID)
  1189. out.push_back(obj);
  1190. }
  1191. });
  1192. }
  1193. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1194. {
  1195. std::vector<const CGObjectInstance *> ret;
  1196. retreiveVisitableObjs(ret, true);
  1197. erase_if(ret, [](const CGObjectInstance *obj)
  1198. {
  1199. return obj->tempOwner != ai->playerID;
  1200. });
  1201. return ret;
  1202. }
  1203. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  1204. {
  1205. visitableObjs.push_back(obj);
  1206. helperObjInfo[obj] = ObjInfo(obj);
  1207. }
  1208. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1209. {
  1210. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  1211. {
  1212. if(obj->ID == 5 && obj->subID == aid)
  1213. return obj;
  1214. }
  1215. return NULL;
  1216. //TODO what if more than one artifact is available? return them all or some slection criteria
  1217. }
  1218. bool VCAI::isAccessible(const int3 &pos)
  1219. {
  1220. //TODO precalculate for speed
  1221. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1222. {
  1223. if(isAccessibleForHero(pos, h))
  1224. return true;
  1225. }
  1226. return false;
  1227. }
  1228. const CGHeroInstance * VCAI::getHeroWithGrail() const
  1229. {
  1230. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1231. if(h->hasArt(2)) //grail
  1232. return h;
  1233. return NULL;
  1234. }
  1235. const CGObjectInstance * VCAI::getUnvisitedObj(const boost::function<bool(const CGObjectInstance *)> &predicate)
  1236. {
  1237. //TODO smarter definition of unvisited
  1238. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1239. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1240. return obj;
  1241. return NULL;
  1242. }
  1243. bool VCAI::isAccessibleForHero(const int3 & pos, const CGHeroInstance * h) const
  1244. {
  1245. cb->setSelection(h);
  1246. return cb->getPathInfo(pos)->reachable();
  1247. }
  1248. class cannotFulfillGoalException : public std::exception
  1249. {
  1250. std::string msg;
  1251. public:
  1252. explicit cannotFulfillGoalException(crstring _Message) : msg(_Message)
  1253. {
  1254. }
  1255. virtual ~cannotFulfillGoalException() throw ()
  1256. {
  1257. };
  1258. const char *what() const throw () OVERRIDE
  1259. {
  1260. return msg.c_str();
  1261. }
  1262. };
  1263. class goalFulfilledException : public std::exception
  1264. {
  1265. std::string msg;
  1266. public:
  1267. explicit goalFulfilledException(crstring _Message) : msg(_Message)
  1268. {
  1269. }
  1270. virtual ~goalFulfilledException() throw ()
  1271. {
  1272. };
  1273. const char *what() const throw () OVERRIDE
  1274. {
  1275. return msg.c_str();
  1276. }
  1277. };
  1278. bool VCAI::moveHeroToTile(int3 dst, const CGHeroInstance * h)
  1279. {
  1280. visitedObject = NULL;
  1281. int3 startHpos = h->visitablePos();
  1282. bool ret = false;
  1283. if(startHpos == dst)
  1284. {
  1285. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1286. cb->moveHero(h,CGHeroInstance::convertPosition(dst, true));
  1287. waitTillFree(); //movement may cause battle or blocking dialog
  1288. ret = true;
  1289. }
  1290. else
  1291. {
  1292. CGPath path;
  1293. cb->getPath2(dst, path);
  1294. if(path.nodes.empty())
  1295. {
  1296. tlog1 << "Hero " << h->name << " cannot reach " << dst << std::endl;
  1297. //setGoal(h, INVALID);
  1298. completeGoal (CGoal(VISIT_TILE).sethero(h));
  1299. cb->recalculatePaths();
  1300. throw std::runtime_error("Wrong move order!");
  1301. }
  1302. int i=path.nodes.size()-1;
  1303. for(; i>0; i--)
  1304. {
  1305. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1306. if(path.nodes[i-1].turns)
  1307. {
  1308. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1309. break;
  1310. }
  1311. int3 endpos = path.nodes[i-1].coord;
  1312. if(endpos == h->visitablePos())
  1313. //if (endpos == h->pos)
  1314. continue;
  1315. // if(i > 1)
  1316. // {
  1317. // int3 afterEndPos = path.nodes[i-2].coord;
  1318. // if(afterEndPos.z != endpos.z)
  1319. //
  1320. // }
  1321. //tlog0 << "Moving " << h->name << " from " << h->getPosition() << " to " << endpos << std::endl;
  1322. cb->moveHero(h,CGHeroInstance::convertPosition(endpos, true));
  1323. waitTillFree(); //movement may cause battle or blocking dialog
  1324. boost::this_thread::interruption_point();
  1325. if(h->tempOwner != playerID) //we lost hero - remove all tasks assigned to him/her
  1326. {
  1327. remove_if_present(lockedHeroes, h);
  1328. BOOST_FOREACH (auto obj, reservedHeroesMap[h])
  1329. {
  1330. remove_if_present(reservedObjs, obj); //unreserve all objects for that hero
  1331. }
  1332. remove_if_present(reservedHeroesMap, h);
  1333. throw std::runtime_error("Hero was lost!"); //we need to throw, otherwise hero will be assigned to sth again
  1334. break;
  1335. }
  1336. }
  1337. ret = !i;
  1338. }
  1339. if (visitedObject) //we step into something interesting
  1340. {
  1341. performObjectInteraction (visitedObject, h);
  1342. }
  1343. if(h->tempOwner == playerID) //we could have lost hero after last move
  1344. {
  1345. cb->recalculatePaths();
  1346. if (startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1347. {
  1348. throw cannotFulfillGoalException("Invalid path found!");
  1349. }
  1350. }
  1351. BNLOG("Hero %s moved from %s to %s", h->name % startHpos % h->visitablePos());
  1352. return ret;
  1353. }
  1354. int howManyTilesWillBeDiscovered(const int3 &pos, int radious)
  1355. {
  1356. int ret = 0;
  1357. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  1358. {
  1359. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  1360. {
  1361. int3 npos = int3(x,y,pos.z);
  1362. if(cb->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cb->isVisible(npos))
  1363. {
  1364. ret++;
  1365. }
  1366. }
  1367. }
  1368. return ret;
  1369. }
  1370. int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
  1371. {
  1372. return howManyTilesWillBeDiscovered(pos + dir, radious);
  1373. }
  1374. void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
  1375. {
  1376. BOOST_FOREACH(const int3 &tile, tiles)
  1377. {
  1378. foreach_neighbour(tile, [&](int3 neighbour)
  1379. {
  1380. if(cb->isVisible(neighbour))
  1381. out.push_back(neighbour);
  1382. });
  1383. }
  1384. }
  1385. void VCAI::tryRealize(CGoal g)
  1386. {
  1387. BNLOG("Attempting realizing goal with code %s", goalName(g.goalType));
  1388. switch(g.goalType)
  1389. {
  1390. case EXPLORE:
  1391. {
  1392. assert(0); //this goal is not elementar!
  1393. }
  1394. break;
  1395. case RECRUIT_HERO:
  1396. {
  1397. if(const CGTownInstance *t = findTownWithTavern())
  1398. {
  1399. //TODO co jesli nie ma dostepnego bohatera?
  1400. //TODO jezeli miasto jest zablokowane, sprobowac oczyscic wejscie
  1401. cb->recruitHero(t, cb->getAvailableHeroes(t)[0]);
  1402. }
  1403. //TODO karkolomna alternatywa - tawerna na mapie przygod lub wiezienie (nie wiem, czy warto?)
  1404. }
  1405. break;
  1406. case VISIT_TILE:
  1407. {
  1408. //cb->recalculatePaths();
  1409. if(!g.hero->movement)
  1410. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1411. if(!g.isBlockedBorderGate(g.tile))
  1412. {
  1413. if (ai->moveHeroToTile(g.tile, g.hero))
  1414. {
  1415. throw goalFulfilledException("");
  1416. }
  1417. }
  1418. else
  1419. throw cannotFulfillGoalException("There's a blocked gate!");
  1420. }
  1421. break;
  1422. case BUILD_STRUCTURE:
  1423. {
  1424. const CGTownInstance *t = g.town;
  1425. if(!t && g.hero)
  1426. t = g.hero->visitedTown;
  1427. if(!t)
  1428. {
  1429. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1430. {
  1431. switch(cb->canBuildStructure(t, g.bid))
  1432. {
  1433. case EBuildingState::ALLOWED:
  1434. cb->buildBuilding(t, g.bid);
  1435. return;
  1436. default:
  1437. break;
  1438. }
  1439. }
  1440. }
  1441. else if(cb->canBuildStructure(t, g.bid) == EBuildingState::ALLOWED)
  1442. {
  1443. cb->buildBuilding(t, g.bid);
  1444. return;
  1445. }
  1446. throw cannotFulfillGoalException("Cannot build a given structure!");
  1447. }
  1448. break;
  1449. case DIG_AT_TILE:
  1450. {
  1451. assert(g.hero->visitablePos() == g.tile);
  1452. if (g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1453. {
  1454. cb->dig (g.hero);
  1455. setGoal (g.hero, INVALID); // finished digging
  1456. }
  1457. else
  1458. {
  1459. ai->lockedHeroes[g.hero] = g; //hero who tries to dig shouldn't do anything else
  1460. throw cannotFulfillGoalException("A hero can't dig!\n");
  1461. }
  1462. }
  1463. break;
  1464. case COLLECT_RES:
  1465. if(const CGObjectInstance *obj = cb->getObj(g.objid, false))
  1466. {
  1467. if(const IMarket *m = IMarket::castFrom(obj, false))
  1468. {
  1469. for (int i = 0; i < ACTUAL_RESOURCE_COUNT; i++)
  1470. {
  1471. if(i == g.resID) continue;
  1472. int toGive, toGet;
  1473. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1474. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1475. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1476. if(cb->getResourceAmount(g.resID) >= g.value)
  1477. return;
  1478. }
  1479. }
  1480. else
  1481. {
  1482. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1483. }
  1484. }
  1485. else
  1486. {
  1487. saving[g.resID] = 1;
  1488. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1489. }
  1490. case CONQUER:
  1491. case GATHER_ARMY:
  1492. case BOOST_HERO:
  1493. // TODO: conquer??
  1494. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1495. case BUILD:
  1496. performTypicalActions();
  1497. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1498. case INVALID:
  1499. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1500. default:
  1501. throw cannotFulfillGoalException("Unknown type of goal !");
  1502. }
  1503. }
  1504. const CGTownInstance * VCAI::findTownWithTavern() const
  1505. {
  1506. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1507. if(vstd::contains(t->builtBuildings, EBuilding::TAVERN) && !t->visitingHero)
  1508. return t;
  1509. return NULL;
  1510. }
  1511. std::vector<const CGHeroInstance *> VCAI::getUnblockedHeroes() const
  1512. {
  1513. std::vector<const CGHeroInstance *> ret = cb->getHeroesInfo();
  1514. BOOST_FOREACH(auto h, lockedHeroes)
  1515. {
  1516. if (!h.second.invalid()) //we can use heroes without valid goal
  1517. remove_if_present(ret, h.first);
  1518. }
  1519. return ret;
  1520. }
  1521. const CGHeroInstance * VCAI::primaryHero() const
  1522. {
  1523. auto hs = cb->getHeroesInfo();
  1524. boost::sort(hs, compareHeroStrength);
  1525. if(hs.empty())
  1526. return NULL;
  1527. return hs.back();
  1528. }
  1529. void VCAI::endTurn()
  1530. {
  1531. tlog4 << "Player " << playerID << " ends turn\n";
  1532. if(!status.haveTurn())
  1533. {
  1534. tlog1 << "Not having turn at the end of turn???\n";
  1535. }
  1536. do
  1537. {
  1538. cb->endTurn();
  1539. } 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
  1540. tlog4 << "Player " << playerID << " ended turn\n";
  1541. }
  1542. void VCAI::striveToGoal(const CGoal &ultimateGoal)
  1543. {
  1544. if (ultimateGoal.invalid())
  1545. return;
  1546. CGoal abstractGoal;
  1547. while(1)
  1548. {
  1549. CGoal goal = ultimateGoal;
  1550. BNLOG("Striving to goal of type %s", goalName(ultimateGoal.goalType));
  1551. int maxGoals = 100; //preventing deadlock for mutually dependent goals
  1552. while(!goal.isElementar && !goal.isAbstract && maxGoals)
  1553. {
  1554. INDENT;
  1555. BNLOG("Considering goal %s", goalName(goal.goalType));
  1556. try
  1557. {
  1558. boost::this_thread::interruption_point();
  1559. goal = goal.whatToDoToAchieve();
  1560. --maxGoals;
  1561. }
  1562. catch(std::exception &e)
  1563. {
  1564. BNLOG("Goal %s decomposition failed: %s", goalName(goal.goalType) % e.what());
  1565. return;
  1566. }
  1567. }
  1568. try
  1569. {
  1570. boost::this_thread::interruption_point();
  1571. if (goal.hero) //lock this hero to fulfill ultimate goal
  1572. {
  1573. if (maxGoals)
  1574. {
  1575. setGoal (goal.hero, goal);
  1576. }
  1577. else
  1578. {
  1579. setGoal (goal.hero, INVALID); // we seemingly don't know what to do with hero
  1580. }
  1581. }
  1582. if (goal.isAbstract)
  1583. {
  1584. abstractGoal = goal; //allow only one abstract goal per call
  1585. BNLOG("Choosing abstract goal %s", goalName(goal.goalType));
  1586. break;
  1587. }
  1588. else
  1589. tryRealize(goal);
  1590. boost::this_thread::interruption_point();
  1591. }
  1592. catch(boost::thread_interrupted &e)
  1593. {
  1594. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1595. throw; //rethrow, we want to truly end this thread
  1596. }
  1597. catch(goalFulfilledException &e)
  1598. {
  1599. completeGoal (goal);
  1600. if (maxGoals > 98) //completed goal was main goal
  1601. //TODO: find better condition
  1602. return;
  1603. }
  1604. catch(std::exception &e)
  1605. {
  1606. BNLOG("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.", goalName(goal.goalType) % goalName(ultimateGoal.goalType));
  1607. BNLOG("The error message was: %s", e.what());
  1608. break;
  1609. }
  1610. }
  1611. //TODO: save abstract goals not related to hero
  1612. if (!abstractGoal.invalid()) //try to realize our one goal
  1613. {
  1614. while (1)
  1615. {
  1616. CGoal goal = CGoal(abstractGoal).setisAbstract(false);
  1617. int maxGoals = 50;
  1618. while (!goal.isElementar && maxGoals) //find elementar goal and fulfill it
  1619. {
  1620. try
  1621. {
  1622. boost::this_thread::interruption_point();
  1623. goal = goal.whatToDoToAchieve();
  1624. --maxGoals;
  1625. }
  1626. catch(std::exception &e)
  1627. {
  1628. BNLOG("Goal %s decomposition failed: %s", goalName(goal.goalType) % e.what());
  1629. return;
  1630. }
  1631. }
  1632. try
  1633. {
  1634. boost::this_thread::interruption_point();
  1635. tryRealize(goal);
  1636. boost::this_thread::interruption_point();
  1637. }
  1638. catch(boost::thread_interrupted &e)
  1639. {
  1640. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1641. throw; //rethrow, we want to truly end this thread
  1642. }
  1643. catch(goalFulfilledException &e)
  1644. {
  1645. completeGoal (goal);
  1646. if (maxGoals > 98) //completed goal was main goal
  1647. //TODO: find better condition
  1648. return;
  1649. }
  1650. catch(std::exception &e)
  1651. {
  1652. BNLOG("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.", goalName(goal.goalType) % goalName(ultimateGoal.goalType));
  1653. BNLOG("The error message was: %s", e.what());
  1654. break;
  1655. }
  1656. }
  1657. }
  1658. }
  1659. void VCAI::performTypicalActions()
  1660. {
  1661. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1662. {
  1663. BNLOG("Looking into %s", t->name);
  1664. buildStructure(t);
  1665. buildArmyIn(t);
  1666. if(!ai->primaryHero() ||
  1667. (t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero())))
  1668. {
  1669. recruitHero(t);
  1670. buildArmyIn(t);
  1671. }
  1672. }
  1673. BOOST_FOREACH(const CGHeroInstance *h, getUnblockedHeroes())
  1674. {
  1675. BNLOG("Looking into %s, MP=%d", h->name.c_str() % h->movement);
  1676. INDENT;
  1677. makePossibleUpgrades(h);
  1678. cb->setSelection(h);
  1679. try
  1680. {
  1681. wander(h);
  1682. }
  1683. catch(std::exception &e)
  1684. {
  1685. BNLOG("Cannot use this hero anymore, received exception: %s", e.what());
  1686. continue;
  1687. }
  1688. }
  1689. }
  1690. void VCAI::buildArmyIn(const CGTownInstance * t)
  1691. {
  1692. makePossibleUpgrades(t->visitingHero);
  1693. makePossibleUpgrades(t);
  1694. recruitCreatures(t);
  1695. moveCreaturesToHero(t);
  1696. }
  1697. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, const CGHeroInstance * h)
  1698. {
  1699. TimeCheck tc("looking for best exploration neighbour");
  1700. std::map<int3, int> dstToRevealedTiles;
  1701. BOOST_FOREACH(crint3 dir, dirs)
  1702. if(cb->isInTheMap(hpos+dir))
  1703. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir) * isSafeToVisit(h, hpos + dir);
  1704. auto best = dstToRevealedTiles.begin();
  1705. best->second *= cb->getPathInfo(best->first)->reachable();
  1706. best->second *= cb->getPathInfo(best->first)->accessible == CGPathNode::ACCESSIBLE;
  1707. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  1708. {
  1709. const CGPathNode *pn = cb->getPathInfo(i->first);
  1710. //const TerrainTile *t = cb->getTile(i->first);
  1711. if(best->second < i->second && i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  1712. best = i;
  1713. }
  1714. if(best->second)
  1715. return best->first;
  1716. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  1717. }
  1718. int3 VCAI::explorationNewPoint(int radius, const CGHeroInstance * h, std::vector<std::vector<int3> > &tiles)
  1719. {
  1720. TimeCheck tc("looking for new exploration point");
  1721. tlog0 << "Looking for an another place for exploration...\n";
  1722. tiles.resize(radius);
  1723. foreach_tile_pos([&](const int3 &pos)
  1724. {
  1725. if(!cb->isVisible(pos))
  1726. tiles[0].push_back(pos);
  1727. });
  1728. for (int i = 1; i < radius; i++)
  1729. {
  1730. getVisibleNeighbours(tiles[i-1], tiles[i]);
  1731. removeDuplicates(tiles[i]);
  1732. BOOST_FOREACH(const int3 &tile, tiles[i])
  1733. {
  1734. if(cb->getPathInfo(tile)->reachable() && isSafeToVisit(h, tile) && howManyTilesWillBeDiscovered(tile, radius))
  1735. {
  1736. return tile;
  1737. }
  1738. }
  1739. }
  1740. throw cannotFulfillGoalException("No accessible tile will bring discoveries!");
  1741. }
  1742. TResources VCAI::estimateIncome() const
  1743. {
  1744. TResources ret;
  1745. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1746. {
  1747. ret[Res::GOLD] += t->dailyIncome();
  1748. //TODO duplikuje newturn
  1749. if(t->hasBuilt(EBuilding::RESOURCE_SILO)) //there is resource silo
  1750. {
  1751. if(t->town->primaryRes == 127) //we'll give wood and ore
  1752. {
  1753. ret[Res::WOOD] ++;
  1754. ret[Res::ORE] ++;
  1755. }
  1756. else
  1757. {
  1758. ret[t->town->primaryRes] ++;
  1759. }
  1760. }
  1761. }
  1762. BOOST_FOREACH(const CGObjectInstance *obj, getFlaggedObjects())
  1763. {
  1764. if(obj->ID == Obj::MINE)
  1765. {
  1766. switch(obj->subID)
  1767. {
  1768. case Res::WOOD:
  1769. case Res::ORE:
  1770. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  1771. break;
  1772. case Res::GOLD:
  1773. case 7: //abandoned mine -> also gold
  1774. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  1775. break;
  1776. default:
  1777. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  1778. break;
  1779. }
  1780. }
  1781. }
  1782. return ret;
  1783. }
  1784. bool VCAI::containsSavedRes(const TResources &cost) const
  1785. {
  1786. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1787. {
  1788. if(saving[i] && cost[i])
  1789. return true;
  1790. }
  1791. return false;
  1792. }
  1793. void VCAI::recruitHero(const CGTownInstance * t)
  1794. {
  1795. BNLOG("Trying to recruit a hero in %s at %s", t->name % t->visitablePos())
  1796. cb->recruitHero(t, cb->getAvailableHeroes(t).front());
  1797. }
  1798. void VCAI::finish()
  1799. {
  1800. if(makingTurn)
  1801. makingTurn->interrupt();
  1802. }
  1803. void VCAI::requestActionASAP(boost::function<void()> whatToDo)
  1804. {
  1805. boost::barrier b(2);
  1806. boost::thread newThread([&b,this,whatToDo]()
  1807. {
  1808. setThreadName(-1, "VCAI::requestActionASAP::helper");
  1809. SET_GLOBAL_STATE(this);
  1810. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  1811. b.wait();
  1812. whatToDo();
  1813. });
  1814. b.wait();
  1815. }
  1816. AIStatus::AIStatus()
  1817. {
  1818. battle = NO_BATTLE;
  1819. remainingQueries = 0;
  1820. havingTurn = false;
  1821. }
  1822. AIStatus::~AIStatus()
  1823. {
  1824. }
  1825. void AIStatus::setBattle(BattleState BS)
  1826. {
  1827. boost::unique_lock<boost::mutex> lock(mx);
  1828. battle = BS;
  1829. cv.notify_all();
  1830. }
  1831. BattleState AIStatus::getBattle()
  1832. {
  1833. boost::unique_lock<boost::mutex> lock(mx);
  1834. return battle;
  1835. }
  1836. void AIStatus::addQueries(int val)
  1837. {
  1838. boost::unique_lock<boost::mutex> lock(mx);
  1839. remainingQueries += val;
  1840. BNLOG("Changing count of queries by %d, to a total of %d", val % remainingQueries);
  1841. assert(remainingQueries >= 0);
  1842. cv.notify_all();
  1843. }
  1844. void AIStatus::addQuery()
  1845. {
  1846. addQueries(1);
  1847. }
  1848. void AIStatus::removeQuery()
  1849. {
  1850. addQueries(-1);
  1851. }
  1852. int AIStatus::getQueriesCount()
  1853. {
  1854. boost::unique_lock<boost::mutex> lock(mx);
  1855. return remainingQueries;
  1856. }
  1857. void AIStatus::startedTurn()
  1858. {
  1859. boost::unique_lock<boost::mutex> lock(mx);
  1860. havingTurn = true;
  1861. cv.notify_all();
  1862. }
  1863. void AIStatus::madeTurn()
  1864. {
  1865. boost::unique_lock<boost::mutex> lock(mx);
  1866. havingTurn = false;
  1867. cv.notify_all();
  1868. }
  1869. void AIStatus::waitTillFree()
  1870. {
  1871. boost::unique_lock<boost::mutex> lock(mx);
  1872. while(battle != NO_BATTLE || remainingQueries)
  1873. cv.wait(lock);
  1874. }
  1875. bool AIStatus::haveTurn()
  1876. {
  1877. boost::unique_lock<boost::mutex> lock(mx);
  1878. return havingTurn;
  1879. }
  1880. int3 whereToExplore(const CGHeroInstance *h)
  1881. {
  1882. //TODO it's stupid and ineffective, write sth better
  1883. cb->setSelection(h);
  1884. int radius = h->getSightRadious();
  1885. int3 hpos = h->visitablePos();
  1886. //look for nearby objs -> visit them if they're close enouh
  1887. const int DIST_LIMIT = 3;
  1888. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  1889. BOOST_FOREACH(const CGObjectInstance *obj, ai->getPossibleDestinations(h))
  1890. {
  1891. int3 op = obj->visitablePos();
  1892. CGPath p;
  1893. cb->getPath2(op, p);
  1894. if(p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  1895. nearbyVisitableObjs.push_back(obj);
  1896. }
  1897. boost::sort(nearbyVisitableObjs, isCloser);
  1898. if(nearbyVisitableObjs.size())
  1899. return nearbyVisitableObjs.back()->visitablePos();
  1900. try
  1901. {
  1902. return ai->explorationBestNeighbour(hpos, radius, h);
  1903. }
  1904. catch(cannotFulfillGoalException &e)
  1905. {
  1906. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow], metryka taksówkowa
  1907. try
  1908. {
  1909. return ai->explorationNewPoint(radius, h, tiles);
  1910. }
  1911. catch(cannotFulfillGoalException &e)
  1912. {
  1913. std::map<int, std::vector<int3> > profits;
  1914. {
  1915. TimeCheck tc("Evaluating exploration possibilities");
  1916. tiles[0].clear(); //we can't reach FoW anyway
  1917. BOOST_FOREACH(auto &vt, tiles)
  1918. BOOST_FOREACH(auto &tile, vt)
  1919. profits[howManyTilesWillBeDiscovered(tile, radius)].push_back(tile);
  1920. }
  1921. if(profits.empty())
  1922. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  1923. auto bestDest = profits.end();
  1924. bestDest--;
  1925. return bestDest->second.front(); //TODO which is the real best tile?
  1926. }
  1927. }
  1928. }
  1929. TSubgoal CGoal::whatToDoToAchieve()
  1930. {
  1931. switch(goalType)
  1932. {
  1933. case WIN:
  1934. {
  1935. const CVictoryCondition &vc = cb->getMapHeader()->victoryCondition;
  1936. EVictoryConditionType::EVictoryConditionType cond = vc.condition;
  1937. if(!vc.appliesToAI)
  1938. {
  1939. //TODO deduce victory from human loss condition
  1940. cond = EVictoryConditionType::WINSTANDARD;
  1941. }
  1942. switch(cond)
  1943. {
  1944. case EVictoryConditionType::ARTIFACT:
  1945. return CGoal(GET_ART_TYPE).setaid(vc.ID);
  1946. case EVictoryConditionType::BEATHERO:
  1947. return CGoal(GET_OBJ).setobjid(vc.ID);
  1948. case EVictoryConditionType::BEATMONSTER:
  1949. return CGoal(GET_OBJ).setobjid(vc.ID);
  1950. case EVictoryConditionType::BUILDCITY:
  1951. //TODO build castle/capitol
  1952. break;
  1953. case EVictoryConditionType::BUILDGRAIL:
  1954. {
  1955. if(const CGHeroInstance *h = ai->getHeroWithGrail())
  1956. {
  1957. //hero is in a town that can host Grail
  1958. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, EBuilding::GRAIL))
  1959. {
  1960. const CGTownInstance *t = h->visitedTown;
  1961. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::GRAIL).settown(t);
  1962. }
  1963. else
  1964. {
  1965. auto towns = cb->getTownsInfo();
  1966. towns.erase(boost::remove_if(towns,
  1967. [](const CGTownInstance *t) -> bool
  1968. {
  1969. return vstd::contains(t->forbiddenBuildings, EBuilding::GRAIL);
  1970. }),
  1971. towns.end());
  1972. boost::sort(towns, isCloser);
  1973. if(towns.size())
  1974. {
  1975. return CGoal(VISIT_TILE).sethero(h).settile(towns.front()->visitablePos());
  1976. }
  1977. }
  1978. }
  1979. double ratio = 0;
  1980. int3 grailPos = cb->getGrailPos(ratio);
  1981. if(ratio > 0.99)
  1982. {
  1983. return CGoal(DIG_AT_TILE).settile(grailPos);
  1984. }
  1985. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  1986. {
  1987. return CGoal(GET_OBJ).setobjid(obj->id);
  1988. }
  1989. else
  1990. return CGoal(EXPLORE);
  1991. }
  1992. break;
  1993. case EVictoryConditionType::CAPTURECITY:
  1994. return CGoal(GET_OBJ).setobjid(vc.ID);
  1995. case EVictoryConditionType::GATHERRESOURCE:
  1996. return CGoal(COLLECT_RES).setresID(vc.ID).setvalue(vc.count);
  1997. //TODO mines? piles? marketplace?
  1998. //save?
  1999. break;
  2000. case EVictoryConditionType::GATHERTROOP:
  2001. break;
  2002. case EVictoryConditionType::TAKEDWELLINGS:
  2003. break;
  2004. case EVictoryConditionType::TAKEMINES:
  2005. break;
  2006. case EVictoryConditionType::TRANSPORTITEM:
  2007. break;
  2008. case EVictoryConditionType::WINSTANDARD:
  2009. return CGoal(CONQUER);
  2010. default:
  2011. assert(0);
  2012. }
  2013. }
  2014. break;
  2015. case GET_OBJ:
  2016. {
  2017. const CGObjectInstance * obj = cb->getObj(objid);
  2018. if(!obj)
  2019. return CGoal(EXPLORE);
  2020. int3 pos = cb->getObj(objid)->visitablePos();
  2021. return CGoal(VISIT_TILE).settile(pos);
  2022. }
  2023. break;
  2024. case GET_ART_TYPE:
  2025. {
  2026. const CGObjectInstance *artInst = ai->lookForArt(aid);
  2027. if(!artInst)
  2028. {
  2029. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid);
  2030. if(alternativeWay.invalid())
  2031. return CGoal(EXPLORE);
  2032. else
  2033. return alternativeWay;
  2034. }
  2035. else
  2036. return CGoal(GET_OBJ).setobjid(artInst->id);
  2037. }
  2038. break;
  2039. case CLEAR_WAY_TO:
  2040. {
  2041. assert(tile.x >= 0); //set tile
  2042. if(!cb->isVisible(tile))
  2043. {
  2044. tlog1 << "Clear way should be used with visible tiles!\n";
  2045. return CGoal(EXPLORE);
  2046. }
  2047. const CGHeroInstance *h = hero ? hero : ai->primaryHero();
  2048. if(!h)
  2049. return CGoal(RECRUIT_HERO);
  2050. cb->setSelection(h);
  2051. SectorMap sm;
  2052. bool dropToFile = false;
  2053. if(dropToFile) //for debug purposes
  2054. sm.write("test.txt");
  2055. int3 tileToHit = sm.firstTileToGet(h, tile);
  2056. //if(isSafeToVisit(h, tileToHit))
  2057. if(isBlockedBorderGate(tileToHit))
  2058. throw cannotFulfillGoalException("There's blocked border gate!");
  2059. if(tileToHit == tile)
  2060. {
  2061. tlog1 << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  2062. % tileToHit % tile % h->name % h->visitablePos();
  2063. throw cannotFulfillGoalException("Retreiving first tile to hit failed (probably)!");
  2064. }
  2065. return CGoal(VISIT_TILE).settile(tileToHit).sethero(h);
  2066. //TODO czy istnieje lepsza droga?
  2067. }
  2068. throw cannotFulfillGoalException("Cannot reach given tile!");
  2069. //return CGoal(EXPLORE); // TODO improve
  2070. case EXPLORE:
  2071. {
  2072. if (hero)
  2073. {
  2074. return CGoal(VISIT_TILE).settile(whereToExplore(hero)).sethero(hero);
  2075. }
  2076. auto hs = cb->getHeroesInfo();
  2077. int howManyHeroes = hs.size();
  2078. erase(hs, [](const CGHeroInstance *h)
  2079. {
  2080. return contains(ai->lockedHeroes, h);
  2081. });
  2082. if(hs.empty()) //all heroes are busy. buy new one
  2083. {
  2084. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2085. return CGoal(RECRUIT_HERO);
  2086. else //find mobile hero with weakest army
  2087. {
  2088. hs = cb->getHeroesInfo();
  2089. erase_if(hs, [](const CGHeroInstance *h)
  2090. {
  2091. return !h->movement; //only hero with movement are of interest for us
  2092. });
  2093. if (hs.empty())
  2094. {
  2095. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2096. return CGoal(RECRUIT_HERO);
  2097. else
  2098. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2099. }
  2100. boost::sort(hs, compareMovement); //closer to what?
  2101. }
  2102. }
  2103. const CGHeroInstance *h = hs.front();
  2104. return (*this).sethero(h).setisAbstract(true);
  2105. }
  2106. I_AM_ELEMENTAR;
  2107. case RECRUIT_HERO:
  2108. {
  2109. const CGTownInstance *t = ai->findTownWithTavern();
  2110. if(!t)
  2111. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::TAVERN);
  2112. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  2113. return CGoal(COLLECT_RES).setresID(Res::GOLD).setvalue(HERO_GOLD_COST);
  2114. I_AM_ELEMENTAR;
  2115. }
  2116. break;
  2117. case VISIT_TILE:
  2118. {
  2119. if(!cb->isVisible(tile))
  2120. return CGoal(EXPLORE);
  2121. if(hero && !ai->isAccessibleForHero(tile, hero))
  2122. hero = NULL;
  2123. if(!hero)
  2124. {
  2125. if(cb->getHeroesInfo().empty())
  2126. {
  2127. return CGoal(RECRUIT_HERO);
  2128. }
  2129. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  2130. {
  2131. if(ai->isAccessibleForHero(tile, h))
  2132. {
  2133. hero = h;
  2134. break;
  2135. }
  2136. }
  2137. }
  2138. if(hero)
  2139. {
  2140. if(isSafeToVisit(hero, tile))
  2141. return CGoal(*this).setisElementar(true);
  2142. else
  2143. {
  2144. return CGoal(GATHER_ARMY).sethero(hero);
  2145. }
  2146. }
  2147. else //inaccessible for all heroes
  2148. {
  2149. return CGoal(CLEAR_WAY_TO).settile(tile);
  2150. }
  2151. }
  2152. break;
  2153. case DIG_AT_TILE:
  2154. {
  2155. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  2156. if(firstObj && firstObj->ID == GameConstants::HEROI_TYPE && firstObj->tempOwner == ai->playerID) //we have hero at dest
  2157. {
  2158. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  2159. return CGoal(*this).sethero(h).setisElementar(true);
  2160. }
  2161. return CGoal(VISIT_TILE).settile(tile);
  2162. }
  2163. break;
  2164. case BUILD_STRUCTURE:
  2165. //TODO check res
  2166. //look for town
  2167. //prerequisites?
  2168. I_AM_ELEMENTAR;
  2169. case COLLECT_RES:
  2170. {
  2171. std::vector<const IMarket*> markets;
  2172. std::vector<const CGObjectInstance*> visObjs;
  2173. ai->retreiveVisitableObjs(visObjs, true);
  2174. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  2175. {
  2176. if(const IMarket *m = IMarket::castFrom(obj, false))
  2177. {
  2178. if(obj->ID == GameConstants::TOWNI_TYPE && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  2179. markets.push_back(m);
  2180. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  2181. markets.push_back(m);
  2182. }
  2183. }
  2184. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  2185. {
  2186. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  2187. });
  2188. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  2189. {
  2190. return !(market->o->ID == GameConstants::TOWNI_TYPE && market->o->tempOwner == ai->playerID)
  2191. && !ai->isAccessible(market->o->visitablePos());
  2192. }),markets.end());
  2193. if(!markets.size())
  2194. {
  2195. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2196. {
  2197. if(cb->canBuildStructure(t, EBuilding::MARKETPLACE) == EBuildingState::ALLOWED)
  2198. return CGoal(BUILD_STRUCTURE).settown(t).setbid(EBuilding::MARKETPLACE);
  2199. }
  2200. }
  2201. else
  2202. {
  2203. const IMarket *m = markets.back();
  2204. //attempt trade at back (best prices)
  2205. int howManyCanWeBuy = 0;
  2206. for(int i = 0; i < ACTUAL_RESOURCE_COUNT; i++)
  2207. {
  2208. if(i == resID) continue;
  2209. int toGive = -1, toReceive = -1;
  2210. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  2211. assert(toGive > 0 && toReceive > 0);
  2212. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  2213. }
  2214. if(howManyCanWeBuy + cb->getResourceAmount(resID) >= value)
  2215. {
  2216. auto backObj = backOrNull(cb->getVisitableObjs(m->o->visitablePos())); //it'll be a hero if we have one there; otherwise marketplace
  2217. assert(backObj);
  2218. if(backObj->tempOwner != ai->playerID)
  2219. return CGoal(GET_OBJ).setobjid(m->o->id);
  2220. return setobjid(m->o->id).setisElementar(true);
  2221. }
  2222. }
  2223. }
  2224. return CGoal(INVALID);
  2225. case CONQUER: //TODO: put it into a function?
  2226. {
  2227. auto hs = cb->getHeroesInfo();
  2228. int howManyHeroes = hs.size();
  2229. erase(hs, [](const CGHeroInstance *h)
  2230. {
  2231. return contains(ai->lockedHeroes, h);
  2232. });
  2233. if(hs.empty()) //all heroes are busy. buy new one
  2234. {
  2235. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2236. return CGoal(RECRUIT_HERO);
  2237. else //find mobile hero with weakest army
  2238. {
  2239. hs = cb->getHeroesInfo();
  2240. erase_if(hs, [](const CGHeroInstance *h)
  2241. {
  2242. return !h->movement; //only hero with movement are of interest for us
  2243. });
  2244. if (hs.empty())
  2245. {
  2246. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2247. return CGoal(RECRUIT_HERO);
  2248. else
  2249. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2250. }
  2251. boost::sort(hs, compareHeroStrength);
  2252. }
  2253. }
  2254. const CGHeroInstance *h = hs.back();
  2255. cb->setSelection(h);
  2256. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  2257. ai->retreiveVisitableObjs(objs);
  2258. erase_if(objs, [&](const CGObjectInstance *obj)
  2259. {
  2260. return (obj->ID != GameConstants::TOWNI_TYPE && obj->ID != GameConstants::HEROI_TYPE) //not town/hero
  2261. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != 0; //not enemy
  2262. });
  2263. if(objs.empty())
  2264. return CGoal(EXPLORE); //we need to find an enemy
  2265. erase_if(objs, [&](const CGObjectInstance *obj)
  2266. {
  2267. return !isSafeToVisit(h, obj->visitablePos());
  2268. });
  2269. if(objs.empty())
  2270. I_AM_ELEMENTAR;
  2271. boost::sort(objs, isCloser);
  2272. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  2273. {
  2274. if(ai->isAccessibleForHero(obj->visitablePos(), h))
  2275. return CGoal(VISIT_TILE).sethero(h).settile(obj->visitablePos());
  2276. }
  2277. return CGoal(EXPLORE); //enemy is inaccessible
  2278. }
  2279. break;
  2280. case BUILD:
  2281. I_AM_ELEMENTAR;
  2282. case INVALID:
  2283. I_AM_ELEMENTAR;
  2284. case GATHER_ARMY:
  2285. {
  2286. //TODO: find hero if none set
  2287. const CGHeroInstance *h = hero;
  2288. cb->setSelection(h);
  2289. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  2290. {
  2291. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  2292. };
  2293. std::vector<const CGTownInstance *> townsReachable;
  2294. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2295. {
  2296. if(!t->visitingHero && howManyReinforcementsCanGet(h,t))
  2297. {
  2298. if(isReachable(t))
  2299. townsReachable.push_back(t);
  2300. }
  2301. }
  2302. if(townsReachable.size()) //try towns first
  2303. {
  2304. boost::sort(townsReachable, compareReinforcements);
  2305. return CGoal(VISIT_TILE).sethero(hero).settile(townsReachable.back()->visitablePos());
  2306. }
  2307. else
  2308. {
  2309. std::vector<const CGObjectInstance *> objs; //here we'll gather all dwellings
  2310. ai->retreiveVisitableObjs(objs);
  2311. erase_if(objs, [&](const CGObjectInstance *obj)
  2312. {
  2313. return (obj->ID != Obj::CREATURE_GENERATOR1); //not town/ dwelling
  2314. });
  2315. if(objs.empty()) //no possible objects, we did eveyrthing already
  2316. return CGoal(EXPLORE).sethero(hero);
  2317. //TODO: check if we can recruit any creatures there, evaluate army
  2318. boost::sort(objs, isCloser);
  2319. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  2320. { //find safe dwelling
  2321. if (isSafeToVisit(hero, obj->visitablePos())) //TODO: make use of multiple heroes
  2322. return CGoal(VISIT_TILE).sethero(hero).settile(obj->visitablePos());
  2323. }
  2324. }
  2325. return CGoal(EXPLORE); //find dwelling
  2326. }
  2327. break;
  2328. default:
  2329. assert(0);
  2330. }
  2331. return CGoal(EXPLORE);
  2332. }
  2333. TSubgoal CGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  2334. {
  2335. if(obj)
  2336. return CGoal(GET_OBJ).setobjid(obj->id);
  2337. else
  2338. return CGoal(EXPLORE);
  2339. }
  2340. TSubgoal CGoal::lookForArtSmart(int aid)
  2341. {
  2342. return CGoal(INVALID);
  2343. }
  2344. bool CGoal::invalid() const
  2345. {
  2346. return goalType == INVALID;
  2347. }
  2348. bool CGoal::isBlockedBorderGate(int3 tileToHit)
  2349. {
  2350. return cb->getTile(tileToHit)->topVisitableID() == Obj::BORDER_GATE
  2351. && cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
  2352. }
  2353. SectorMap::SectorMap()
  2354. {
  2355. // int3 sizes = cb->getMapSize();
  2356. // sector.resize(sizes.x);
  2357. // BOOST_FOREACH(auto &i, sector)
  2358. // i.resize(sizes.y);
  2359. //
  2360. // BOOST_FOREACH(auto &i, sector)
  2361. // BOOST_FOREACH(auto &j, i)
  2362. // j.resize(sizes.z, 0);
  2363. update();
  2364. }
  2365. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  2366. {
  2367. if(t->blocked && !t->visitable)
  2368. {
  2369. sec = NOT_AVAILABLE;
  2370. return true;
  2371. }
  2372. return false;
  2373. }
  2374. bool markIfBlocked(ui8 &sec, crint3 pos)
  2375. {
  2376. return markIfBlocked(sec, pos, cb->getTile(pos));
  2377. }
  2378. void SectorMap::update()
  2379. {
  2380. clear();
  2381. int curSector = 3; //0 is invisible, 1 is not explored
  2382. foreach_tile_pos([&](crint3 pos)
  2383. {
  2384. if(retreiveTile(pos) == NOT_CHECKED)
  2385. {
  2386. if(!markIfBlocked(retreiveTile(pos), pos))
  2387. exploreNewSector(pos, curSector++);
  2388. }
  2389. });
  2390. valid = true;
  2391. }
  2392. void SectorMap::clear()
  2393. {
  2394. sector = cb->getVisibilityMap();
  2395. valid = false;
  2396. }
  2397. bool canBeEmbarkmentPoint(const TerrainTile *t)
  2398. {
  2399. //tile must be free of with unoccupied boat
  2400. return !t->blocked
  2401. || (t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT);
  2402. }
  2403. void SectorMap::exploreNewSector(crint3 pos, int num)
  2404. {
  2405. Sector &s = infoOnSectors[num];
  2406. s.id = num;
  2407. s.water = cb->getTile(pos)->isWater();
  2408. std::queue<int3> toVisit;
  2409. toVisit.push(pos);
  2410. while(toVisit.size())
  2411. {
  2412. int3 curPos = toVisit.front();
  2413. toVisit.pop();
  2414. ui8 &sec = retreiveTile(curPos);
  2415. if(sec == NOT_CHECKED)
  2416. {
  2417. const TerrainTile *t = cb->getTile(curPos);
  2418. if(!markIfBlocked(sec, curPos, t))
  2419. {
  2420. if(t->isWater() == s.water) //sector is only-water or only-land
  2421. {
  2422. sec = num;
  2423. s.tiles.push_back(curPos);
  2424. foreach_neighbour(curPos, [&](crint3 neighPos)
  2425. {
  2426. if(retreiveTile(neighPos) == NOT_CHECKED)
  2427. {
  2428. toVisit.push(neighPos);
  2429. //parent[neighPos] = curPos;
  2430. }
  2431. const TerrainTile *nt = cb->getTile(neighPos, false);
  2432. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt))
  2433. {
  2434. s.embarkmentPoints.push_back(neighPos);
  2435. }
  2436. });
  2437. if(t->visitable && vstd::contains(ai->knownSubterraneanGates, t->visitableObjects.front()))
  2438. toVisit.push(ai->knownSubterraneanGates[t->visitableObjects.front()]->pos);
  2439. }
  2440. }
  2441. }
  2442. }
  2443. removeDuplicates(s.embarkmentPoints);
  2444. }
  2445. void SectorMap::write(crstring fname)
  2446. {
  2447. std::ofstream out(fname);
  2448. for(int k = 0; k < cb->getMapSize().z; k++)
  2449. {
  2450. for(int j = 0; j < cb->getMapSize().y; j++)
  2451. {
  2452. for(int i = 0; i < cb->getMapSize().x; i++)
  2453. {
  2454. out << (int)sector[i][j][k] << '\t';
  2455. }
  2456. out << std::endl;
  2457. }
  2458. out << std::endl;
  2459. }
  2460. }
  2461. bool isWeeklyRevisitable (const CGObjectInstance * obj)
  2462. { //TODO: allow polling of remaining creatures in dwelling
  2463. if (dynamic_cast<const CGVisitableOPW *>(obj) || //ensures future compatibility, unlike IDs
  2464. dynamic_cast<const CGDwelling *>(obj) ||
  2465. dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  2466. return true;
  2467. switch (obj->ID)
  2468. {
  2469. case Obj::STABLES: //any other potential visitable objects?
  2470. return true;
  2471. }
  2472. return false;
  2473. }
  2474. bool shouldVisit (const CGHeroInstance * h, const CGObjectInstance * obj)
  2475. {
  2476. switch (obj->ID)
  2477. {
  2478. case Obj::CREATURE_GENERATOR1:
  2479. {
  2480. if (obj->tempOwner != h->tempOwner)
  2481. return true; //flag just in case
  2482. bool canRecruitCreatures = false;
  2483. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2484. BOOST_FOREACH(auto level, d->creatures)
  2485. {
  2486. BOOST_FOREACH(auto c, level.second)
  2487. {
  2488. if (h->getSlotFor(c) != -1)
  2489. canRecruitCreatures = true;
  2490. }
  2491. }
  2492. return canRecruitCreatures;
  2493. }
  2494. case Obj::MONOLITH1:
  2495. case Obj::MONOLITH2:
  2496. case Obj::MONOLITH3:
  2497. case Obj::WHIRLPOOL:
  2498. //TODO: mehcanism for handling monoliths
  2499. return false;
  2500. case Obj::SCHOOL_OF_MAGIC:
  2501. case Obj::SCHOOL_OF_WAR:
  2502. {
  2503. TResources myRes = ai->myCb->getResourceAmount();
  2504. if (myRes[Res::GOLD] - GOLD_RESERVE < 1000)
  2505. return false;
  2506. }
  2507. break;
  2508. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2509. if (h->level < 12)
  2510. return false;
  2511. case Obj::TREE_OF_KNOWLEDGE:
  2512. {
  2513. TResources myRes = ai->myCb->getResourceAmount();
  2514. if (myRes[Res::GOLD] - GOLD_RESERVE < 2000 || myRes[Res::GEMS] < 10)
  2515. return false;
  2516. }
  2517. break;
  2518. }
  2519. if (obj->wasVisited(h))
  2520. return false;
  2521. return true;
  2522. }
  2523. int3 SectorMap::firstTileToGet(const CGHeroInstance *h, crint3 dst)
  2524. {
  2525. int sourceSector = retreiveTile(h->visitablePos()),
  2526. destinationSector = retreiveTile(dst);
  2527. if(sourceSector != destinationSector)
  2528. {
  2529. const Sector *src = &infoOnSectors[sourceSector],
  2530. *dst = &infoOnSectors[destinationSector];
  2531. std::map<const Sector*, const Sector*> preds;
  2532. std::queue<const Sector *> sq;
  2533. sq.push(src);
  2534. while(!sq.empty())
  2535. {
  2536. const Sector *s = sq.front();
  2537. sq.pop();
  2538. BOOST_FOREACH(int3 ep, s->embarkmentPoints)
  2539. {
  2540. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  2541. //preds[s].push_back(neigh);
  2542. if(!preds[neigh])
  2543. {
  2544. preds[neigh] = s;
  2545. sq.push(neigh);
  2546. }
  2547. }
  2548. //TODO consider other types of connections between sectors?
  2549. }
  2550. if(!preds[dst])
  2551. {
  2552. write("test.txt");
  2553. throw cannotFulfillGoalException(str(format("Cannot find connection between sectors %d and %d") % src->id % dst->id));
  2554. }
  2555. std::vector<const Sector*> toTraverse;
  2556. toTraverse.push_back(dst);
  2557. while(toTraverse.back() != src)
  2558. {
  2559. toTraverse.push_back(preds[toTraverse.back()]);
  2560. }
  2561. if(preds[dst])
  2562. {
  2563. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  2564. if(!src->water && sectorToReach->water) //embark
  2565. {
  2566. //embark on ship -> look for an EP with a boat
  2567. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  2568. {
  2569. const TerrainTile *t = cb->getTile(pos);
  2570. return t && t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT
  2571. && retreiveTile(pos) == sectorToReach->id;
  2572. });
  2573. if(firstEP != src->embarkmentPoints.end())
  2574. {
  2575. return *firstEP;
  2576. }
  2577. else
  2578. {
  2579. //we need to find a shipyard with an access to the desired sector's EP
  2580. //TODO what about Summon Boat spell?
  2581. std::vector<const IShipyard *> shipyards;
  2582. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2583. {
  2584. if(t->hasBuilt(EBuilding::SHIPYARD))
  2585. shipyards.push_back(t);
  2586. }
  2587. std::vector<const CGObjectInstance*> visObjs;
  2588. ai->retreiveVisitableObjs(visObjs, true);
  2589. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  2590. {
  2591. if(obj->ID != GameConstants::TOWNI_TYPE) //towns were handled in the previous loop
  2592. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  2593. shipyards.push_back(shipyard);
  2594. }
  2595. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  2596. {
  2597. return shipyard->state() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  2598. }),shipyards.end());
  2599. if(!shipyards.size())
  2600. {
  2601. //TODO consider possibility of building shipyard in a town
  2602. throw cannotFulfillGoalException("There is no known shipyard!");
  2603. }
  2604. //we have only shipyards that possibly can build ships onto the appropriate EP
  2605. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  2606. {
  2607. return s->o->tempOwner == ai->playerID;
  2608. });
  2609. if(ownedGoodShipyard != shipyards.end())
  2610. {
  2611. const IShipyard *s = *ownedGoodShipyard;
  2612. TResources shipCost;
  2613. s->getBoatCost(shipCost);
  2614. if(cb->getResourceAmount().canAfford(shipCost))
  2615. {
  2616. int3 ret = s->bestLocation();
  2617. cb->buildBoat(s);
  2618. return ret;
  2619. }
  2620. else
  2621. {
  2622. //TODO gather res
  2623. throw cannotFulfillGoalException("Not enough resources to build a boat");
  2624. }
  2625. }
  2626. else
  2627. {
  2628. //TODO pick best shipyard to take over
  2629. return shipyards.front()->o->pos;
  2630. }
  2631. }
  2632. }
  2633. else if(src->water && !sectorToReach->water)
  2634. {
  2635. //TODO
  2636. //disembark
  2637. }
  2638. else
  2639. {
  2640. //TODO
  2641. //transition between two land/water sectors. Monolith? Whirlpool? ...
  2642. throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  2643. }
  2644. }
  2645. else
  2646. {
  2647. throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  2648. }
  2649. }
  2650. else
  2651. {
  2652. makeParentBFS(h->visitablePos());
  2653. int3 curtile = dst;
  2654. while(curtile != h->visitablePos())
  2655. {
  2656. if(cb->getPathInfo(curtile)->reachable())
  2657. {
  2658. return curtile;
  2659. }
  2660. else
  2661. {
  2662. auto i = parent.find(curtile);
  2663. if(i != parent.end())
  2664. {
  2665. assert(curtile != i->second);
  2666. curtile = i->second;
  2667. }
  2668. else
  2669. throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  2670. }
  2671. }
  2672. }
  2673. throw cannotFulfillGoalException("Impossible happened.");
  2674. }
  2675. void SectorMap::makeParentBFS(crint3 source)
  2676. {
  2677. parent.clear();
  2678. int mySector = retreiveTile(source);
  2679. std::queue<int3> toVisit;
  2680. toVisit.push(source);
  2681. while(toVisit.size())
  2682. {
  2683. int3 curPos = toVisit.front();
  2684. toVisit.pop();
  2685. ui8 &sec = retreiveTile(curPos);
  2686. assert(sec == mySector); //consider only tiles from the same sector
  2687. //const TerrainTile *t = cb->getTile(curPos);
  2688. foreach_neighbour(curPos, [&](crint3 neighPos)
  2689. {
  2690. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  2691. {
  2692. toVisit.push(neighPos);
  2693. parent[neighPos] = curPos;
  2694. }
  2695. });
  2696. }
  2697. }
  2698. unsigned char & SectorMap::retreiveTile(crint3 pos)
  2699. {
  2700. return retreiveTileN(sector, pos);
  2701. }
  2702. const CGObjectInstance * ObjectIdRef::operator->() const
  2703. {
  2704. return cb->getObj(id, false);
  2705. }
  2706. ObjectIdRef::operator const CGObjectInstance*() const
  2707. {
  2708. return cb->getObj(id, false);
  2709. }
  2710. ObjectIdRef::ObjectIdRef(int _id) : id(_id)
  2711. {
  2712. }
  2713. ObjectIdRef::ObjectIdRef(const CGObjectInstance *obj) : id(obj->id)
  2714. {
  2715. }
  2716. bool ObjectIdRef::operator<(const ObjectIdRef &rhs) const
  2717. {
  2718. return id < rhs.id;
  2719. }