AINodeStorage.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /*
  2. * AINodeStorage.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 "AINodeStorage.h"
  12. #include "Actions/TownPortalAction.h"
  13. #include "../Goals/Goals.h"
  14. #include "../../../CCallback.h"
  15. #include "../../../lib/mapping/CMap.h"
  16. #include "../../../lib/mapObjects/MapObjects.h"
  17. #include "../../../lib/PathfinderUtil.h"
  18. #include "../../../lib/CPlayerState.h"
  19. AINodeStorage::AINodeStorage(const int3 & Sizes)
  20. : sizes(Sizes)
  21. {
  22. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][EPathfindingLayer::NUM_LAYERS][NUM_CHAINS]);
  23. dangerEvaluator.reset(new FuzzyHelper());
  24. }
  25. AINodeStorage::~AINodeStorage() = default;
  26. void AINodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs)
  27. {
  28. //TODO: fix this code duplication with NodeStorage::initialize, problem is to keep `resetTile` inline
  29. int3 pos;
  30. const PlayerColor player = ai->playerID;
  31. const int3 sizes = gs->getMapSize();
  32. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(player)->fogOfWarMap;
  33. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  34. const bool useFlying = options.useFlying;
  35. const bool useWaterWalking = options.useWaterWalking;
  36. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  37. {
  38. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  39. {
  40. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  41. {
  42. const TerrainTile * tile = &gs->map->getTile(pos);
  43. switch(tile->terType)
  44. {
  45. case ETerrainType::ROCK:
  46. break;
  47. case ETerrainType::WATER:
  48. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  49. if(useFlying)
  50. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  51. if(useWaterWalking)
  52. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  53. break;
  54. default:
  55. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  56. if(useFlying)
  57. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  58. break;
  59. }
  60. }
  61. }
  62. }
  63. }
  64. void AINodeStorage::reset()
  65. {
  66. actors.clear();
  67. }
  68. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  69. {
  70. return static_cast<const AIPathNode *>(node);
  71. }
  72. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  73. {
  74. auto aiNode = static_cast<AIPathNode *>(node);
  75. updater(aiNode);
  76. }
  77. boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(const int3 & pos, const EPathfindingLayer layer, const ChainActor * actor)
  78. {
  79. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  80. for(AIPathNode & node : chains)
  81. {
  82. if(node.actor == actor)
  83. {
  84. return &node;
  85. }
  86. if(!node.actor)
  87. {
  88. node.actor = actor;
  89. return &node;
  90. }
  91. }
  92. return boost::none;
  93. }
  94. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  95. {
  96. std::vector<CGPathNode *> initialNodes;
  97. for(auto actorPtr : actors)
  98. {
  99. const ChainActor * actor = actorPtr.get();
  100. AIPathNode * initialNode =
  101. getOrCreateNode(actor->initialPosition, actor->layer, actor)
  102. .get();
  103. initialNode->turns = actor->initialTurn;
  104. initialNode->moveRemains = actor->initialMovement;
  105. initialNode->danger = 0;
  106. initialNode->cost = 0.0;
  107. if(actor->isMovable)
  108. {
  109. initialNodes.push_back(initialNode);
  110. }
  111. else
  112. {
  113. initialNode->locked = true;
  114. }
  115. }
  116. return initialNodes;
  117. }
  118. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility)
  119. {
  120. for(int i = 0; i < NUM_CHAINS; i++)
  121. {
  122. AIPathNode & heroNode = nodes[coord.x][coord.y][coord.z][layer][i];
  123. heroNode.actor = nullptr;
  124. heroNode.danger = 0;
  125. heroNode.manaCost = 0;
  126. heroNode.specialAction.reset();
  127. heroNode.update(coord, layer, accessibility);
  128. }
  129. }
  130. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  131. {
  132. const AIPathNode * srcNode = getAINode(source.node);
  133. updateAINode(destination.node, [&](AIPathNode * dstNode)
  134. {
  135. dstNode->moveRemains = destination.movementLeft;
  136. dstNode->turns = destination.turn;
  137. dstNode->cost = destination.cost;
  138. dstNode->danger = srcNode->danger;
  139. dstNode->action = destination.action;
  140. dstNode->theNodeBefore = srcNode->theNodeBefore;
  141. dstNode->manaCost = srcNode->manaCost;
  142. if(dstNode->specialAction && dstNode->actor)
  143. {
  144. dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
  145. }
  146. });
  147. }
  148. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  149. const PathNodeInfo & source,
  150. const PathfinderConfig * pathfinderConfig,
  151. const CPathfinderHelper * pathfinderHelper)
  152. {
  153. std::vector<CGPathNode *> neighbours;
  154. neighbours.reserve(16);
  155. const AIPathNode * srcNode = getAINode(source.node);
  156. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  157. for(auto & neighbour : accessibleNeighbourTiles)
  158. {
  159. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  160. {
  161. auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
  162. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  163. continue;
  164. neighbours.push_back(nextNode.get());
  165. }
  166. }
  167. return neighbours;
  168. }
  169. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  170. {
  171. auto aiNode = getAINode(node);
  172. return aiNode->actor->hero;
  173. }
  174. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  175. {
  176. std::set<const CGHeroInstance *> heroes;
  177. for(auto actor : actors)
  178. {
  179. if(actor->hero)
  180. heroes.insert(hero);
  181. }
  182. return heroes;
  183. }
  184. void AINodeStorage::setHeroes(std::vector<HeroPtr> heroes, const VCAI * _ai)
  185. {
  186. cb = _ai->myCb.get();
  187. ai = _ai;
  188. for(auto & hero : heroes)
  189. {
  190. uint64_t mask = 1 << actors.size();
  191. actors.push_back(std::make_shared<ChainActor>(hero.get(), mask));
  192. }
  193. }
  194. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  195. const PathNodeInfo & source,
  196. const PathfinderConfig * pathfinderConfig,
  197. const CPathfinderHelper * pathfinderHelper)
  198. {
  199. std::vector<CGPathNode *> neighbours;
  200. if(source.isNodeObjectVisitable())
  201. {
  202. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  203. auto srcNode = getAINode(source.node);
  204. for(auto & neighbour : accessibleExits)
  205. {
  206. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  207. if(!node)
  208. continue;
  209. neighbours.push_back(node.get());
  210. }
  211. }
  212. if(hero->getPosition(false) == source.coord)
  213. {
  214. calculateTownPortalTeleportations(source, neighbours);
  215. }
  216. return neighbours;
  217. }
  218. void AINodeStorage::calculateTownPortalTeleportations(
  219. const PathNodeInfo & source,
  220. std::vector<CGPathNode *> & neighbours)
  221. {
  222. SpellID spellID = SpellID::TOWN_PORTAL;
  223. const CSpell * townPortal = spellID.toSpell();
  224. auto srcNode = getAINode(source.node);
  225. if(hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal))
  226. {
  227. auto towns = cb->getTownsInfo(false);
  228. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  229. {
  230. return cb->getPlayerRelations(hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  231. });
  232. if(!towns.size())
  233. {
  234. return;
  235. }
  236. // TODO: Copy/Paste from TownPortalMechanics
  237. auto skillLevel = hero->getSpellSchoolLevel(townPortal);
  238. auto movementCost = GameConstants::BASE_MOVEMENT_COST * (skillLevel >= 3 ? 2 : 3);
  239. if(hero->movement < movementCost)
  240. {
  241. return;
  242. }
  243. if(skillLevel < SecSkillLevel::ADVANCED)
  244. {
  245. const CGTownInstance * nearestTown = *vstd::minElementByFun(towns, [&](const CGTownInstance * t) -> int
  246. {
  247. return hero->visitablePos().dist2dSQ(t->visitablePos());
  248. });
  249. towns = std::vector<const CGTownInstance *>{ nearestTown };
  250. }
  251. for(const CGTownInstance * targetTown : towns)
  252. {
  253. if(targetTown->visitingHero)
  254. continue;
  255. auto nodeOptional = getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, srcNode->actor->castActor);
  256. if(nodeOptional)
  257. {
  258. #ifdef VCMI_TRACE_PATHFINDER
  259. logAi->trace("Adding town portal node at %s", targetTown->name);
  260. #endif
  261. AIPathNode * node = nodeOptional.get();
  262. node->theNodeBefore = source.node;
  263. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  264. node->moveRemains = source.node->moveRemains;
  265. neighbours.push_back(node);
  266. }
  267. }
  268. }
  269. }
  270. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  271. {
  272. auto pos = destination.coord;
  273. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  274. auto destinationNode = getAINode(destination.node);
  275. for(const AIPathNode & node : chains)
  276. {
  277. auto sameNode = node.actor == destinationNode->actor;
  278. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN)
  279. {
  280. continue;
  281. }
  282. if(node.danger <= destinationNode->danger && destinationNode->actor == node.actor->battleActor)
  283. {
  284. if(node.cost < destinationNode->cost)
  285. {
  286. #ifdef VCMI_TRACE_PATHFINDER
  287. logAi->trace(
  288. "Block ineficient move %s:->%s, mask=%i, mp diff: %i",
  289. source.coord.toString(),
  290. destination.coord.toString(),
  291. destinationNode->chainMask,
  292. node.moveRemains - destinationNode->moveRemains);
  293. #endif
  294. return true;
  295. }
  296. }
  297. }
  298. return false;
  299. }
  300. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  301. {
  302. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  303. for(const AIPathNode & node : chains)
  304. {
  305. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  306. && node.actor && node.actor->hero == hero.h)
  307. {
  308. return true;
  309. }
  310. }
  311. return false;
  312. }
  313. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  314. {
  315. std::vector<AIPath> paths;
  316. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  317. auto initialPos = hero->visitablePos();
  318. for(const AIPathNode & node : chains)
  319. {
  320. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor)
  321. {
  322. continue;
  323. }
  324. AIPath path;
  325. const AIPathNode * current = &node;
  326. path.targetHero = node.actor->hero;
  327. while(current != nullptr && current->coord != initialPos)
  328. {
  329. AIPathNodeInfo pathNode;
  330. pathNode.cost = current->cost;
  331. pathNode.turns = current->turns;
  332. pathNode.danger = current->danger;
  333. pathNode.coord = current->coord;
  334. path.nodes.push_back(pathNode);
  335. path.specialAction = current->specialAction;
  336. current = getAINode(current->theNodeBefore);
  337. }
  338. path.targetObjectDanger = evaluateDanger(pos);
  339. paths.push_back(path);
  340. }
  341. return paths;
  342. }
  343. AIPath::AIPath()
  344. : nodes({})
  345. {
  346. }
  347. int3 AIPath::firstTileToGet() const
  348. {
  349. if(nodes.size())
  350. {
  351. return nodes.back().coord;
  352. }
  353. return int3(-1, -1, -1);
  354. }
  355. uint64_t AIPath::getPathDanger() const
  356. {
  357. if(nodes.size())
  358. {
  359. return nodes.front().danger;
  360. }
  361. return 0;
  362. }
  363. float AIPath::movementCost() const
  364. {
  365. if(nodes.size())
  366. {
  367. return nodes.front().cost;
  368. }
  369. // TODO: boost:optional?
  370. return 0.0;
  371. }
  372. uint64_t AIPath::getTotalDanger(HeroPtr hero) const
  373. {
  374. uint64_t pathDanger = getPathDanger();
  375. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  376. return danger;
  377. }
  378. ChainActor::ChainActor(const CGHeroInstance * hero, int chainMask)
  379. :hero(hero), isMovable(true), chainMask(chainMask)
  380. {
  381. initialPosition = hero->visitablePos();
  382. layer = hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND;
  383. initialMovement = hero->movement;
  384. initialTurn = 0;
  385. setupSpecialActors();
  386. }
  387. void ChainActor::copyFrom(ChainActor * base)
  388. {
  389. hero = base->hero;
  390. layer = base->layer;
  391. initialMovement = base->initialMovement;
  392. initialTurn = base->initialTurn;
  393. }
  394. void ChainActor::setupSpecialActors()
  395. {
  396. auto allActors = std::vector<ChainActor *>{ this };
  397. specialActors.resize(7);
  398. for(int i = 1; i < 8; i++)
  399. {
  400. ChainActor & specialActor = specialActors[i - 1];
  401. specialActor.copyFrom(this);
  402. specialActor.allowBattle = (i & 1) > 0;
  403. specialActor.allowSpellCast = (i & 2) > 0;
  404. specialActor.allowUseResources = (i & 4) > 0;
  405. allActors.push_back(&specialActor);
  406. }
  407. for(int i = 0; i <= 8; i++)
  408. {
  409. ChainActor * actor = allActors[i];
  410. actor->battleActor = allActors[i | 1];
  411. actor->castActor = allActors[i | 2];
  412. actor->resourceActor = allActors[i | 4];
  413. }
  414. }