VCAI.cpp 96 KB

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