VCAI.cpp 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892
  1. #include "StdInc.h"
  2. #include "VCAI.h"
  3. #include "../../lib/UnlockGuard.h"
  4. #include "../../lib/CObjectHandler.h"
  5. #include "../../lib/CConfigHandler.h"
  6. #include "../../lib/CHeroHandler.h"
  7. /*
  8. * CCreatureHandler.h, part of VCMI engine
  9. *
  10. * Authors: listed in file AUTHORS in main folder
  11. *
  12. * License: GNU General Public License v2.0 or later
  13. * Full text of license available in license.txt file, in main folder
  14. *
  15. */
  16. extern FuzzyHelper *fh;
  17. class CGVisitableOPW;
  18. class TSubgoal;
  19. const double SAFE_ATTACK_CONSTANT = 1.5;
  20. 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)
  21. using namespace vstd;
  22. //one thread may be turn of AI and another will be handling a side effect for AI2
  23. boost::thread_specific_ptr<CCallback> cb;
  24. boost::thread_specific_ptr<VCAI> ai;
  25. //std::map<int, std::map<int, int> > HeroView::infosCount;
  26. //helper RAII to manage global ai/cb ptrs
  27. struct SetGlobalState
  28. {
  29. SetGlobalState(VCAI * AI)
  30. {
  31. assert(!ai.get());
  32. assert(!cb.get());
  33. ai.reset(AI);
  34. cb.reset(AI->myCb.get());
  35. }
  36. ~SetGlobalState()
  37. {
  38. ai.release();
  39. cb.release();
  40. }
  41. };
  42. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  43. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  44. #define MAKING_TURN SET_GLOBAL_STATE(this)
  45. unsigned char &retreiveTileN(std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  46. {
  47. return vectors[pos.x][pos.y][pos.z];
  48. }
  49. const unsigned char &retreiveTileN(const std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  50. {
  51. return vectors[pos.x][pos.y][pos.z];
  52. }
  53. void foreach_tile(std::vector< std::vector< std::vector<unsigned char> > > &vectors, std::function<void(unsigned char &in)> foo)
  54. {
  55. for(auto & vector : vectors)
  56. for(auto j = vector.begin(); j != vector.end(); j++)
  57. for(auto & elem : *j)
  58. foo(elem);
  59. }
  60. struct ObjInfo
  61. {
  62. int3 pos;
  63. std::string name;
  64. ObjInfo(){}
  65. ObjInfo(const CGObjectInstance *obj):
  66. pos(obj->pos),
  67. name(obj->getHoverText())
  68. {
  69. }
  70. };
  71. std::map<const CGObjectInstance *, ObjInfo> helperObjInfo;
  72. VCAI::VCAI(void)
  73. {
  74. LOG_TRACE(logAi);
  75. makingTurn = nullptr;
  76. }
  77. VCAI::~VCAI(void)
  78. {
  79. LOG_TRACE(logAi);
  80. }
  81. void VCAI::availableCreaturesChanged(const CGDwelling *town)
  82. {
  83. LOG_TRACE(logAi);
  84. NET_EVENT_HANDLER;
  85. }
  86. void VCAI::heroMoved(const TryMoveHero & details)
  87. {
  88. LOG_TRACE(logAi);
  89. NET_EVENT_HANDLER;
  90. validateObject(details.id); //enemy hero may have left visible area
  91. if(details.result == TryMoveHero::TELEPORTATION)
  92. {
  93. const int3 from = CGHeroInstance::convertPosition(details.start, false),
  94. to = CGHeroInstance::convertPosition(details.end, false);
  95. const CGObjectInstance *o1 = frontOrNull(cb->getVisitableObjs(from)),
  96. *o2 = frontOrNull(cb->getVisitableObjs(to));
  97. if(o1 && o2 && o1->ID == Obj::SUBTERRANEAN_GATE && o2->ID == Obj::SUBTERRANEAN_GATE)
  98. {
  99. knownSubterraneanGates[o1] = o2;
  100. knownSubterraneanGates[o2] = o1;
  101. logAi->debugStream() << boost::format("Found a pair of subterranean gates between %s and %s!") % from % to;
  102. }
  103. }
  104. }
  105. void VCAI::stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute)
  106. {
  107. LOG_TRACE_PARAMS(logAi, "isAbsolute '%i'", isAbsolute);
  108. NET_EVENT_HANDLER;
  109. }
  110. void VCAI::heroInGarrisonChange(const CGTownInstance *town)
  111. {
  112. LOG_TRACE(logAi);
  113. NET_EVENT_HANDLER;
  114. }
  115. void VCAI::centerView(int3 pos, int focusTime)
  116. {
  117. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  118. NET_EVENT_HANDLER;
  119. }
  120. void VCAI::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  121. {
  122. LOG_TRACE(logAi);
  123. NET_EVENT_HANDLER;
  124. }
  125. void VCAI::artifactAssembled(const ArtifactLocation &al)
  126. {
  127. LOG_TRACE(logAi);
  128. NET_EVENT_HANDLER;
  129. }
  130. void VCAI::showTavernWindow(const CGObjectInstance *townOrTavern)
  131. {
  132. LOG_TRACE(logAi);
  133. NET_EVENT_HANDLER;
  134. }
  135. void VCAI::showThievesGuildWindow (const CGObjectInstance * obj)
  136. {
  137. LOG_TRACE(logAi);
  138. NET_EVENT_HANDLER;
  139. }
  140. void VCAI::playerBlocked(int reason, bool start)
  141. {
  142. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  143. NET_EVENT_HANDLER;
  144. if (start && reason == PlayerBlocked::UPCOMING_BATTLE)
  145. status.setBattle(UPCOMING_BATTLE);
  146. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  147. status.setMove(start);
  148. }
  149. void VCAI::showPuzzleMap()
  150. {
  151. LOG_TRACE(logAi);
  152. NET_EVENT_HANDLER;
  153. }
  154. void VCAI::showShipyardDialog(const IShipyard *obj)
  155. {
  156. LOG_TRACE(logAi);
  157. NET_EVENT_HANDLER;
  158. }
  159. void VCAI::gameOver(PlayerColor player, bool victory)
  160. {
  161. LOG_TRACE_PARAMS(logAi, "victory '%i'", victory);
  162. NET_EVENT_HANDLER;
  163. logAi->debugStream() << boost::format("Player %d: I heard that player %d %s.") % playerID % player.getNum() % (victory ? "won" : "lost");
  164. if(player == playerID)
  165. {
  166. if(victory)
  167. {
  168. logAi->debugStream() << "VCAI: I won! Incredible!";
  169. logAi->debugStream() << "Turn nr " << myCb->getDate();
  170. }
  171. else
  172. {
  173. logAi->debugStream() << "VCAI: Player " << player << " lost. It's me. What a disappointment! :(";
  174. }
  175. // //let's make Impossible difficulty finally standing to its name :>
  176. // if(myCb->getStartInfo()->difficulty == 4 && !victory)
  177. // {
  178. // //play dirty: crash the whole engine to avoid lose
  179. // //that way AI is unbeatable!
  180. // *(int*)nullptr = 666;
  181. // }
  182. // TODO - at least write some insults on stdout
  183. finish();
  184. }
  185. }
  186. void VCAI::artifactPut(const ArtifactLocation &al)
  187. {
  188. LOG_TRACE(logAi);
  189. NET_EVENT_HANDLER;
  190. }
  191. void VCAI::artifactRemoved(const ArtifactLocation &al)
  192. {
  193. LOG_TRACE(logAi);
  194. NET_EVENT_HANDLER;
  195. }
  196. void VCAI::stacksErased(const StackLocation &location)
  197. {
  198. LOG_TRACE(logAi);
  199. NET_EVENT_HANDLER;
  200. }
  201. void VCAI::artifactDisassembled(const ArtifactLocation &al)
  202. {
  203. LOG_TRACE(logAi);
  204. NET_EVENT_HANDLER;
  205. }
  206. void VCAI::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  207. {
  208. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->hoverName : std::string("n/a")));
  209. NET_EVENT_HANDLER;
  210. if(start)
  211. {
  212. markObjectVisited (visitedObj);
  213. erase_if_present(reservedObjs, visitedObj); //unreserve objects
  214. erase_if_present(reservedHeroesMap[visitor], visitedObj);
  215. completeGoal (Goals::GetObj(visitedObj->id.getNum()).sethero(visitor)); //we don't need to visit in anymore
  216. }
  217. status.heroVisit(visitedObj, start);
  218. }
  219. void VCAI::availableArtifactsChanged(const CGBlackMarket *bm /*= nullptr*/)
  220. {
  221. LOG_TRACE(logAi);
  222. NET_EVENT_HANDLER;
  223. }
  224. void VCAI::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  225. {
  226. LOG_TRACE(logAi);
  227. NET_EVENT_HANDLER;
  228. //buildArmyIn(town);
  229. //moveCreaturesToHero(town);
  230. }
  231. void VCAI::tileHidden(const std::unordered_set<int3, ShashInt3> &pos)
  232. {
  233. LOG_TRACE(logAi);
  234. NET_EVENT_HANDLER;
  235. validateVisitableObjs();
  236. }
  237. void VCAI::tileRevealed(const std::unordered_set<int3, ShashInt3> &pos)
  238. {
  239. LOG_TRACE(logAi);
  240. NET_EVENT_HANDLER;
  241. for(int3 tile : pos)
  242. for(const CGObjectInstance *obj : myCb->getVisitableObjs(tile))
  243. addVisitableObj(obj);
  244. }
  245. void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  246. {
  247. LOG_TRACE(logAi);
  248. NET_EVENT_HANDLER;
  249. auto firstHero = cb->getHero(hero1);
  250. auto secondHero = cb->getHero(hero2);
  251. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s and %s") % firstHero->name % secondHero->name));
  252. requestActionASAP([=]()
  253. {
  254. if (firstHero->getHeroStrength() > secondHero->getHeroStrength() && canGetArmy (firstHero, secondHero))
  255. pickBestCreatures (firstHero, secondHero);
  256. else if (canGetArmy (secondHero, firstHero))
  257. pickBestCreatures (secondHero, firstHero);
  258. completeGoal(Goals::AbstractGoal(Goals::VISIT_HERO).sethero(firstHero)); //TODO: what if we were visited by other hero in the meantime?
  259. completeGoal(Goals::AbstractGoal(Goals::VISIT_HERO).sethero(secondHero));
  260. //TODO: exchange artifacts
  261. answerQuery(query, 0);
  262. });
  263. }
  264. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  265. {
  266. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which % val);
  267. NET_EVENT_HANDLER;
  268. }
  269. void VCAI::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  270. {
  271. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  272. NET_EVENT_HANDLER;
  273. }
  274. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  275. {
  276. LOG_TRACE(logAi);
  277. NET_EVENT_HANDLER;
  278. }
  279. void VCAI::stackChangedType(const StackLocation &location, const CCreature &newType)
  280. {
  281. LOG_TRACE(logAi);
  282. NET_EVENT_HANDLER;
  283. }
  284. void VCAI::stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count)
  285. {
  286. LOG_TRACE(logAi);
  287. NET_EVENT_HANDLER;
  288. }
  289. void VCAI::newObject(const CGObjectInstance * obj)
  290. {
  291. LOG_TRACE(logAi);
  292. NET_EVENT_HANDLER;
  293. if(obj->isVisitable())
  294. addVisitableObj(obj);
  295. }
  296. void VCAI::objectRemoved(const CGObjectInstance *obj)
  297. {
  298. LOG_TRACE(logAi);
  299. NET_EVENT_HANDLER;
  300. erase_if_present(visitableObjs, obj);
  301. erase_if_present(alreadyVisited, obj);
  302. erase_if_present(reservedObjs, obj);
  303. for(auto &p : reservedHeroesMap)
  304. erase_if_present(p.second, obj);
  305. //TODO
  306. //there are other places where CGObjectinstance ptrs are stored...
  307. //
  308. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  309. {
  310. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  311. }
  312. }
  313. void VCAI::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  314. {
  315. LOG_TRACE(logAi);
  316. NET_EVENT_HANDLER;
  317. requestActionASAP([=]()
  318. {
  319. makePossibleUpgrades(visitor);
  320. });
  321. }
  322. void VCAI::playerBonusChanged(const Bonus &bonus, bool gain)
  323. {
  324. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  325. NET_EVENT_HANDLER;
  326. }
  327. void VCAI::newStackInserted(const StackLocation &location, const CStackInstance &stack)
  328. {
  329. LOG_TRACE(logAi);
  330. NET_EVENT_HANDLER;
  331. }
  332. void VCAI::heroCreated(const CGHeroInstance*)
  333. {
  334. LOG_TRACE(logAi);
  335. NET_EVENT_HANDLER;
  336. }
  337. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  338. {
  339. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  340. NET_EVENT_HANDLER;
  341. }
  342. void VCAI::showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID)
  343. {
  344. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  345. NET_EVENT_HANDLER;
  346. }
  347. void VCAI::requestRealized(PackageApplied *pa)
  348. {
  349. LOG_TRACE(logAi);
  350. NET_EVENT_HANDLER;
  351. if(status.haveTurn())
  352. {
  353. if(pa->packType == typeList.getTypeID<EndTurn>())
  354. if(pa->result)
  355. status.madeTurn();
  356. }
  357. if(pa->packType == typeList.getTypeID<QueryReply>())
  358. {
  359. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  360. }
  361. }
  362. void VCAI::receivedResource(int type, int val)
  363. {
  364. LOG_TRACE_PARAMS(logAi, "type '%i', val '%i'", type % val);
  365. NET_EVENT_HANDLER;
  366. }
  367. void VCAI::stacksSwapped(const StackLocation &loc1, const StackLocation &loc2)
  368. {
  369. LOG_TRACE(logAi);
  370. NET_EVENT_HANDLER;
  371. }
  372. void VCAI::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  373. {
  374. LOG_TRACE(logAi);
  375. NET_EVENT_HANDLER;
  376. }
  377. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  378. {
  379. LOG_TRACE(logAi);
  380. NET_EVENT_HANDLER;
  381. }
  382. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  383. {
  384. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  385. NET_EVENT_HANDLER;
  386. }
  387. void VCAI::battleResultsApplied()
  388. {
  389. LOG_TRACE(logAi);
  390. NET_EVENT_HANDLER;
  391. assert(status.getBattle() == ENDING_BATTLE);
  392. status.setBattle(NO_BATTLE);
  393. }
  394. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  395. {
  396. LOG_TRACE(logAi);
  397. NET_EVENT_HANDLER;
  398. if(sop->what == ObjProperty::OWNER)
  399. {
  400. if(sop->val == playerID.getNum())
  401. erase_if_present(visitableObjs, myCb->getObj(sop->id));
  402. //TODO restore lost obj
  403. }
  404. }
  405. void VCAI::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what)
  406. {
  407. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  408. NET_EVENT_HANDLER;
  409. }
  410. void VCAI::heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain)
  411. {
  412. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  413. NET_EVENT_HANDLER;
  414. }
  415. void VCAI::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  416. {
  417. LOG_TRACE(logAi);
  418. NET_EVENT_HANDLER;
  419. }
  420. void VCAI::init(shared_ptr<CCallback> CB)
  421. {
  422. LOG_TRACE(logAi);
  423. myCb = CB;
  424. cbc = CB;
  425. NET_EVENT_HANDLER;
  426. playerID = *myCb->getMyColor();
  427. myCb->waitTillRealize = true;
  428. myCb->unlockGsWhenWaiting = true;
  429. if(!fh)
  430. fh = new FuzzyHelper();
  431. retreiveVisitableObjs(visitableObjs);
  432. }
  433. void VCAI::yourTurn()
  434. {
  435. LOG_TRACE(logAi);
  436. NET_EVENT_HANDLER;
  437. status.startedTurn();
  438. makingTurn = make_unique<boost::thread>(&VCAI::makeTurn, this);
  439. }
  440. void VCAI::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, QueryID queryID)
  441. {
  442. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  443. NET_EVENT_HANDLER;
  444. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->name % hero->level));
  445. requestActionASAP([=]{ answerQuery(queryID, 0); });
  446. }
  447. void VCAI::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  448. {
  449. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  450. NET_EVENT_HANDLER;
  451. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  452. requestActionASAP([=]{ answerQuery(queryID, 0); });
  453. }
  454. void VCAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel)
  455. {
  456. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i'", text % askID % soundID % selection % cancel);
  457. NET_EVENT_HANDLER;
  458. int sel = 0;
  459. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  460. % components.size() % text));
  461. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  462. sel = components.size();
  463. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  464. sel = 1;
  465. requestActionASAP([=]()
  466. {
  467. answerQuery(askID, sel);
  468. });
  469. }
  470. void VCAI::showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  471. {
  472. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  473. NET_EVENT_HANDLER;
  474. std::string s1 = up ? up->nodeName() : "NONE";
  475. std::string s2 = down ? down->nodeName() : "NONE";
  476. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  477. //you can't request action from action-response thread
  478. requestActionASAP([=]()
  479. {
  480. pickBestCreatures (down, up);
  481. answerQuery(queryID, 0);
  482. });
  483. }
  484. void VCAI::saveGame(COSer<CSaveFile> &h, const int version)
  485. {
  486. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  487. NET_EVENT_HANDLER;
  488. validateVisitableObjs();
  489. CAdventureAI::saveGame(h, version);
  490. serializeInternal(h, version);
  491. }
  492. void VCAI::loadGame(CISer<CLoadFile> &h, const int version)
  493. {
  494. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  495. NET_EVENT_HANDLER;
  496. CAdventureAI::loadGame(h, version);
  497. serializeInternal(h, version);
  498. }
  499. void makePossibleUpgrades(const CArmedInstance *obj)
  500. {
  501. if(!obj)
  502. return;
  503. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  504. {
  505. if(const CStackInstance *s = obj->getStackPtr(SlotID(i)))
  506. {
  507. UpgradeInfo ui;
  508. cb->getUpgradeInfo(obj, SlotID(i), ui);
  509. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  510. {
  511. cb->upgradeCreature(obj, SlotID(i), ui.newID[0]);
  512. }
  513. }
  514. }
  515. }
  516. void VCAI::makeTurn()
  517. {
  518. MAKING_TURN;
  519. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  520. setThreadName("VCAI::makeTurn");
  521. logAi->debugStream() << boost::format("Player %d starting turn") % static_cast<int>(playerID.getNum());
  522. switch(cb->getDate(Date::DAY_OF_WEEK))
  523. {
  524. case 1:
  525. {
  526. townVisitsThisWeek.clear();
  527. std::vector<const CGObjectInstance *> objs;
  528. retreiveVisitableObjs(objs, true);
  529. for(const CGObjectInstance *obj : objs)
  530. {
  531. if (isWeeklyRevisitable(obj))
  532. {
  533. if (!vstd::contains(visitableObjs, obj))
  534. visitableObjs.push_back(obj);
  535. auto o = std::find (alreadyVisited.begin(), alreadyVisited.end(), obj);
  536. if (o != alreadyVisited.end())
  537. alreadyVisited.erase(o);
  538. }
  539. }
  540. }
  541. break;
  542. case 7: //reconsider strategy
  543. {
  544. if(auto h = primaryHero()) //check if our primary hero can handle danger
  545. {
  546. ui64 totalDanger = 0;
  547. int dangerousObjects = 0;
  548. std::vector<const CGObjectInstance *> objs;
  549. retreiveVisitableObjs(objs, false);
  550. for (auto obj : objs)
  551. {
  552. if (evaluateDanger(obj)) //potentilaly dnagerous
  553. {
  554. totalDanger += evaluateDanger(obj->visitablePos(), *h);
  555. ++dangerousObjects;
  556. }
  557. }
  558. ui64 averageDanger = totalDanger / std::max(dangerousObjects, 1);
  559. if (dangerousObjects && averageDanger > h->getHeroStrength())
  560. {
  561. setGoal (h, Goals::GatherArmy(averageDanger * SAFE_ATTACK_CONSTANT).sethero(h).setisAbstract(true));
  562. }
  563. }
  564. }
  565. break;
  566. }
  567. if(cb->getSelectedHero())
  568. cb->recalculatePaths();
  569. makeTurnInternal();
  570. makingTurn.reset();
  571. return;
  572. }
  573. void VCAI::makeTurnInternal()
  574. {
  575. saving = 0;
  576. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  577. for(const CGTownInstance *t : cb->getTownsInfo())
  578. moveCreaturesToHero(t);
  579. try
  580. {
  581. //Pick objects reserved in previous turn - we expect only nerby objects there
  582. auto reservedHeroesCopy = reservedHeroesMap; //work on copy => the map may be changed while iterating (eg because hero died when attempting a goal)
  583. for (auto hero : reservedHeroesCopy)
  584. {
  585. if(reservedHeroesMap.count(hero.first))
  586. continue; //hero might have been removed while we were in this loop
  587. if(!hero.first.validAndSet())
  588. {
  589. logAi->errorStream() << "Hero " << hero.first.name << " present on reserved map. Shouldn't be. ";
  590. continue;
  591. }
  592. cb->setSelection(hero.first.get());
  593. boost::sort (hero.second, isCloser);
  594. for (auto obj : hero.second)
  595. {
  596. if(!obj || !obj->defInfo || !cb->getObj(obj->id))
  597. {
  598. logAi->errorStream() << "Error: there is wrong object on list for hero " << hero.first->name;
  599. continue;
  600. }
  601. striveToGoal (Goals::VisitTile(obj->visitablePos()).sethero(hero.first));
  602. }
  603. }
  604. //now try to win
  605. striveToGoal(Goals::Win());
  606. //finally, continue our abstract long-term goals
  607. //heroes tend to die in the process and loose their goals, unsafe to iterate it
  608. std::vector<std::pair<HeroPtr, Goals::AbstractGoal> > safeCopy;
  609. boost::copy(lockedHeroes, std::back_inserter(safeCopy));
  610. typedef std::pair<HeroPtr, Goals::AbstractGoal> TItrType;
  611. auto lockedHeroesSorter = [](TItrType h1, TItrType h2) -> bool
  612. {
  613. return compareMovement (h1.first, h2.first);
  614. };
  615. boost::sort(safeCopy, lockedHeroesSorter);
  616. while (safeCopy.size()) //continue our goals
  617. {
  618. auto it = safeCopy.begin();
  619. if (it->first && it->first->tempOwner == playerID && vstd::contains(lockedHeroes, it->first)) //make sure hero still has his goal
  620. {
  621. cb->setSelection(*it->first);
  622. striveToGoal (it->second);
  623. }
  624. safeCopy.erase(it);
  625. }
  626. auto quests = myCb->getMyQuests();
  627. for (auto quest : quests)
  628. {
  629. striveToQuest (quest);
  630. }
  631. striveToGoal(Goals::Build()); //TODO: smarter building management
  632. }
  633. catch(boost::thread_interrupted &e)
  634. {
  635. logAi->debugStream() << "Making turn thread has been interrupted. We'll end without calling endTurn.";
  636. return;
  637. }
  638. catch(std::exception &e)
  639. {
  640. logAi->debugStream() << "Making turn thread has caught an exception: " << e.what();
  641. }
  642. endTurn();
  643. }
  644. bool VCAI::goVisitObj(const CGObjectInstance * obj, HeroPtr h)
  645. {
  646. int3 dst = obj->visitablePos();
  647. logAi->debugStream() << boost::format("%s will try to visit %s at (%s)") % h->name % obj->getHoverText() % strFromInt3(dst);
  648. return moveHeroToTile(dst, h);
  649. }
  650. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  651. {
  652. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->name % obj->getHoverText() % obj->pos);
  653. switch (obj->ID)
  654. {
  655. case Obj::CREATURE_GENERATOR1:
  656. recruitCreatures (dynamic_cast<const CGDwelling *>(obj));
  657. checkHeroArmy (h);
  658. break;
  659. case Obj::TOWN:
  660. moveCreaturesToHero (dynamic_cast<const CGTownInstance *>(obj));
  661. if (h->visitedTown) //we are inside, not just attacking
  662. {
  663. townVisitsThisWeek[h].push_back(h->visitedTown);
  664. if (!h->hasSpellbook() && cb->getResourceAmount(Res::GOLD) >= GameConstants::SPELLBOOK_GOLD_COST + saving[Res::GOLD] &&
  665. h->visitedTown->hasBuilt (BuildingID::MAGES_GUILD_1))
  666. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  667. }
  668. break;
  669. }
  670. }
  671. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  672. {
  673. if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
  674. {
  675. pickBestCreatures (t->visitingHero, t);
  676. }
  677. }
  678. bool VCAI::canGetArmy (const CGHeroInstance * army, const CGHeroInstance * source)
  679. { //TODO: merge with pickBestCreatures
  680. if(army->tempOwner != source->tempOwner)
  681. {
  682. logAi->errorStream() << "Why are we even considering exchange between heroes from different players?";
  683. return false;
  684. }
  685. const CArmedInstance *armies[] = {army, source};
  686. int armySize = 0;
  687. //we calculate total strength for each creature type available in armies
  688. std::map<const CCreature*, int> creToPower;
  689. for(auto armyPtr : armies)
  690. for(auto &i : armyPtr->Slots())
  691. {
  692. ++armySize;//TODO: allow splitting stacks?
  693. creToPower[i.second->type] += i.second->getPower();
  694. }
  695. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  696. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  697. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  698. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  699. {
  700. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  701. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  702. {
  703. return lhs.second < rhs.second;
  704. });
  705. bestArmy.push_back(creIt->first);
  706. creToPower.erase(creIt);
  707. if(creToPower.empty())
  708. break;
  709. }
  710. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  711. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  712. {
  713. for(auto armyPtr : armies)
  714. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  715. {
  716. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  717. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1 && armyPtr != army)) //can't take away last creature
  718. return true; //at least one exchange will be performed
  719. }
  720. }
  721. return false;
  722. }
  723. void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source)
  724. {
  725. //TODO - what if source is a hero (the last stack problem) -> it'd good to create a single stack of weakest cre
  726. const CArmedInstance *armies[] = {army, source};
  727. int armySize = 0;
  728. //we calculate total strength for each creature type available in armies
  729. std::map<const CCreature*, int> creToPower;
  730. for(auto armyPtr : armies)
  731. for(auto &i : armyPtr->Slots())
  732. {
  733. ++armySize;//TODO: allow splitting stacks?
  734. creToPower[i.second->type] += i.second->getPower();
  735. }
  736. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  737. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  738. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  739. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  740. {
  741. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  742. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  743. {
  744. return lhs.second < rhs.second;
  745. });
  746. bestArmy.push_back(creIt->first);
  747. creToPower.erase(creIt);
  748. if(creToPower.empty())
  749. break;
  750. }
  751. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  752. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  753. {
  754. for(auto armyPtr : armies)
  755. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  756. {
  757. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  758. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1 && armyPtr != army))
  759. cb->mergeOrSwapStacks(armyPtr, army, SlotID(j), SlotID(i));
  760. }
  761. }
  762. //TODO - having now strongest possible army, we may want to think about arranging stacks
  763. auto hero = dynamic_cast<const CGHeroInstance *>(army);
  764. if (hero)
  765. {
  766. checkHeroArmy (hero);
  767. }
  768. }
  769. void VCAI::recruitCreatures(const CGDwelling * d)
  770. {
  771. for(int i = 0; i < d->creatures.size(); i++)
  772. {
  773. if(!d->creatures[i].second.size())
  774. continue;
  775. int count = d->creatures[i].first;
  776. CreatureID creID = d->creatures[i].second.back();
  777. // const CCreature *c = VLC->creh->creatures[creID];
  778. // if(containsSavedRes(c->cost))
  779. // continue;
  780. amin(count, freeResources() / VLC->creh->creatures[creID]->cost);
  781. if(count > 0)
  782. cb->recruitCreatures(d, creID, count, i);
  783. }
  784. }
  785. bool VCAI::tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays)
  786. {
  787. if (!vstd::contains(t->town->buildings, building))
  788. return false; // no such building in town
  789. if (t->hasBuilt(building)) //Already built? Shouldn't happen in general
  790. return true;
  791. std::set<BuildingID> toBuild = cb->getBuildingRequiments(t, building);
  792. //erase all already built buildings
  793. for (auto buildIter = toBuild.begin(); buildIter != toBuild.end();)
  794. {
  795. if (t->hasBuilt(*buildIter))
  796. toBuild.erase(buildIter++);
  797. else
  798. buildIter++;
  799. }
  800. toBuild.insert(building);
  801. for(BuildingID buildID : toBuild)
  802. {
  803. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  804. if (canBuild == EBuildingState::HAVE_CAPITAL
  805. || canBuild == EBuildingState::FORBIDDEN
  806. || canBuild == EBuildingState::NO_WATER)
  807. return false; //we won't be able to build this
  808. }
  809. if (maxDays && toBuild.size() > maxDays)
  810. return false;
  811. TResources currentRes = cb->getResourceAmount();
  812. TResources income = estimateIncome();
  813. //TODO: calculate if we have enough resources to build it in maxDays
  814. for(const auto & buildID : toBuild)
  815. {
  816. const CBuilding *b = t->town->buildings.at(buildID);
  817. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  818. if(canBuild == EBuildingState::ALLOWED)
  819. {
  820. if(!containsSavedRes(b->resources))
  821. {
  822. logAi->debugStream() << boost::format("Player %d will build %s in town of %s at %s") % playerID % b->Name() % t->name % t->pos;
  823. cb->buildBuilding(t, buildID);
  824. return true;
  825. }
  826. continue;
  827. }
  828. else if(canBuild == EBuildingState::NO_RESOURCES)
  829. {
  830. TResources cost = t->town->buildings.at(buildID)->resources;
  831. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  832. {
  833. int diff = currentRes[i] - cost[i] + income[i];
  834. if(diff < 0)
  835. saving[i] = 1;
  836. }
  837. continue;
  838. }
  839. }
  840. return false;
  841. }
  842. bool VCAI::tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  843. {
  844. for(const auto & building : buildList)
  845. {
  846. if(t->hasBuilt(building))
  847. continue;
  848. if (tryBuildStructure(t, building, maxDays))
  849. return true;
  850. }
  851. return false; //Can't build anything
  852. }
  853. bool VCAI::tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  854. {
  855. for(const auto & building : buildList)
  856. {
  857. if(t->hasBuilt(building))
  858. continue;
  859. return tryBuildStructure(t, building, maxDays);
  860. }
  861. return false;//Nothing to build
  862. }
  863. void VCAI::buildStructure(const CGTownInstance * t)
  864. {
  865. //TODO make *real* town development system
  866. //TODO: faction-specific development: use special buildings, build dwellings in better order, etc
  867. //TODO: build resource silo, defences when needed
  868. //Possible - allow "locking" on specific building (build prerequisites and then building itself)
  869. //Set of buildings for different goals. Does not include any prerequisites.
  870. const BuildingID essential[] = {BuildingID::TAVERN, BuildingID::TOWN_HALL};
  871. const BuildingID goldSource[] = {BuildingID::TOWN_HALL, BuildingID::CITY_HALL, BuildingID::CAPITOL};
  872. const BuildingID unitsSource[] = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3,
  873. BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7};
  874. const BuildingID unitsUpgrade[] = { BuildingID::DWELL_LVL_1_UP, BuildingID::DWELL_LVL_2_UP, BuildingID::DWELL_LVL_3_UP,
  875. BuildingID::DWELL_LVL_4_UP, BuildingID::DWELL_LVL_5_UP, BuildingID::DWELL_LVL_6_UP, BuildingID::DWELL_LVL_7_UP};
  876. const BuildingID unitGrowth[] = { BuildingID::FORT, BuildingID::CITADEL, BuildingID::CASTLE, BuildingID::HORDE_1,
  877. BuildingID::HORDE_1_UPGR, BuildingID::HORDE_2, BuildingID::HORDE_2_UPGR};
  878. const BuildingID spells[] = {BuildingID::MAGES_GUILD_1, BuildingID::MAGES_GUILD_2, BuildingID::MAGES_GUILD_3,
  879. BuildingID::MAGES_GUILD_4, BuildingID::MAGES_GUILD_5};
  880. const BuildingID extra[] = {BuildingID::RESOURCE_SILO, BuildingID::SPECIAL_1, BuildingID::SPECIAL_2, BuildingID::SPECIAL_3,
  881. BuildingID::SPECIAL_4, BuildingID::SHIPYARD}; // all remaining buildings
  882. TResources currentRes = cb->getResourceAmount();
  883. TResources income = estimateIncome();
  884. if (tryBuildAnyStructure(t, std::vector<BuildingID>(essential, essential + ARRAY_COUNT(essential))))
  885. return;
  886. //we're running out of gold - try to build something gold-producing. Multiplier can be tweaked, 6 is minimum due to buildings costs
  887. if (currentRes[Res::GOLD] < income[Res::GOLD] * 6)
  888. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  889. return;
  890. if (cb->getDate(Date::DAY_OF_WEEK) > 6)// last 2 days of week - try to focus on growth
  891. {
  892. if (tryBuildNextStructure(t, std::vector<BuildingID>(unitGrowth, unitGrowth + ARRAY_COUNT(unitGrowth)), 2))
  893. return;
  894. }
  895. // first in-game week or second half of any week: try build dwellings
  896. if (cb->getDate(Date::DAY) < 7 || cb->getDate(Date::DAY_OF_WEEK) > 3)
  897. if (tryBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK)))
  898. return;
  899. //try to upgrade dwelling
  900. for(int i = 0; i < ARRAY_COUNT(unitsUpgrade); i++)
  901. {
  902. if (t->hasBuilt(unitsSource[i]) && !t->hasBuilt(unitsUpgrade[i]))
  903. {
  904. if (tryBuildStructure(t, unitsUpgrade[i]))
  905. return;
  906. }
  907. }
  908. //remaining tasks
  909. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  910. return;
  911. if (tryBuildNextStructure(t, std::vector<BuildingID>(spells, spells + ARRAY_COUNT(spells))))
  912. return;
  913. if (tryBuildAnyStructure(t, std::vector<BuildingID>(extra, extra + ARRAY_COUNT(extra))))
  914. return;
  915. }
  916. std::vector<const CGObjectInstance *> VCAI::getPossibleDestinations(HeroPtr h)
  917. {
  918. validateVisitableObjs();
  919. std::vector<const CGObjectInstance *> possibleDestinations;
  920. for(const CGObjectInstance *obj : visitableObjs)
  921. {
  922. if(cb->getPathInfo(obj->visitablePos())->reachable() && !obj->wasVisited(playerID) &&
  923. (obj->tempOwner != playerID || isWeeklyRevisitable(obj))) //flag or get weekly resources / creatures
  924. possibleDestinations.push_back(obj);
  925. }
  926. boost::sort(possibleDestinations, isCloser);
  927. possibleDestinations.erase(boost::remove_if(possibleDestinations, [&](const CGObjectInstance *obj) -> bool
  928. {
  929. const int3 pos = obj->visitablePos();
  930. if(vstd::contains(alreadyVisited, obj))
  931. return true;
  932. if(!isSafeToVisit(h, pos))
  933. return true;
  934. if (!shouldVisit(h, obj))
  935. return true;
  936. if (vstd::contains(reservedObjs, obj)) //does checking for our own reserved objects make sense? here?
  937. return true;
  938. const CGObjectInstance *topObj = cb->getVisitableObjs(pos).back(); //it may be hero visiting this obj
  939. //we don't try visiting object on which allied or owned hero stands
  940. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  941. if(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  942. return true;
  943. return false;
  944. }),possibleDestinations.end());
  945. return possibleDestinations;
  946. }
  947. void VCAI::wander(HeroPtr h)
  948. {
  949. while(1)
  950. {
  951. validateVisitableObjs();
  952. std::vector <ObjectIdRef> dests;
  953. range::copy(reservedHeroesMap[h], std::back_inserter(dests));
  954. if (!dests.size())
  955. range::copy(getPossibleDestinations(h), std::back_inserter(dests));
  956. if(!dests.size())
  957. {
  958. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  959. {
  960. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  961. };
  962. std::vector<const CGTownInstance *> townsReachable;
  963. std::vector<const CGTownInstance *> townsNotReachable;
  964. for(const CGTownInstance *t : cb->getTownsInfo())
  965. {
  966. if(!t->visitingHero && howManyReinforcementsCanGet(h,t) && !vstd::contains(townVisitsThisWeek[h], t))
  967. {
  968. if(isReachable(t))
  969. townsReachable.push_back(t);
  970. else
  971. townsNotReachable.push_back(t);
  972. }
  973. }
  974. if(townsReachable.size())
  975. {
  976. boost::sort(townsReachable, compareReinforcements);
  977. dests.emplace_back(townsReachable.back());
  978. }
  979. else if(townsNotReachable.size())
  980. {
  981. boost::sort(townsNotReachable, compareReinforcements);
  982. //TODO pick the truly best
  983. const CGTownInstance *t = townsNotReachable.back();
  984. logAi->debugStream() << boost::format("%s can't reach any town, we'll try to make our way to %s at %s") % h->name % t->name % t->visitablePos();
  985. int3 pos1 = h->pos;
  986. striveToGoal(Goals::VisitTile(t->visitablePos()).sethero(h));
  987. if (pos1 == h->pos && h == primaryHero()) //hero can't move
  988. {
  989. if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST && cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES && cb->getAvailableHeroes(t).size())
  990. recruitHero(t);
  991. }
  992. break;
  993. }
  994. else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST)
  995. {
  996. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  997. erase_if(towns, [](const CGTownInstance *t) -> bool
  998. {
  999. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1000. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1001. return true;
  1002. return false;
  1003. });
  1004. boost::sort(towns, compareArmyStrength);
  1005. if(towns.size())
  1006. recruitHero(towns.back());
  1007. break;
  1008. }
  1009. else
  1010. {
  1011. logAi->debugStream() << "Nowhere more to go...";
  1012. break;
  1013. }
  1014. }
  1015. const ObjectIdRef&dest = dests.front();
  1016. logAi->debugStream() << boost::format("Of all %d destinations, object oid=%d seems nice") % dests.size() % dest.id.getNum();
  1017. if(!goVisitObj(dest, h))
  1018. {
  1019. if(!dest)
  1020. {
  1021. logAi->debugStream() << boost::format("Visit attempt made the object (id=%d) gone...") % dest.id.getNum();
  1022. }
  1023. else
  1024. {
  1025. logAi->debugStream() << boost::format("Hero %s apparently used all MPs (%d left)") % h->name % h->movement;
  1026. reserveObject(h, dest); //reserve that object - we predict it will be reached soon
  1027. //removed - do not forget abstract goal so easily
  1028. //setGoal(h, CGoal(VISIT_TILE).sethero(h).settile(dest->visitablePos()));
  1029. }
  1030. break;
  1031. }
  1032. if(h->visitedTown)
  1033. {
  1034. townVisitsThisWeek[h].push_back(h->visitedTown);
  1035. buildArmyIn(h->visitedTown);
  1036. break;
  1037. }
  1038. }
  1039. }
  1040. void VCAI::setGoal(HeroPtr h, const Goals::AbstractGoal &goal)
  1041. { //TODO: check for presence?
  1042. if (goal.invalid())
  1043. erase_if_present(lockedHeroes, h);
  1044. else
  1045. lockedHeroes[h] = Goals::AbstractGoal(goal).setisElementar(false); //always evaluate goals before realizing
  1046. }
  1047. void VCAI::setGoal(HeroPtr h, Goals::EGoals goalType)
  1048. {
  1049. if (goalType == Goals::INVALID)
  1050. erase_if_present(lockedHeroes, h);
  1051. else
  1052. lockedHeroes[h] = Goals::AbstractGoal(goalType).setisElementar(false); //always evaluate goals before realizing;
  1053. }
  1054. void VCAI::completeGoal (const Goals::AbstractGoal &goal)
  1055. {
  1056. if (const CGHeroInstance * h = goal.hero.get(true))
  1057. {
  1058. auto it = lockedHeroes.find(h);
  1059. if (it != lockedHeroes.end())
  1060. if (it->second.goalType == goal.goalType)
  1061. lockedHeroes.erase(it); //goal fulfilled, free hero
  1062. }
  1063. }
  1064. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  1065. {
  1066. NET_EVENT_HANDLER;
  1067. assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1068. status.setBattle(ONGOING_BATTLE);
  1069. const CGObjectInstance *presumedEnemy = backOrNull(cb->getVisitableObjs(tile)); //may be nullptr in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit
  1070. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->hoverName : "unknown enemy") % tile);
  1071. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1072. }
  1073. void VCAI::battleEnd(const BattleResult *br)
  1074. {
  1075. NET_EVENT_HANDLER;
  1076. assert(status.getBattle() == ONGOING_BATTLE);
  1077. status.setBattle(ENDING_BATTLE);
  1078. bool won = br->winner == myCb->battleGetMySide();
  1079. logAi->debugStream() << boost::format("Player %d: I %s the %s!") % playerID % (won ? "won" : "lost") % battlename;
  1080. battlename.clear();
  1081. CAdventureAI::battleEnd(br);
  1082. }
  1083. void VCAI::waitTillFree()
  1084. {
  1085. auto unlock = vstd::makeUnlockSharedGuard(cb->getGsMutex());
  1086. status.waitTillFree();
  1087. }
  1088. void VCAI::markObjectVisited (const CGObjectInstance *obj)
  1089. {
  1090. if(dynamic_cast<const CGVisitableOPH *>(obj) || //we may want to wisit it with another hero
  1091. dynamic_cast<const CGBonusingObject *>(obj) || //or another time
  1092. (obj->ID == Obj::MONSTER))
  1093. return;
  1094. alreadyVisited.push_back(obj);
  1095. }
  1096. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance *obj)
  1097. {
  1098. reservedObjs.push_back(obj);
  1099. reservedHeroesMap[h].push_back(obj);
  1100. logAi->debugStream() << "reserved object id=" << obj->id << "; address=" << (intptr_t)obj << "; name=" << obj->getHoverText();
  1101. }
  1102. void VCAI::validateVisitableObjs()
  1103. {
  1104. std::vector<const CGObjectInstance *> hlp;
  1105. retreiveVisitableObjs(hlp, true);
  1106. std::string errorMsg;
  1107. auto shouldBeErased = [&](const CGObjectInstance *obj) -> bool
  1108. {
  1109. if(!vstd::contains(hlp, obj))
  1110. {
  1111. logAi->errorStream() << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << errorMsg;
  1112. return true;
  1113. }
  1114. return false;
  1115. };
  1116. //errorMsg is captured by ref so lambda will take the new text
  1117. errorMsg = " shouldn't be on the visitable objects list!";
  1118. erase_if(visitableObjs, shouldBeErased);
  1119. for(auto &p : reservedHeroesMap)
  1120. {
  1121. errorMsg = " shouldn't be on list for hero " + p.first->name + "!";
  1122. erase_if(p.second, shouldBeErased);
  1123. }
  1124. errorMsg = " shouldn't be on the reserved objs list!";
  1125. erase_if(reservedObjs, shouldBeErased);
  1126. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1127. errorMsg = " shouldn't be on the already visited objs list!";
  1128. erase_if(alreadyVisited, shouldBeErased);
  1129. }
  1130. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1131. {
  1132. foreach_tile_pos([&](const int3 &pos)
  1133. {
  1134. for(const CGObjectInstance *obj : myCb->getVisitableObjs(pos, false))
  1135. {
  1136. if(includeOwned || obj->tempOwner != playerID)
  1137. out.push_back(obj);
  1138. }
  1139. });
  1140. }
  1141. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1142. {
  1143. std::vector<const CGObjectInstance *> ret;
  1144. retreiveVisitableObjs(ret, true);
  1145. erase_if(ret, [](const CGObjectInstance *obj)
  1146. {
  1147. return obj->tempOwner != ai->playerID;
  1148. });
  1149. return ret;
  1150. }
  1151. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  1152. {
  1153. visitableObjs.push_back(obj);
  1154. helperObjInfo[obj] = ObjInfo(obj);
  1155. }
  1156. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1157. {
  1158. for(const CGObjectInstance *obj : ai->visitableObjs)
  1159. {
  1160. if(obj->ID == 5 && obj->subID == aid)
  1161. return obj;
  1162. }
  1163. return nullptr;
  1164. //TODO what if more than one artifact is available? return them all or some slection criteria
  1165. }
  1166. bool VCAI::isAccessible(const int3 &pos)
  1167. {
  1168. //TODO precalculate for speed
  1169. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1170. {
  1171. if(isAccessibleForHero(pos, h))
  1172. return true;
  1173. }
  1174. return false;
  1175. }
  1176. HeroPtr VCAI::getHeroWithGrail() const
  1177. {
  1178. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1179. if(h->hasArt(2)) //grail
  1180. return h;
  1181. return nullptr;
  1182. }
  1183. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> &predicate)
  1184. {
  1185. //TODO smarter definition of unvisited
  1186. for(const CGObjectInstance *obj : visitableObjs)
  1187. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1188. return obj;
  1189. return nullptr;
  1190. }
  1191. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies /*= false*/) const
  1192. {
  1193. cb->setSelection(*h);
  1194. if (!includeAllies)
  1195. { //don't visit tile occupied by allied hero
  1196. for (auto obj : cb->getVisitableObjs(pos))
  1197. {
  1198. if (obj->ID == Obj::HERO && obj->tempOwner == h->tempOwner && obj != h.get())
  1199. return false;
  1200. }
  1201. }
  1202. return cb->getPathInfo(pos)->reachable();
  1203. }
  1204. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1205. {
  1206. logAi->debugStream() << boost::format("Moving hero %s to tile %s") % h->name % dst;
  1207. int3 startHpos = h->visitablePos();
  1208. bool ret = false;
  1209. if(startHpos == dst)
  1210. {
  1211. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1212. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1213. waitTillFree(); //movement may cause battle or blocking dialog
  1214. ret = true;
  1215. }
  1216. else
  1217. {
  1218. CGPath path;
  1219. cb->getPath2(dst, path);
  1220. if(path.nodes.empty())
  1221. {
  1222. logAi->errorStream() << "Hero " << h->name << " cannot reach " << dst;
  1223. //setGoal(h, INVALID);
  1224. completeGoal (Goals::AbstractGoal(Goals::VISIT_TILE).sethero(h));
  1225. cb->recalculatePaths();
  1226. throw std::runtime_error("Wrong move order!");
  1227. }
  1228. int i=path.nodes.size()-1;
  1229. for(; i>0; i--)
  1230. {
  1231. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1232. if(path.nodes[i-1].turns)
  1233. {
  1234. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1235. break;
  1236. }
  1237. int3 endpos = path.nodes[i-1].coord;
  1238. if(endpos == h->visitablePos())
  1239. //if (endpos == h->pos)
  1240. continue;
  1241. // if(i > 1)
  1242. // {
  1243. // int3 afterEndPos = path.nodes[i-2].coord;
  1244. // if(afterEndPos.z != endpos.z)
  1245. //
  1246. // }
  1247. //logAi->debugStream() << "Moving " << h->name << " from " << h->getPosition() << " to " << endpos;
  1248. cb->moveHero(*h, CGHeroInstance::convertPosition(endpos, true));
  1249. waitTillFree(); //movement may cause battle or blocking dialog
  1250. boost::this_thread::interruption_point();
  1251. if(!h) //we lost hero - remove all tasks assigned to him/her
  1252. {
  1253. lostHero(h);
  1254. //we need to throw, otherwise hero will be assigned to sth again
  1255. throw std::runtime_error("Hero was lost!");
  1256. }
  1257. }
  1258. ret = !i;
  1259. }
  1260. if (auto visitedObject = frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1261. {
  1262. performObjectInteraction (visitedObject, h);
  1263. //BNLOG("Hero %s moved from %s to %s at %s", h->name % startHpos % visitedObject->hoverName % h->visitablePos());
  1264. //throw goalFulfilledException (CGoal(GET_OBJ).setobjid(visitedObject->id));
  1265. }
  1266. if(h) //we could have lost hero after last move
  1267. {
  1268. cb->recalculatePaths();
  1269. if (startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1270. {
  1271. throw cannotFulfillGoalException("Invalid path found!");
  1272. }
  1273. }
  1274. logAi->debugStream() << boost::format("Hero %s moved from %s to %s. Returning %d.") % h->name % startHpos % h->visitablePos() % ret;
  1275. return ret;
  1276. }
  1277. void VCAI::tryRealize(Goals::Explore g)
  1278. {
  1279. throw cannotFulfillGoalException("EXPLORE is not a elementar goal!");
  1280. }
  1281. void VCAI::tryRealize(Goals::RecruitHero g)
  1282. {
  1283. if(const CGTownInstance *t = findTownWithTavern())
  1284. {
  1285. recruitHero(t, true);
  1286. //TODO try to free way to blocked town
  1287. //TODO: adventure map tavern or prison?
  1288. }
  1289. }
  1290. void VCAI::tryRealize(Goals::VisitTile g)
  1291. {
  1292. //cb->recalculatePaths();
  1293. if(!g.hero->movement)
  1294. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1295. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1296. {
  1297. logAi->warnStream() << boost::format("Why do I want to move hero %s to tile %s? Already standing on that tile! ") % g.hero->name % g.tile;
  1298. throw goalFulfilledException (g);
  1299. }
  1300. //if(!g.isBlockedBorderGate(g.tile))
  1301. //{
  1302. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1303. {
  1304. throw goalFulfilledException (g);
  1305. }
  1306. //}
  1307. //else
  1308. // throw cannotFulfillGoalException("There's a blocked gate!, we should never be here"); //CLEAR_WAY_TO should get keymaster tent
  1309. }
  1310. void VCAI::tryRealize(Goals::VisitHero g)
  1311. {
  1312. if(!g.hero->movement)
  1313. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1314. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1315. {
  1316. throw goalFulfilledException (g);
  1317. }
  1318. }
  1319. void VCAI::tryRealize(Goals::BuildThis g)
  1320. {
  1321. const CGTownInstance *t = g.town;
  1322. if(!t && g.hero)
  1323. t = g.hero->visitedTown;
  1324. if(!t)
  1325. {
  1326. for(const CGTownInstance *t : cb->getTownsInfo())
  1327. {
  1328. switch(cb->canBuildStructure(t, BuildingID(g.bid)))
  1329. {
  1330. case EBuildingState::ALLOWED:
  1331. cb->buildBuilding(t, BuildingID(g.bid));
  1332. return;
  1333. default:
  1334. break;
  1335. }
  1336. }
  1337. }
  1338. else if(cb->canBuildStructure(t, BuildingID(g.bid)) == EBuildingState::ALLOWED)
  1339. {
  1340. cb->buildBuilding(t, BuildingID(g.bid));
  1341. return;
  1342. }
  1343. throw cannotFulfillGoalException("Cannot build a given structure!");
  1344. }
  1345. void VCAI::tryRealize(Goals::DigAtTile g)
  1346. {
  1347. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1348. if (g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1349. {
  1350. cb->dig(g.hero.get());
  1351. setGoal(g.hero, Goals::INVALID); // finished digging
  1352. }
  1353. else
  1354. {
  1355. ai->lockedHeroes[g.hero] = g; //hero who tries to dig shouldn't do anything else
  1356. throw cannotFulfillGoalException("A hero can't dig!\n");
  1357. }
  1358. }
  1359. void VCAI::tryRealize(Goals::CollectRes g)
  1360. {
  1361. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1362. throw cannotFulfillGoalException("Goal is already fulfilled!");
  1363. if(const CGObjectInstance *obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1364. {
  1365. if(const IMarket *m = IMarket::castFrom(obj, false))
  1366. {
  1367. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  1368. {
  1369. if(i == g.resID) continue;
  1370. int toGive, toGet;
  1371. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1372. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1373. //TODO trade only as much as needed
  1374. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1375. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1376. return;
  1377. }
  1378. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1379. }
  1380. else
  1381. {
  1382. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1383. }
  1384. }
  1385. else
  1386. {
  1387. saving[g.resID] = 1;
  1388. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1389. }
  1390. }
  1391. void VCAI::tryRealize(Goals::Build g)
  1392. {
  1393. performTypicalActions(); //TODO: separate build and wander
  1394. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1395. }
  1396. void VCAI::tryRealize(Goals::Invalid g)
  1397. {
  1398. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1399. }
  1400. void VCAI::tryRealize(Goals::AbstractGoal g)
  1401. {
  1402. logAi->debugStream() << boost::format("Attempting realizing goal with code %s") % g.name();
  1403. throw cannotFulfillGoalException("Unknown type of goal !");
  1404. }
  1405. const CGTownInstance * VCAI::findTownWithTavern() const
  1406. {
  1407. for(const CGTownInstance *t : cb->getTownsInfo())
  1408. if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
  1409. return t;
  1410. return nullptr;
  1411. }
  1412. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1413. {
  1414. std::vector<HeroPtr> ret;
  1415. boost::copy(cb->getHeroesInfo(), std::back_inserter(ret));
  1416. for(auto h : lockedHeroes)
  1417. {
  1418. //if (!h.second.invalid()) //we can use heroes without valid goal
  1419. if (h.second.goalType == Goals::DIG_AT_TILE || !h.first->movement) //experiment: use all heroes that have movement left, TODO: unlock heroes that couldn't realize their goals
  1420. erase_if_present(ret, h.first);
  1421. }
  1422. return ret;
  1423. }
  1424. HeroPtr VCAI::primaryHero() const
  1425. {
  1426. auto hs = cb->getHeroesInfo();
  1427. boost::sort(hs, compareHeroStrength);
  1428. if(hs.empty())
  1429. return nullptr;
  1430. return hs.back();
  1431. }
  1432. void VCAI::endTurn()
  1433. {
  1434. logAi->debugStream() << "Player " << static_cast<int>(playerID.getNum()) << " ends turn";
  1435. if(!status.haveTurn())
  1436. {
  1437. logAi->errorStream() << "Not having turn at the end of turn???";
  1438. }
  1439. do
  1440. {
  1441. cb->endTurn();
  1442. } 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
  1443. logAi->debugStream() << "Player " << static_cast<int>(playerID.getNum()) << " ended turn";
  1444. }
  1445. bool VCAI::fulfillsGoal (Goals::AbstractGoal &goal, Goals::AbstractGoal &mainGoal)
  1446. {
  1447. if (mainGoal.goalType == Goals::GET_OBJ && goal.goalType == Goals::VISIT_TILE) //deduce that GET_OBJ was completed by visiting object's tile
  1448. { //TODO: more universal mechanism
  1449. if (cb->getObj(ObjectInstanceID(mainGoal.objid))->visitablePos() == goal.tile)
  1450. return true;
  1451. }
  1452. return false;
  1453. }
  1454. bool VCAI::fulfillsGoal (Goals::AbstractGoal &goal, const Goals::AbstractGoal &mainGoal)
  1455. {
  1456. return fulfillsGoal (goal, const_cast<Goals::AbstractGoal&>(mainGoal));
  1457. }
  1458. void VCAI::striveToGoal(const Goals::AbstractGoal &ultimateGoal)
  1459. {
  1460. if (ultimateGoal.invalid())
  1461. return;
  1462. std::shared_ptr<Goals::AbstractGoal> abstractGoal = make_shared<Goals::AbstractGoal>(Goals::Invalid());
  1463. while(1)
  1464. {
  1465. std::shared_ptr<Goals::AbstractGoal> goal = make_shared<Goals::AbstractGoal>(ultimateGoal); //FIXME: preserve subclass of goal
  1466. logAi->debugStream() << boost::format("Striving to goal of type %s") % ultimateGoal.name();
  1467. int maxGoals = 100; //preventing deadlock for mutually dependent goals, FIXME: do not try to realize goal when loop didn't suceed
  1468. while(!goal->isElementar && !goal->isAbstract && maxGoals)
  1469. {
  1470. logAi->debugStream() << boost::format("Considering goal %s") % goal->name();
  1471. try
  1472. {
  1473. boost::this_thread::interruption_point();
  1474. goal = goal->whatToDoToAchieve(); //FIXME: why it calls always base class?
  1475. --maxGoals;
  1476. }
  1477. catch(std::exception &e)
  1478. {
  1479. logAi->debugStream() << boost::format("Goal %s decomposition failed: %s") % goal->name() % e.what();
  1480. //setGoal (goal.hero, INVALID); //test: if we don't know how to realize goal, we should abandon it for now
  1481. return;
  1482. }
  1483. }
  1484. try
  1485. {
  1486. boost::this_thread::interruption_point();
  1487. if (!maxGoals)
  1488. {
  1489. std::runtime_error e("Too many subgoals, don't know what to do");
  1490. throw (e);
  1491. }
  1492. if (goal->hero) //lock this hero to fulfill ultimate goal
  1493. {
  1494. if (maxGoals)
  1495. {
  1496. setGoal(goal->hero, *goal.get());
  1497. }
  1498. else
  1499. {
  1500. setGoal(goal->hero, Goals::INVALID); // we seemingly don't know what to do with hero
  1501. }
  1502. }
  1503. if (goal->isAbstract)
  1504. {
  1505. abstractGoal = goal; //allow only one abstract goal per call
  1506. logAi->debugStream() << boost::format("Choosing abstract goal %s") % goal->name();
  1507. break;
  1508. }
  1509. else
  1510. tryRealize(*goal);
  1511. boost::this_thread::interruption_point();
  1512. }
  1513. catch(boost::thread_interrupted &e)
  1514. {
  1515. logAi->debugStream() << boost::format("Player %d: Making turn thread received an interruption!") % playerID;
  1516. throw; //rethrow, we want to truly end this thread
  1517. }
  1518. catch(goalFulfilledException &e)
  1519. {
  1520. completeGoal (*goal);
  1521. if (fulfillsGoal (*goal, ultimateGoal) || maxGoals > 98) //completed goal was main goal //TODO: find better condition
  1522. return;
  1523. }
  1524. catch(std::exception &e)
  1525. {
  1526. logAi->debugStream() << boost::format("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.") % goal->name() % ultimateGoal.name();
  1527. logAi->debugStream() << boost::format("The error message was: %s") % e.what();
  1528. break;
  1529. }
  1530. }
  1531. //TODO: save abstract goals not related to hero
  1532. //TODO: refactor, duplicated code
  1533. if (!abstractGoal->invalid()) //try to realize our one goal
  1534. {
  1535. while (1)
  1536. {
  1537. std::shared_ptr<Goals::AbstractGoal> goal(abstractGoal);
  1538. goal->setisAbstract(false);
  1539. int maxGoals = 50;
  1540. while (!goal->isElementar && maxGoals) //find elementar goal and fulfill it
  1541. {
  1542. try
  1543. {
  1544. boost::this_thread::interruption_point();
  1545. goal = goal->whatToDoToAchieve();
  1546. --maxGoals;
  1547. }
  1548. catch(std::exception &e)
  1549. {
  1550. logAi->debugStream() << boost::format("Goal %s decomposition failed: %s") % goal->name() % e.what();
  1551. //setGoal (goal.hero, INVALID);
  1552. return;
  1553. }
  1554. }
  1555. try
  1556. {
  1557. boost::this_thread::interruption_point();
  1558. if (!maxGoals)
  1559. {
  1560. std::runtime_error e("Too many subgoals, don't know what to do");
  1561. throw (e);
  1562. }
  1563. tryRealize(*goal);
  1564. boost::this_thread::interruption_point();
  1565. }
  1566. catch(boost::thread_interrupted &e)
  1567. {
  1568. logAi->debugStream() << boost::format("Player %d: Making turn thread received an interruption!") % playerID;
  1569. throw; //rethrow, we want to truly end this thread
  1570. }
  1571. catch(goalFulfilledException &e)
  1572. {
  1573. completeGoal (*goal); //FIXME: deduce that we have realized GET_OBJ goal
  1574. if (fulfillsGoal (*goal, *abstractGoal) || maxGoals > 98) //completed goal was main goal
  1575. return;
  1576. }
  1577. catch(std::exception &e)
  1578. {
  1579. logAi->debugStream() << boost::format("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.") % goal->name() % ultimateGoal.name();
  1580. logAi->debugStream() << boost::format("The error message was: %s") % e.what();
  1581. break;
  1582. }
  1583. }
  1584. }
  1585. }
  1586. void VCAI::striveToQuest (const QuestInfo &q)
  1587. {
  1588. if (q.quest->missionType && q.quest->progress != CQuest::COMPLETE) //FIXME: quests are never synchronized. Pointer handling needed
  1589. {
  1590. MetaString ms;
  1591. q.quest->getRolloverText(ms, false);
  1592. logAi->debugStream() << boost::format("Trying to realize quest: %s") % ms.toString();
  1593. auto heroes = cb->getHeroesInfo();
  1594. switch (q.quest->missionType)
  1595. {
  1596. case CQuest::MISSION_ART:
  1597. {
  1598. for (auto hero : heroes) //TODO: remove duplicated code?
  1599. {
  1600. if (q.quest->checkQuest(hero))
  1601. {
  1602. striveToGoal (Goals::GetObj(q.obj->id.getNum()).sethero(hero));
  1603. return;
  1604. }
  1605. }
  1606. for (auto art : q.quest->m5arts)
  1607. {
  1608. striveToGoal (Goals::GetArtOfType(art)); //TODO: transport?
  1609. }
  1610. break;
  1611. }
  1612. case CQuest::MISSION_HERO:
  1613. {
  1614. //striveToGoal (CGoal(RECRUIT_HERO));
  1615. for (auto hero : heroes)
  1616. {
  1617. if (q.quest->checkQuest(hero))
  1618. {
  1619. striveToGoal (Goals::GetObj(q.obj->id.getNum()).sethero(hero));
  1620. return;
  1621. }
  1622. }
  1623. striveToGoal (Goals::FindObj(Obj::PRISON)); //rule of a thumb - quest heroes usually are locked in prisons
  1624. //BNLOG ("Don't know how to recruit hero with id %d\n", q.quest->m13489val);
  1625. break;
  1626. }
  1627. case CQuest::MISSION_ARMY:
  1628. {
  1629. for (auto hero : heroes)
  1630. {
  1631. if (q.quest->checkQuest(hero)) //veyr bad info - stacks can be split between multiple heroes :(
  1632. {
  1633. striveToGoal (Goals::GetObj(q.obj->id.getNum()).sethero(hero));
  1634. return;
  1635. }
  1636. }
  1637. for (auto creature : q.quest->m6creatures)
  1638. {
  1639. striveToGoal (Goals::GatherTroops(creature.type->idNumber, creature.count));
  1640. }
  1641. //TODO: exchange armies... oh my
  1642. //BNLOG ("Don't know how to recruit %d of %s\n", (int)(creature.count) % creature.type->namePl);
  1643. break;
  1644. }
  1645. case CQuest::MISSION_RESOURCES:
  1646. {
  1647. if (heroes.size())
  1648. {
  1649. if (q.quest->checkQuest(heroes.front())) //it doesn't matter which hero it is
  1650. {
  1651. striveToGoal (Goals::VisitTile(q.tile));
  1652. }
  1653. else
  1654. {
  1655. for (int i = 0; i < q.quest->m7resources.size(); ++i)
  1656. {
  1657. if (q.quest->m7resources[i])
  1658. striveToGoal (Goals::CollectRes(i, q.quest->m7resources[i]));
  1659. }
  1660. }
  1661. }
  1662. else
  1663. striveToGoal (Goals::RecruitHero()); //FIXME: checkQuest requires any hero belonging to player :(
  1664. break;
  1665. }
  1666. case CQuest::MISSION_KILL_HERO:
  1667. case CQuest::MISSION_KILL_CREATURE:
  1668. {
  1669. auto obj = cb->getObjByQuestIdentifier(q.quest->m13489val);
  1670. if (obj)
  1671. striveToGoal (Goals::GetObj(obj->id.getNum()));
  1672. else
  1673. striveToGoal (Goals::VisitTile(q.tile)); //visit seer hut
  1674. break;
  1675. }
  1676. case CQuest::MISSION_PRIMARY_STAT:
  1677. {
  1678. auto heroes = cb->getHeroesInfo();
  1679. for (auto hero : heroes)
  1680. {
  1681. if (q.quest->checkQuest(hero))
  1682. {
  1683. striveToGoal (Goals::GetObj(q.obj->id.getNum()).sethero(hero));
  1684. return;
  1685. }
  1686. }
  1687. for (int i = 0; i < q.quest->m2stats.size(); ++i)
  1688. {
  1689. logAi->debugStream() << boost::format("Don't know how to increase primary stat %d") % i;
  1690. }
  1691. break;
  1692. }
  1693. case CQuest::MISSION_LEVEL:
  1694. {
  1695. auto heroes = cb->getHeroesInfo();
  1696. for (auto hero : heroes)
  1697. {
  1698. if (q.quest->checkQuest(hero))
  1699. {
  1700. striveToGoal (Goals::VisitTile(q.tile).sethero(hero)); //TODO: causes infinite loop :/
  1701. return;
  1702. }
  1703. }
  1704. logAi->debugStream() << boost::format("Don't know how to reach hero level %d") % q.quest->m13489val;
  1705. break;
  1706. }
  1707. case CQuest::MISSION_PLAYER:
  1708. {
  1709. if (playerID.getNum() != q.quest->m13489val)
  1710. logAi->debugStream() << boost::format("Can't be player of color %d") % q.quest->m13489val;
  1711. break;
  1712. }
  1713. case CQuest::MISSION_KEYMASTER:
  1714. {
  1715. striveToGoal (Goals::FindObj(Obj::KEYMASTER, q.obj->subID));
  1716. break;
  1717. }
  1718. }
  1719. }
  1720. }
  1721. void VCAI::performTypicalActions()
  1722. {
  1723. for(const CGTownInstance *t : cb->getTownsInfo())
  1724. {
  1725. logAi->debugStream() << boost::format("Looking into %s") % t->name;
  1726. buildStructure(t);
  1727. buildArmyIn(t);
  1728. if(!ai->primaryHero() ||
  1729. (t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero())))
  1730. {
  1731. recruitHero(t);
  1732. buildArmyIn(t);
  1733. }
  1734. }
  1735. for(auto h : getUnblockedHeroes())
  1736. {
  1737. logAi->debugStream() << boost::format("Looking into %s, MP=%d") % h->name.c_str() % h->movement;
  1738. makePossibleUpgrades(*h);
  1739. cb->setSelection(*h);
  1740. try
  1741. {
  1742. wander(h);
  1743. }
  1744. catch(std::exception &e)
  1745. {
  1746. logAi->debugStream() << boost::format("Cannot use this hero anymore, received exception: %s") % e.what();
  1747. continue;
  1748. }
  1749. }
  1750. }
  1751. void VCAI::buildArmyIn(const CGTownInstance * t)
  1752. {
  1753. makePossibleUpgrades(t->visitingHero);
  1754. makePossibleUpgrades(t);
  1755. recruitCreatures(t);
  1756. moveCreaturesToHero(t);
  1757. }
  1758. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h)
  1759. {
  1760. TimeCheck tc("looking for best exploration neighbour");
  1761. std::map<int3, int> dstToRevealedTiles;
  1762. for(crint3 dir : dirs)
  1763. if(cb->isInTheMap(hpos+dir))
  1764. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir) * isSafeToVisit(h, hpos + dir);
  1765. auto best = dstToRevealedTiles.begin();
  1766. best->second *= cb->getPathInfo(best->first)->reachable();
  1767. best->second *= cb->getPathInfo(best->first)->accessible == CGPathNode::ACCESSIBLE;
  1768. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  1769. {
  1770. const CGPathNode *pn = cb->getPathInfo(i->first);
  1771. //const TerrainTile *t = cb->getTile(i->first);
  1772. if(best->second < i->second && i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  1773. best = i;
  1774. }
  1775. if(best->second)
  1776. return best->first;
  1777. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  1778. }
  1779. int3 VCAI::explorationNewPoint(int radius, HeroPtr h, std::vector<std::vector<int3> > &tiles)
  1780. {
  1781. TimeCheck tc("looking for new exploration point");
  1782. logAi->debugStream() << "Looking for an another place for exploration...";
  1783. tiles.resize(radius);
  1784. foreach_tile_pos([&](const int3 &pos)
  1785. {
  1786. if(!cb->isVisible(pos))
  1787. tiles[0].push_back(pos);
  1788. });
  1789. for (int i = 1; i < radius; i++)
  1790. {
  1791. getVisibleNeighbours(tiles[i-1], tiles[i]);
  1792. removeDuplicates(tiles[i]);
  1793. for(const int3 &tile : tiles[i])
  1794. {
  1795. if(cb->getPathInfo(tile)->reachable() && isSafeToVisit(h, tile) && howManyTilesWillBeDiscovered(tile, radius) && !isBlockedBorderGate(tile))
  1796. {
  1797. return tile;
  1798. }
  1799. }
  1800. }
  1801. throw cannotFulfillGoalException("No accessible tile will bring discoveries!");
  1802. }
  1803. TResources VCAI::estimateIncome() const
  1804. {
  1805. TResources ret;
  1806. for(const CGTownInstance *t : cb->getTownsInfo())
  1807. {
  1808. ret[Res::GOLD] += t->dailyIncome();
  1809. //TODO duplikuje newturn
  1810. if(t->hasBuilt(BuildingID::RESOURCE_SILO)) //there is resource silo
  1811. {
  1812. if(t->town->primaryRes == Res::WOOD_AND_ORE) //we'll give wood and ore
  1813. {
  1814. ret[Res::WOOD] ++;
  1815. ret[Res::ORE] ++;
  1816. }
  1817. else
  1818. {
  1819. ret[t->town->primaryRes] ++;
  1820. }
  1821. }
  1822. }
  1823. for(const CGObjectInstance *obj : getFlaggedObjects())
  1824. {
  1825. if(obj->ID == Obj::MINE)
  1826. {
  1827. switch(obj->subID)
  1828. {
  1829. case Res::WOOD:
  1830. case Res::ORE:
  1831. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  1832. break;
  1833. case Res::GOLD:
  1834. case 7: //abandoned mine -> also gold
  1835. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  1836. break;
  1837. default:
  1838. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  1839. break;
  1840. }
  1841. }
  1842. }
  1843. return ret;
  1844. }
  1845. bool VCAI::containsSavedRes(const TResources &cost) const
  1846. {
  1847. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1848. {
  1849. if(saving[i] && cost[i])
  1850. return true;
  1851. }
  1852. return false;
  1853. }
  1854. void VCAI::checkHeroArmy (HeroPtr h)
  1855. {
  1856. auto it = lockedHeroes.find(h);
  1857. if (it != lockedHeroes.end())
  1858. {
  1859. if (it->second.goalType == Goals::GATHER_ARMY && it->second.value <= h->getArmyStrength())
  1860. completeGoal(Goals::GatherArmy(it->second.value).sethero(h));
  1861. }
  1862. }
  1863. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  1864. {
  1865. logAi->debugStream() << boost::format("Trying to recruit a hero in %s at %s") % t->name % t->visitablePos();
  1866. if(auto availableHero = frontOrNull(cb->getAvailableHeroes(t)))
  1867. cb->recruitHero(t, availableHero);
  1868. else if(throwing)
  1869. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  1870. }
  1871. void VCAI::finish()
  1872. {
  1873. if(makingTurn)
  1874. makingTurn->interrupt();
  1875. }
  1876. void VCAI::requestActionASAP(std::function<void()> whatToDo)
  1877. {
  1878. // static boost::mutex m;
  1879. // boost::unique_lock<boost::mutex> mylock(m);
  1880. boost::barrier b(2);
  1881. boost::thread newThread([&b,this,whatToDo]()
  1882. {
  1883. setThreadName("VCAI::requestActionASAP::helper");
  1884. SET_GLOBAL_STATE(this);
  1885. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  1886. b.wait();
  1887. whatToDo();
  1888. });
  1889. b.wait();
  1890. }
  1891. void VCAI::lostHero(HeroPtr h)
  1892. {
  1893. logAi->debugStream() << boost::format("I lost my hero %s. It's best to forget and move on.") % h.name;
  1894. erase_if_present(lockedHeroes, h);
  1895. for(auto obj : reservedHeroesMap[h])
  1896. {
  1897. erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  1898. }
  1899. erase_if_present(reservedHeroesMap, h);
  1900. }
  1901. void VCAI::answerQuery(QueryID queryID, int selection)
  1902. {
  1903. logAi->debugStream() << boost::format("I'll answer the query %d giving the choice %d") % queryID % selection;
  1904. if(queryID != QueryID(-1))
  1905. {
  1906. cb->selectionMade(selection, queryID);
  1907. }
  1908. else
  1909. {
  1910. logAi->debugStream() << boost::format("Since the query ID is %d, the answer won't be sent. This is not a real query!") % queryID;
  1911. //do nothing
  1912. }
  1913. }
  1914. void VCAI::requestSent(const CPackForServer *pack, int requestID)
  1915. {
  1916. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  1917. if(auto reply = dynamic_cast<const QueryReply*>(pack))
  1918. {
  1919. status.attemptedAnsweringQuery(reply->qid, requestID);
  1920. }
  1921. }
  1922. std::string VCAI::getBattleAIName() const
  1923. {
  1924. if(settings["server"]["neutralAI"].getType() == JsonNode::DATA_STRING)
  1925. return settings["server"]["neutralAI"].String();
  1926. else
  1927. return "StupidAI";
  1928. }
  1929. void VCAI::validateObject(const CGObjectInstance *obj)
  1930. {
  1931. validateObject(obj->id);
  1932. }
  1933. void VCAI::validateObject(ObjectIdRef obj)
  1934. {
  1935. auto matchesId = [&] (const CGObjectInstance *hlpObj) -> bool { return hlpObj->id == obj.id; };
  1936. if(!obj)
  1937. {
  1938. erase_if(visitableObjs, matchesId);
  1939. for(auto &p : reservedHeroesMap)
  1940. erase_if(p.second, matchesId);
  1941. erase_if(reservedObjs, matchesId);
  1942. }
  1943. }
  1944. TResources VCAI::freeResources() const
  1945. {
  1946. TResources myRes = cb->getResourceAmount();
  1947. myRes[Res::GOLD] -= GOLD_RESERVE;
  1948. vstd::amax(myRes[Res::GOLD], 0);
  1949. return myRes;
  1950. }
  1951. AIStatus::AIStatus()
  1952. {
  1953. battle = NO_BATTLE;
  1954. havingTurn = false;
  1955. ongoingHeroMovement = false;
  1956. }
  1957. AIStatus::~AIStatus()
  1958. {
  1959. }
  1960. void AIStatus::setBattle(BattleState BS)
  1961. {
  1962. boost::unique_lock<boost::mutex> lock(mx);
  1963. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  1964. battle = BS;
  1965. cv.notify_all();
  1966. }
  1967. BattleState AIStatus::getBattle()
  1968. {
  1969. boost::unique_lock<boost::mutex> lock(mx);
  1970. return battle;
  1971. }
  1972. void AIStatus::addQuery(QueryID ID, std::string description)
  1973. {
  1974. boost::unique_lock<boost::mutex> lock(mx);
  1975. if(ID == QueryID(-1))
  1976. {
  1977. logAi->debugStream() << boost::format("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s") % ID % description;
  1978. return;
  1979. }
  1980. assert(!vstd::contains(remainingQueries, ID));
  1981. assert(ID.getNum() >= 0);
  1982. remainingQueries[ID] = description;
  1983. cv.notify_all();
  1984. logAi->debugStream() << boost::format("Adding query %d - %s. Total queries count: %d") % ID % description % remainingQueries.size();
  1985. }
  1986. void AIStatus::removeQuery(QueryID ID)
  1987. {
  1988. boost::unique_lock<boost::mutex> lock(mx);
  1989. assert(vstd::contains(remainingQueries, ID));
  1990. std::string description = remainingQueries[ID];
  1991. remainingQueries.erase(ID);
  1992. cv.notify_all();
  1993. logAi->debugStream() << boost::format("Removing query %d - %s. Total queries count: %d") % ID % description % remainingQueries.size();
  1994. }
  1995. int AIStatus::getQueriesCount()
  1996. {
  1997. boost::unique_lock<boost::mutex> lock(mx);
  1998. return remainingQueries.size();
  1999. }
  2000. void AIStatus::startedTurn()
  2001. {
  2002. boost::unique_lock<boost::mutex> lock(mx);
  2003. havingTurn = true;
  2004. cv.notify_all();
  2005. }
  2006. void AIStatus::madeTurn()
  2007. {
  2008. boost::unique_lock<boost::mutex> lock(mx);
  2009. havingTurn = false;
  2010. cv.notify_all();
  2011. }
  2012. void AIStatus::waitTillFree()
  2013. {
  2014. boost::unique_lock<boost::mutex> lock(mx);
  2015. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  2016. cv.timed_wait(lock, boost::posix_time::milliseconds(100));
  2017. }
  2018. bool AIStatus::haveTurn()
  2019. {
  2020. boost::unique_lock<boost::mutex> lock(mx);
  2021. return havingTurn;
  2022. }
  2023. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  2024. {
  2025. boost::unique_lock<boost::mutex> lock(mx);
  2026. assert(vstd::contains(remainingQueries, queryID));
  2027. std::string description = remainingQueries[queryID];
  2028. logAi->debugStream() << boost::format("Attempted answering query %d - %s. Request id=%d. Waiting for results...") % queryID % description % answerRequestID;
  2029. requestToQueryID[answerRequestID] = queryID;
  2030. }
  2031. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2032. {
  2033. assert(vstd::contains(requestToQueryID, answerRequestID));
  2034. QueryID query = requestToQueryID[answerRequestID];
  2035. assert(vstd::contains(remainingQueries, query));
  2036. requestToQueryID.erase(answerRequestID);
  2037. if(result)
  2038. {
  2039. removeQuery(query);
  2040. }
  2041. else
  2042. {
  2043. logAi->errorStream() << "Something went really wrong, failed to answer query " << query << ": " << remainingQueries[query];
  2044. //TODO safely retry
  2045. }
  2046. }
  2047. void AIStatus::heroVisit(const CGObjectInstance *obj, bool started)
  2048. {
  2049. boost::unique_lock<boost::mutex> lock(mx);
  2050. if(started)
  2051. objectsBeingVisited.push_back(obj);
  2052. else
  2053. {
  2054. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  2055. // causing visit to hero on the other side.
  2056. // However, we are guaranteed that start/end visit notification maintain stack order.
  2057. assert(!objectsBeingVisited.empty());
  2058. objectsBeingVisited.pop_back();
  2059. }
  2060. cv.notify_all();
  2061. }
  2062. void AIStatus::setMove(bool ongoing)
  2063. {
  2064. boost::unique_lock<boost::mutex> lock(mx);
  2065. ongoingHeroMovement = ongoing;
  2066. cv.notify_all();
  2067. }
  2068. SectorMap::SectorMap()
  2069. {
  2070. // int3 sizes = cb->getMapSize();
  2071. // sector.resize(sizes.x);
  2072. // for(auto &i : sector)
  2073. // i.resize(sizes.y);
  2074. //
  2075. // for(auto &i : sector)
  2076. // for(auto &j : i)
  2077. // j.resize(sizes.z, 0);
  2078. update();
  2079. }
  2080. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  2081. {
  2082. if(t->blocked && !t->visitable)
  2083. {
  2084. sec = NOT_AVAILABLE;
  2085. return true;
  2086. }
  2087. return false;
  2088. }
  2089. bool markIfBlocked(ui8 &sec, crint3 pos)
  2090. {
  2091. return markIfBlocked(sec, pos, cb->getTile(pos));
  2092. }
  2093. void SectorMap::update()
  2094. {
  2095. clear();
  2096. int curSector = 3; //0 is invisible, 1 is not explored
  2097. foreach_tile_pos([&](crint3 pos)
  2098. {
  2099. if(retreiveTile(pos) == NOT_CHECKED)
  2100. {
  2101. if(!markIfBlocked(retreiveTile(pos), pos))
  2102. exploreNewSector(pos, curSector++);
  2103. }
  2104. });
  2105. valid = true;
  2106. }
  2107. void SectorMap::clear()
  2108. {
  2109. sector = cb->getVisibilityMap();
  2110. valid = false;
  2111. }
  2112. void SectorMap::exploreNewSector(crint3 pos, int num)
  2113. {
  2114. Sector &s = infoOnSectors[num];
  2115. s.id = num;
  2116. s.water = cb->getTile(pos)->isWater();
  2117. std::queue<int3> toVisit;
  2118. toVisit.push(pos);
  2119. while(!toVisit.empty())
  2120. {
  2121. int3 curPos = toVisit.front();
  2122. toVisit.pop();
  2123. ui8 &sec = retreiveTile(curPos);
  2124. if(sec == NOT_CHECKED)
  2125. {
  2126. const TerrainTile *t = cb->getTile(curPos);
  2127. if(!markIfBlocked(sec, curPos, t))
  2128. {
  2129. if(t->isWater() == s.water) //sector is only-water or only-land
  2130. {
  2131. sec = num;
  2132. s.tiles.push_back(curPos);
  2133. foreach_neighbour(curPos, [&](crint3 neighPos)
  2134. {
  2135. if(retreiveTile(neighPos) == NOT_CHECKED)
  2136. {
  2137. toVisit.push(neighPos);
  2138. //parent[neighPos] = curPos;
  2139. }
  2140. const TerrainTile *nt = cb->getTile(neighPos, false);
  2141. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt))
  2142. {
  2143. s.embarkmentPoints.push_back(neighPos);
  2144. }
  2145. });
  2146. if(t->visitable && vstd::contains(ai->knownSubterraneanGates, t->visitableObjects.front()))
  2147. toVisit.push(ai->knownSubterraneanGates[t->visitableObjects.front()]->visitablePos());
  2148. }
  2149. }
  2150. }
  2151. }
  2152. removeDuplicates(s.embarkmentPoints);
  2153. }
  2154. void SectorMap::write(crstring fname)
  2155. {
  2156. std::ofstream out(fname);
  2157. for(int k = 0; k < cb->getMapSize().z; k++)
  2158. {
  2159. for(int j = 0; j < cb->getMapSize().y; j++)
  2160. {
  2161. for(int i = 0; i < cb->getMapSize().x; i++)
  2162. {
  2163. out << (int)sector[i][j][k] << '\t';
  2164. }
  2165. out << std::endl;
  2166. }
  2167. out << std::endl;
  2168. }
  2169. }
  2170. bool isWeeklyRevisitable (const CGObjectInstance * obj)
  2171. { //TODO: allow polling of remaining creatures in dwelling
  2172. if (dynamic_cast<const CGVisitableOPW *>(obj) || //ensures future compatibility, unlike IDs
  2173. dynamic_cast<const CGDwelling *>(obj) ||
  2174. dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  2175. return true;
  2176. switch (obj->ID)
  2177. {
  2178. case Obj::STABLES:
  2179. case Obj::MAGIC_WELL:
  2180. case Obj::HILL_FORT:
  2181. return true;
  2182. case Obj::BORDER_GATE:
  2183. case Obj::BORDERGUARD:
  2184. return (dynamic_cast <const CGKeys *>(obj))->wasMyColorVisited (ai->playerID); //FIXME: they could be revisited sooner than in a week
  2185. }
  2186. return false;
  2187. }
  2188. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2189. {
  2190. switch (obj->ID)
  2191. {
  2192. case Obj::BORDERGUARD:
  2193. case Obj::BORDER_GATE:
  2194. {
  2195. for (auto q : ai->myCb->getMyQuests())
  2196. {
  2197. if (q.obj == obj)
  2198. {
  2199. return false; // do not visit guards or gates when wandering
  2200. }
  2201. }
  2202. return true; //we don't have this quest yet
  2203. }
  2204. case Obj::SEER_HUT:
  2205. case Obj::QUEST_GUARD:
  2206. {
  2207. for (auto q : ai->myCb->getMyQuests())
  2208. {
  2209. if (q.obj == obj)
  2210. {
  2211. if (q.quest->checkQuest(*h))
  2212. return true; //we completed the quest
  2213. else
  2214. return false; //we can't complete this quest
  2215. }
  2216. }
  2217. return true; //we don't have this quest yet
  2218. }
  2219. case Obj::CREATURE_GENERATOR1:
  2220. {
  2221. if (obj->tempOwner != h->tempOwner)
  2222. return true; //flag just in case
  2223. bool canRecruitCreatures = false;
  2224. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2225. for(auto level : d->creatures)
  2226. {
  2227. for(auto c : level.second)
  2228. {
  2229. if (h->getSlotFor(CreatureID(c)) != SlotID())
  2230. canRecruitCreatures = true;
  2231. }
  2232. }
  2233. return canRecruitCreatures;
  2234. }
  2235. case Obj::HILL_FORT:
  2236. {
  2237. for (auto slot : h->Slots())
  2238. {
  2239. if (slot.second->type->upgrades.size())
  2240. return true; //TODO: check price?
  2241. }
  2242. return false;
  2243. }
  2244. case Obj::MONOLITH1:
  2245. case Obj::MONOLITH2:
  2246. case Obj::MONOLITH3:
  2247. case Obj::WHIRLPOOL:
  2248. //TODO: mechanism for handling monoliths
  2249. return false;
  2250. case Obj::SCHOOL_OF_MAGIC:
  2251. case Obj::SCHOOL_OF_WAR:
  2252. {
  2253. TResources myRes = ai->myCb->getResourceAmount();
  2254. if (myRes[Res::GOLD] - GOLD_RESERVE < 1000)
  2255. return false;
  2256. }
  2257. break;
  2258. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2259. if (h->level < 12)
  2260. return false;
  2261. break;
  2262. case Obj::TREE_OF_KNOWLEDGE:
  2263. {
  2264. TResources myRes = ai->myCb->getResourceAmount();
  2265. if (myRes[Res::GOLD] - GOLD_RESERVE < 2000 || myRes[Res::GEMS] < 10)
  2266. return false;
  2267. }
  2268. break;
  2269. case Obj::MAGIC_WELL:
  2270. return h->mana < h->manaLimit();
  2271. case Obj::PRISON:
  2272. return ai->myCb->getHeroesInfo().size() < GameConstants::MAX_HEROES_PER_PLAYER;
  2273. case Obj::BOAT:
  2274. return false;
  2275. //Boats are handled by pathfinder
  2276. }
  2277. if (obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  2278. return false;
  2279. return true;
  2280. }
  2281. int3 SectorMap::firstTileToGet(HeroPtr h, crint3 dst)
  2282. {
  2283. int sourceSector = retreiveTile(h->visitablePos()),
  2284. destinationSector = retreiveTile(dst);
  2285. if(sourceSector != destinationSector)
  2286. {
  2287. const Sector *src = &infoOnSectors[sourceSector],
  2288. *dst = &infoOnSectors[destinationSector];
  2289. std::map<const Sector*, const Sector*> preds;
  2290. std::queue<const Sector *> sq;
  2291. sq.push(src);
  2292. while(!sq.empty())
  2293. {
  2294. const Sector *s = sq.front();
  2295. sq.pop();
  2296. for(int3 ep : s->embarkmentPoints)
  2297. {
  2298. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  2299. //preds[s].push_back(neigh);
  2300. if(!preds[neigh])
  2301. {
  2302. preds[neigh] = s;
  2303. sq.push(neigh);
  2304. }
  2305. }
  2306. //TODO consider other types of connections between sectors?
  2307. }
  2308. if(!preds[dst])
  2309. {
  2310. write("test.txt");
  2311. ai->completeGoal (Goals::Explore(h)); //if we can't find the way, seemingly all tiles were explored
  2312. //TODO: more organized way?
  2313. throw cannotFulfillGoalException(boost::str(boost::format("Cannot find connection between sectors %d and %d") % src->id % dst->id));
  2314. }
  2315. std::vector<const Sector*> toTraverse;
  2316. toTraverse.push_back(dst);
  2317. while(toTraverse.back() != src)
  2318. {
  2319. toTraverse.push_back(preds[toTraverse.back()]);
  2320. }
  2321. if(preds[dst])
  2322. {
  2323. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  2324. if(!src->water && sectorToReach->water) //embark
  2325. {
  2326. //embark on ship -> look for an EP with a boat
  2327. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  2328. {
  2329. const TerrainTile *t = cb->getTile(pos);
  2330. return t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT
  2331. && retreiveTile(pos) == sectorToReach->id;
  2332. });
  2333. if(firstEP != src->embarkmentPoints.end())
  2334. {
  2335. return *firstEP;
  2336. }
  2337. else
  2338. {
  2339. //we need to find a shipyard with an access to the desired sector's EP
  2340. //TODO what about Summon Boat spell?
  2341. std::vector<const IShipyard *> shipyards;
  2342. for(const CGTownInstance *t : cb->getTownsInfo())
  2343. {
  2344. if(t->hasBuilt(BuildingID::SHIPYARD))
  2345. shipyards.push_back(t);
  2346. }
  2347. std::vector<const CGObjectInstance*> visObjs;
  2348. ai->retreiveVisitableObjs(visObjs, true);
  2349. for(const CGObjectInstance *obj : visObjs)
  2350. {
  2351. if(obj->ID != Obj::TOWN) //towns were handled in the previous loop
  2352. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  2353. shipyards.push_back(shipyard);
  2354. }
  2355. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  2356. {
  2357. return shipyard->shipyardStatus() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  2358. }),shipyards.end());
  2359. if(!shipyards.size())
  2360. {
  2361. //TODO consider possibility of building shipyard in a town
  2362. throw cannotFulfillGoalException("There is no known shipyard!");
  2363. }
  2364. //we have only shipyards that possibly can build ships onto the appropriate EP
  2365. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  2366. {
  2367. return s->o->tempOwner == ai->playerID;
  2368. });
  2369. if(ownedGoodShipyard != shipyards.end())
  2370. {
  2371. const IShipyard *s = *ownedGoodShipyard;
  2372. TResources shipCost;
  2373. s->getBoatCost(shipCost);
  2374. if(cb->getResourceAmount().canAfford(shipCost))
  2375. {
  2376. int3 ret = s->bestLocation();
  2377. cb->buildBoat(s);
  2378. return ret;
  2379. }
  2380. else
  2381. {
  2382. //TODO gather res
  2383. throw cannotFulfillGoalException("Not enough resources to build a boat");
  2384. }
  2385. }
  2386. else
  2387. {
  2388. //TODO pick best shipyard to take over
  2389. return shipyards.front()->o->visitablePos();
  2390. }
  2391. }
  2392. }
  2393. else if(src->water && !sectorToReach->water)
  2394. {
  2395. //TODO
  2396. //disembark
  2397. }
  2398. else
  2399. {
  2400. //TODO
  2401. //transition between two land/water sectors. Monolith? Whirlpool? ...
  2402. throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  2403. }
  2404. }
  2405. else
  2406. {
  2407. throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  2408. }
  2409. }
  2410. else
  2411. {
  2412. makeParentBFS(h->visitablePos());
  2413. int3 curtile = dst;
  2414. while(curtile != h->visitablePos())
  2415. {
  2416. if(cb->getPathInfo(curtile)->reachable())
  2417. {
  2418. return curtile;
  2419. }
  2420. else
  2421. {
  2422. auto i = parent.find(curtile);
  2423. if(i != parent.end())
  2424. {
  2425. assert(curtile != i->second);
  2426. curtile = i->second;
  2427. }
  2428. else
  2429. throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  2430. }
  2431. }
  2432. }
  2433. throw cannotFulfillGoalException("Impossible happened.");
  2434. }
  2435. void SectorMap::makeParentBFS(crint3 source)
  2436. {
  2437. parent.clear();
  2438. int mySector = retreiveTile(source);
  2439. std::queue<int3> toVisit;
  2440. toVisit.push(source);
  2441. while(!toVisit.empty())
  2442. {
  2443. int3 curPos = toVisit.front();
  2444. toVisit.pop();
  2445. ui8 &sec = retreiveTile(curPos);
  2446. assert(sec == mySector); //consider only tiles from the same sector
  2447. UNUSED(sec);
  2448. //const TerrainTile *t = cb->getTile(curPos);
  2449. foreach_neighbour(curPos, [&](crint3 neighPos)
  2450. {
  2451. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  2452. {
  2453. toVisit.push(neighPos);
  2454. parent[neighPos] = curPos;
  2455. }
  2456. });
  2457. }
  2458. }
  2459. unsigned char & SectorMap::retreiveTile(crint3 pos)
  2460. {
  2461. return retreiveTileN(sector, pos);
  2462. }
  2463. const CGObjectInstance * ObjectIdRef::operator->() const
  2464. {
  2465. return cb->getObj(id, false);
  2466. }
  2467. ObjectIdRef::operator const CGObjectInstance*() const
  2468. {
  2469. return cb->getObj(id, false);
  2470. }
  2471. ObjectIdRef::ObjectIdRef(ObjectInstanceID _id) : id(_id)
  2472. {
  2473. }
  2474. ObjectIdRef::ObjectIdRef(const CGObjectInstance *obj) : id(obj->id)
  2475. {
  2476. }
  2477. bool ObjectIdRef::operator<(const ObjectIdRef &rhs) const
  2478. {
  2479. return id < rhs.id;
  2480. }
  2481. HeroPtr::HeroPtr(const CGHeroInstance *H)
  2482. {
  2483. if(!H)
  2484. {
  2485. //init from nullptr should equal to default init
  2486. *this = HeroPtr();
  2487. return;
  2488. }
  2489. h = H;
  2490. name = h->name;
  2491. hid = H->id;
  2492. // infosCount[ai->playerID][hid]++;
  2493. }
  2494. HeroPtr::HeroPtr()
  2495. {
  2496. h = nullptr;
  2497. hid = ObjectInstanceID();
  2498. }
  2499. HeroPtr::~HeroPtr()
  2500. {
  2501. // if(hid >= 0)
  2502. // infosCount[ai->playerID][hid]--;
  2503. }
  2504. bool HeroPtr::operator<(const HeroPtr &rhs) const
  2505. {
  2506. return hid < rhs.hid;
  2507. }
  2508. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull /*= false*/) const
  2509. {
  2510. //TODO? check if these all assertions every time we get info about hero affect efficiency
  2511. //
  2512. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  2513. assert(doWeExpectNull || h);
  2514. if(h)
  2515. {
  2516. auto obj = cb->getObj(hid);
  2517. const bool owned = obj && obj->tempOwner == ai->playerID;
  2518. if(doWeExpectNull && !owned)
  2519. {
  2520. return nullptr;
  2521. }
  2522. else
  2523. {
  2524. assert(obj);
  2525. assert(owned);
  2526. }
  2527. }
  2528. return h;
  2529. }
  2530. const CGHeroInstance * HeroPtr::operator->() const
  2531. {
  2532. return get();
  2533. }
  2534. bool HeroPtr::validAndSet() const
  2535. {
  2536. return get(true);
  2537. }
  2538. const CGHeroInstance * HeroPtr::operator*() const
  2539. {
  2540. return get();
  2541. }