VCAI.cpp 61 KB

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