AIUtility.cpp 13 KB

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