VCAI.cpp 82 KB

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