VCAI.cpp 62 KB

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