AIUtility.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /*
  2. * AIUtility.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "AIUtility.h"
  12. #include "VCAI.h"
  13. #include "Fuzzy.h"
  14. #include "../../lib/UnlockGuard.h"
  15. #include "../../lib/CConfigHandler.h"
  16. #include "../../lib/CHeroHandler.h"
  17. #include "../../lib/mapObjects/CBank.h"
  18. #include "../../lib/mapObjects/CGTownInstance.h"
  19. #include "../../lib/mapObjects/CQuest.h"
  20. #include "../../lib/mapping/CMapDefines.h"
  21. extern boost::thread_specific_ptr<CCallback> cb;
  22. extern boost::thread_specific_ptr<VCAI> ai;
  23. extern FuzzyHelper * fh;
  24. //extern static const int3 dirs[8];
  25. const CGObjectInstance * ObjectIdRef::operator->() const
  26. {
  27. return cb->getObj(id, false);
  28. }
  29. ObjectIdRef::operator const CGObjectInstance *() const
  30. {
  31. return cb->getObj(id, false);
  32. }
  33. ObjectIdRef::ObjectIdRef(ObjectInstanceID _id)
  34. : id(_id)
  35. {
  36. }
  37. ObjectIdRef::ObjectIdRef(const CGObjectInstance * obj)
  38. : id(obj->id)
  39. {
  40. }
  41. bool ObjectIdRef::operator<(const ObjectIdRef & rhs) const
  42. {
  43. return id < rhs.id;
  44. }
  45. HeroPtr::HeroPtr(const CGHeroInstance * H)
  46. {
  47. if(!H)
  48. {
  49. //init from nullptr should equal to default init
  50. *this = HeroPtr();
  51. return;
  52. }
  53. h = H;
  54. name = h->name;
  55. hid = H->id;
  56. // infosCount[ai->playerID][hid]++;
  57. }
  58. HeroPtr::HeroPtr()
  59. {
  60. h = nullptr;
  61. hid = ObjectInstanceID();
  62. }
  63. HeroPtr::~HeroPtr()
  64. {
  65. // if(hid >= 0)
  66. // infosCount[ai->playerID][hid]--;
  67. }
  68. bool HeroPtr::operator<(const HeroPtr & rhs) const
  69. {
  70. return hid < rhs.hid;
  71. }
  72. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull) const
  73. {
  74. //TODO? check if these all assertions every time we get info about hero affect efficiency
  75. //
  76. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  77. assert(doWeExpectNull || h);
  78. if(h)
  79. {
  80. auto obj = cb->getObj(hid);
  81. const bool owned = obj && obj->tempOwner == ai->playerID;
  82. if(doWeExpectNull && !owned)
  83. {
  84. return nullptr;
  85. }
  86. else
  87. {
  88. assert(obj);
  89. assert(owned);
  90. }
  91. }
  92. return h;
  93. }
  94. const CGHeroInstance * HeroPtr::operator->() const
  95. {
  96. return get();
  97. }
  98. bool HeroPtr::validAndSet() const
  99. {
  100. return get(true);
  101. }
  102. const CGHeroInstance * HeroPtr::operator*() const
  103. {
  104. return get();
  105. }
  106. bool HeroPtr::operator==(const HeroPtr & rhs) const
  107. {
  108. return h == rhs.get(true);
  109. }
  110. void foreach_tile_pos(std::function<void(const int3 & pos)> foo)
  111. {
  112. // some micro-optimizations since this function gets called a LOT
  113. // callback pointer is thread-specific and slow to retrieve -> read map size only once
  114. int3 mapSize = cb->getMapSize();
  115. for(int i = 0; i < mapSize.x; i++)
  116. {
  117. for(int j = 0; j < mapSize.y; j++)
  118. {
  119. for(int k = 0; k < mapSize.z; k++)
  120. foo(int3(i, j, k));
  121. }
  122. }
  123. }
  124. void foreach_tile_pos(CCallback * cbp, std::function<void(CCallback * cbp, const int3 & pos)> foo)
  125. {
  126. int3 mapSize = cbp->getMapSize();
  127. for(int i = 0; i < mapSize.x; i++)
  128. {
  129. for(int j = 0; j < mapSize.y; j++)
  130. {
  131. for(int k = 0; k < mapSize.z; k++)
  132. foo(cbp, int3(i, j, k));
  133. }
  134. }
  135. }
  136. void foreach_neighbour(const int3 & pos, std::function<void(const int3 & pos)> foo)
  137. {
  138. CCallback * cbp = cb.get(); // avoid costly retrieval of thread-specific pointer
  139. for(const int3 & dir : int3::getDirs())
  140. {
  141. const int3 n = pos + dir;
  142. if(cbp->isInTheMap(n))
  143. foo(pos + dir);
  144. }
  145. }
  146. void foreach_neighbour(CCallback * cbp, const int3 & pos, std::function<void(CCallback * cbp, const int3 & pos)> foo)
  147. {
  148. for(const int3 & dir : int3::getDirs())
  149. {
  150. const int3 n = pos + dir;
  151. if(cbp->isInTheMap(n))
  152. foo(cbp, pos + dir);
  153. }
  154. }
  155. bool CDistanceSorter::operator()(const CGObjectInstance * lhs, const CGObjectInstance * rhs)
  156. {
  157. const CGPathNode * ln = ai->myCb->getPathsInfo(hero)->getPathInfo(lhs->visitablePos());
  158. const CGPathNode * rn = ai->myCb->getPathsInfo(hero)->getPathInfo(rhs->visitablePos());
  159. if(ln->turns != rn->turns)
  160. return ln->turns < rn->turns;
  161. return (ln->moveRemains > rn->moveRemains);
  162. }
  163. bool compareMovement(HeroPtr lhs, HeroPtr rhs)
  164. {
  165. return lhs->movement > rhs->movement;
  166. }
  167. ui64 evaluateDanger(crint3 tile)
  168. {
  169. const TerrainTile * t = cb->getTile(tile, false);
  170. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  171. return 190000000; //MUCH
  172. ui64 objectDanger = 0;
  173. ui64 guardDanger = 0;
  174. auto visObjs = cb->getVisitableObjs(tile);
  175. if(visObjs.size())
  176. objectDanger = evaluateDanger(visObjs.back());
  177. int3 guardPos = cb->getGuardingCreaturePosition(tile);
  178. if(guardPos.x >= 0 && guardPos != tile)
  179. guardDanger = evaluateDanger(guardPos);
  180. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  181. return std::max(objectDanger, guardDanger);
  182. }
  183. ui64 evaluateDanger(crint3 tile, const CGHeroInstance * visitor)
  184. {
  185. const TerrainTile * t = cb->getTile(tile, false);
  186. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  187. return 190000000; //MUCH
  188. ui64 objectDanger = 0;
  189. ui64 guardDanger = 0;
  190. auto visitableObjects = cb->getVisitableObjs(tile);
  191. // in some scenarios hero happens to be "under" the object (eg town). Then we consider ONLY the hero.
  192. if(vstd::contains_if(visitableObjects, objWithID<Obj::HERO>))
  193. {
  194. vstd::erase_if(visitableObjects, [](const CGObjectInstance * obj)
  195. {
  196. return !objWithID<Obj::HERO>(obj);
  197. });
  198. }
  199. if(const CGObjectInstance * dangerousObject = vstd::backOrNull(visitableObjects))
  200. {
  201. objectDanger = evaluateDanger(dangerousObject); //unguarded objects can also be dangerous or unhandled
  202. if(objectDanger)
  203. {
  204. //TODO: don't downcast objects AI shouldn't know about!
  205. auto armedObj = dynamic_cast<const CArmedInstance *>(dangerousObject);
  206. if(armedObj)
  207. {
  208. float tacticalAdvantage = fh->getTacticalAdvantage(visitor, armedObj);
  209. objectDanger *= tacticalAdvantage; //this line tends to go infinite for allied towns (?)
  210. }
  211. }
  212. if(dangerousObject->ID == Obj::SUBTERRANEAN_GATE)
  213. {
  214. //check guard on the other side of the gate
  215. auto it = ai->knownSubterraneanGates.find(dangerousObject);
  216. if(it != ai->knownSubterraneanGates.end())
  217. {
  218. auto guards = cb->getGuardingCreatures(it->second->visitablePos());
  219. for(auto cre : guards)
  220. {
  221. vstd::amax(guardDanger, evaluateDanger(cre) * fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance *>(cre)));
  222. }
  223. }
  224. }
  225. }
  226. auto guards = cb->getGuardingCreatures(tile);
  227. for(auto cre : guards)
  228. {
  229. vstd::amax(guardDanger, evaluateDanger(cre) * fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance *>(cre))); //we are interested in strongest monster around
  230. }
  231. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  232. return std::max(objectDanger, guardDanger);
  233. }
  234. ui64 evaluateDanger(const CGObjectInstance * obj)
  235. {
  236. if(obj->tempOwner < PlayerColor::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID) != PlayerRelations::ENEMIES) //owned or allied objects don't pose any threat
  237. return 0;
  238. switch(obj->ID)
  239. {
  240. case Obj::HERO:
  241. {
  242. InfoAboutHero iah;
  243. cb->getHeroInfo(obj, iah);
  244. return iah.army.getStrength();
  245. }
  246. case Obj::TOWN:
  247. case Obj::GARRISON:
  248. case Obj::GARRISON2:
  249. {
  250. InfoAboutTown iat;
  251. cb->getTownInfo(obj, iat);
  252. return iat.army.getStrength();
  253. }
  254. case Obj::MONSTER:
  255. {
  256. //TODO!!!!!!!!
  257. const CGCreature * cre = dynamic_cast<const CGCreature *>(obj);
  258. return cre->getArmyStrength();
  259. }
  260. case Obj::CREATURE_GENERATOR1:
  261. case Obj::CREATURE_GENERATOR4:
  262. {
  263. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  264. return d->getArmyStrength();
  265. }
  266. case Obj::MINE:
  267. case Obj::ABANDONED_MINE:
  268. {
  269. const CArmedInstance * a = dynamic_cast<const CArmedInstance *>(obj);
  270. return a->getArmyStrength();
  271. }
  272. case Obj::CRYPT: //crypt
  273. case Obj::CREATURE_BANK: //crebank
  274. case Obj::DRAGON_UTOPIA:
  275. case Obj::SHIPWRECK: //shipwreck
  276. case Obj::DERELICT_SHIP: //derelict ship
  277. // case Obj::PYRAMID:
  278. return fh->estimateBankDanger(dynamic_cast<const CBank *>(obj));
  279. case Obj::PYRAMID:
  280. {
  281. if(obj->subID == 0)
  282. return fh->estimateBankDanger(dynamic_cast<const CBank *>(obj));
  283. else
  284. return 0;
  285. }
  286. default:
  287. return 0;
  288. }
  289. }
  290. bool compareDanger(const CGObjectInstance * lhs, const CGObjectInstance * rhs)
  291. {
  292. return evaluateDanger(lhs) < evaluateDanger(rhs);
  293. }
  294. bool isSafeToVisit(HeroPtr h, crint3 tile)
  295. {
  296. const ui64 heroStrength = h->getTotalStrength();
  297. const ui64 dangerStrength = evaluateDanger(tile, *h);
  298. if(dangerStrength)
  299. {
  300. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  301. {
  302. logAi->trace("It's safe for %s to visit tile %s", h->name, tile.toString());
  303. return true;
  304. }
  305. else
  306. {
  307. return false;
  308. }
  309. }
  310. return true; //there's no danger
  311. }
  312. bool isObjectRemovable(const CGObjectInstance * obj)
  313. {
  314. //FIXME: move logic to object property!
  315. switch (obj->ID)
  316. {
  317. case Obj::MONSTER:
  318. case Obj::RESOURCE:
  319. case Obj::CAMPFIRE:
  320. case Obj::TREASURE_CHEST:
  321. case Obj::ARTIFACT:
  322. case Obj::BORDERGUARD:
  323. return true;
  324. break;
  325. default:
  326. return false;
  327. break;
  328. }
  329. }
  330. bool canBeEmbarkmentPoint(const TerrainTile * t, bool fromWater)
  331. {
  332. // TODO: Such information should be provided by pathfinder
  333. // Tile must be free or with unoccupied boat
  334. if(!t->blocked)
  335. {
  336. return true;
  337. }
  338. else if(!fromWater) // do not try to board when in water sector
  339. {
  340. if(t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT)
  341. return true;
  342. }
  343. return false;
  344. }
  345. int3 whereToExplore(HeroPtr h)
  346. {
  347. TimeCheck tc("where to explore");
  348. int radius = h->getSightRadius();
  349. int3 hpos = h->visitablePos();
  350. auto sm = ai->getCachedSectorMap(h);
  351. //look for nearby objs -> visit them if they're close enouh
  352. const int DIST_LIMIT = 3;
  353. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  354. for(int x = hpos.x - DIST_LIMIT; x <= hpos.x + DIST_LIMIT; ++x) //get only local objects instead of all possible objects on the map
  355. {
  356. for(int y = hpos.y - DIST_LIMIT; y <= hpos.y + DIST_LIMIT; ++y)
  357. {
  358. for(auto obj : cb->getVisitableObjs(int3(x, y, hpos.z), false))
  359. {
  360. int3 op = obj->visitablePos();
  361. CGPath p;
  362. ai->myCb->getPathsInfo(h.get())->getPath(p, op);
  363. if(p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  364. {
  365. if(ai->isGoodForVisit(obj, h, *sm))
  366. nearbyVisitableObjs.push_back(obj);
  367. }
  368. }
  369. }
  370. }
  371. vstd::removeDuplicates(nearbyVisitableObjs); //one object may occupy multiple tiles
  372. boost::sort(nearbyVisitableObjs, CDistanceSorter(h.get()));
  373. if(nearbyVisitableObjs.size())
  374. return nearbyVisitableObjs.back()->visitablePos();
  375. try //check if nearby tiles allow us to reveal anything - this is quick
  376. {
  377. return ai->explorationBestNeighbour(hpos, radius, h);
  378. }
  379. catch(cannotFulfillGoalException & e)
  380. {
  381. //perform exhaustive search
  382. return ai->explorationNewPoint(h);
  383. }
  384. }
  385. bool isBlockedBorderGate(int3 tileToHit) //TODO: is that function needed? should be handled by pathfinder
  386. {
  387. if(cb->getTile(tileToHit)->topVisitableId() != Obj::BORDER_GATE)
  388. return false;
  389. auto gate = dynamic_cast<const CGKeys *>(cb->getTile(tileToHit)->topVisitableObj());
  390. return !gate->passableFor(ai->playerID);
  391. }
  392. bool isBlockVisitObj(const int3 & pos)
  393. {
  394. if(auto obj = cb->getTopObj(pos))
  395. {
  396. if(obj->blockVisit) //we can't stand on that object
  397. return true;
  398. }
  399. return false;
  400. }
  401. bool hasReachableNeighbor(const int3 &pos, HeroPtr hero, CCallback * cbp)
  402. {
  403. for(crint3 dir : int3::getDirs())
  404. {
  405. int3 tile = pos + dir;
  406. if(cbp->isInTheMap(tile) && cbp->getPathsInfo(hero.get())->getPathInfo(tile)->reachable())
  407. {
  408. return true;
  409. }
  410. }
  411. return false;
  412. }
  413. int howManyTilesWillBeDiscovered(const int3 & pos, int radious, CCallback * cbp, HeroPtr hero)
  414. {
  415. int ret = 0;
  416. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  417. {
  418. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  419. {
  420. int3 npos = int3(x, y, pos.z);
  421. if(cbp->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cbp->isVisible(npos))
  422. {
  423. if(hasReachableNeighbor(npos, hero, cbp))
  424. ret++;
  425. }
  426. }
  427. }
  428. return ret;
  429. }
  430. void getVisibleNeighbours(const std::vector<int3> & tiles, std::vector<int3> & out)
  431. {
  432. for(const int3 & tile : tiles)
  433. {
  434. foreach_neighbour(tile, [&](int3 neighbour)
  435. {
  436. if(cb->isVisible(neighbour))
  437. out.push_back(neighbour);
  438. });
  439. }
  440. }
  441. creInfo infoFromDC(const dwellingContent & dc)
  442. {
  443. creInfo ci;
  444. ci.count = dc.first;
  445. ci.creID = dc.second.size() ? dc.second.back() : CreatureID(-1); //should never be accessed
  446. if (ci.creID != -1)
  447. {
  448. ci.cre = VLC->creh->creatures[ci.creID];
  449. ci.level = ci.cre->level; //this is cretaure tier, while tryRealize expects dwelling level. Ignore.
  450. }
  451. else
  452. {
  453. ci.cre = nullptr;
  454. ci.level = 0;
  455. }
  456. return ci;
  457. }
  458. ui64 howManyReinforcementsCanBuy(HeroPtr h, const CGTownInstance * t)
  459. {
  460. ui64 aivalue = 0;
  461. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  462. for(auto const dc : t->creatures)
  463. {
  464. creInfo ci = infoFromDC(dc);
  465. if(ci.count && ci.creID != -1) //valid creature at this level
  466. {
  467. //can be merged with another stack?
  468. SlotID dst = h->getSlotFor(ci.creID);
  469. if (!h->hasStackAtSlot(dst)) //need another new slot for this stack
  470. if (!freeHeroSlots) //no more place for stacks
  471. continue;
  472. else
  473. freeHeroSlots--; //new slot will be occupied
  474. //we found matching occupied or free slot
  475. aivalue += ci.count * ci.cre->AIValue;
  476. }
  477. }
  478. return aivalue;
  479. }
  480. ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance * t)
  481. {
  482. ui64 ret = 0;
  483. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  484. std::vector<const CStackInstance *> toMove;
  485. for(auto const slot : t->Slots())
  486. {
  487. //can be merged woth another stack?
  488. SlotID dst = h->getSlotFor(slot.second->getCreatureID());
  489. if(h->hasStackAtSlot(dst))
  490. ret += t->getPower(slot.first);
  491. else
  492. toMove.push_back(slot.second);
  493. }
  494. boost::sort(toMove, [](const CStackInstance * lhs, const CStackInstance * rhs)
  495. {
  496. return lhs->getPower() < rhs->getPower();
  497. });
  498. for(auto & stack : boost::adaptors::reverse(toMove))
  499. {
  500. if(freeHeroSlots)
  501. {
  502. ret += stack->getPower();
  503. freeHeroSlots--;
  504. }
  505. else
  506. break;
  507. }
  508. return ret;
  509. }
  510. bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
  511. {
  512. return h1->getTotalStrength() < h2->getTotalStrength();
  513. }
  514. bool compareArmyStrength(const CArmedInstance * a1, const CArmedInstance * a2)
  515. {
  516. return a1->getArmyStrength() < a2->getArmyStrength();
  517. }
  518. bool compareArtifacts(const CArtifactInstance * a1, const CArtifactInstance * a2)
  519. {
  520. auto art1 = a1->artType;
  521. auto art2 = a2->artType;
  522. if(art1->price == art2->price)
  523. return art1->valOfBonuses(Bonus::PRIMARY_SKILL) > art2->valOfBonuses(Bonus::PRIMARY_SKILL);
  524. else if(art1->price > art2->price)
  525. return true;
  526. else
  527. return false;
  528. }