AINodeStorage.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. if(heroChainPass)
  29. return;
  30. //TODO: fix this code duplication with NodeStorage::initialize, problem is to keep `resetTile` inline
  31. int3 pos;
  32. const PlayerColor player = ai->playerID;
  33. const int3 sizes = gs->getMapSize();
  34. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(player)->fogOfWarMap;
  35. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  36. const bool useFlying = options.useFlying;
  37. const bool useWaterWalking = options.useWaterWalking;
  38. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  39. {
  40. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  41. {
  42. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  43. {
  44. const TerrainTile * tile = &gs->map->getTile(pos);
  45. switch(tile->terType)
  46. {
  47. case ETerrainType::ROCK:
  48. break;
  49. case ETerrainType::WATER:
  50. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  51. if(useFlying)
  52. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  53. if(useWaterWalking)
  54. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  55. break;
  56. default:
  57. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  58. if(useFlying)
  59. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  60. break;
  61. }
  62. }
  63. }
  64. }
  65. }
  66. void AINodeStorage::clear()
  67. {
  68. actors.clear();
  69. heroChainPass = false;
  70. }
  71. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  72. {
  73. return static_cast<const AIPathNode *>(node);
  74. }
  75. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  76. {
  77. auto aiNode = static_cast<AIPathNode *>(node);
  78. updater(aiNode);
  79. }
  80. boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
  81. const int3 & pos,
  82. const EPathfindingLayer layer,
  83. const ChainActor * actor)
  84. {
  85. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  86. for(AIPathNode & node : chains)
  87. {
  88. if(node.actor == actor)
  89. {
  90. return &node;
  91. }
  92. if(!node.actor)
  93. {
  94. node.actor = actor;
  95. return &node;
  96. }
  97. }
  98. return boost::none;
  99. }
  100. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  101. {
  102. if(heroChainPass)
  103. return heroChain;
  104. std::vector<CGPathNode *> initialNodes;
  105. for(auto actorPtr : actors)
  106. {
  107. ChainActor * actor = actorPtr.get();
  108. AIPathNode * initialNode =
  109. getOrCreateNode(actor->initialPosition, actor->layer, actor)
  110. .get();
  111. initialNode->turns = actor->initialTurn;
  112. initialNode->moveRemains = actor->initialMovement;
  113. initialNode->danger = 0;
  114. initialNode->cost = 0.0;
  115. if(actor->isMovable)
  116. {
  117. initialNodes.push_back(initialNode);
  118. }
  119. else
  120. {
  121. initialNode->locked = true;
  122. }
  123. }
  124. return initialNodes;
  125. }
  126. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility)
  127. {
  128. for(int i = 0; i < NUM_CHAINS; i++)
  129. {
  130. AIPathNode & heroNode = nodes[coord.x][coord.y][coord.z][layer][i];
  131. heroNode.actor = nullptr;
  132. heroNode.danger = 0;
  133. heroNode.manaCost = 0;
  134. heroNode.specialAction.reset();
  135. heroNode.armyLoss = 0;
  136. heroNode.chainOther = nullptr;
  137. heroNode.update(coord, layer, accessibility);
  138. }
  139. }
  140. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  141. {
  142. const AIPathNode * srcNode = getAINode(source.node);
  143. updateAINode(destination.node, [&](AIPathNode * dstNode)
  144. {
  145. commit(dstNode, srcNode, destination.action, destination.turn, destination.movementLeft, destination.cost);
  146. if(dstNode->specialAction && dstNode->actor)
  147. {
  148. dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
  149. }
  150. });
  151. }
  152. void AINodeStorage::commit(
  153. AIPathNode * destination,
  154. const AIPathNode * source,
  155. CGPathNode::ENodeAction action,
  156. int turn,
  157. int movementLeft,
  158. float cost) const
  159. {
  160. destination->action = action;
  161. destination->cost = cost;
  162. destination->moveRemains = movementLeft;
  163. destination->turns = turn;
  164. destination->armyLoss = source->armyLoss;
  165. destination->manaCost = source->manaCost;
  166. destination->danger = source->danger;
  167. destination->theNodeBefore = source->theNodeBefore;
  168. }
  169. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  170. const PathNodeInfo & source,
  171. const PathfinderConfig * pathfinderConfig,
  172. const CPathfinderHelper * pathfinderHelper)
  173. {
  174. std::vector<CGPathNode *> neighbours;
  175. neighbours.reserve(16);
  176. const AIPathNode * srcNode = getAINode(source.node);
  177. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  178. for(auto & neighbour : accessibleNeighbourTiles)
  179. {
  180. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  181. {
  182. auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
  183. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  184. continue;
  185. neighbours.push_back(nextNode.get());
  186. }
  187. }
  188. return neighbours;
  189. }
  190. bool AINodeStorage::calculateHeroChain()
  191. {
  192. heroChainPass = true;
  193. heroChain.resize(0);
  194. foreach_tile_pos([&](const int3 & pos) {
  195. auto layer = EPathfindingLayer::LAND;
  196. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  197. for(AIPathNode & node : chains)
  198. {
  199. if(node.locked && node.turns < 1)
  200. addHeroChain(&node);
  201. }
  202. });
  203. return heroChain.size();
  204. }
  205. void AINodeStorage::addHeroChain(AIPathNode * srcNode)
  206. {
  207. auto chains = nodes[srcNode->coord.x][srcNode->coord.y][srcNode->coord.z][srcNode->layer];
  208. for(AIPathNode & node : chains)
  209. {
  210. if(!node.locked || !node.actor || node.action == CGPathNode::ENodeAction::UNKNOWN && node.actor->hero)
  211. {
  212. continue;
  213. }
  214. addHeroChain(srcNode, &node);
  215. addHeroChain(&node, srcNode);
  216. }
  217. }
  218. void AINodeStorage::addHeroChain(AIPathNode * carrier, AIPathNode * other)
  219. {
  220. if(carrier->actor->canExchange(other->actor))
  221. {
  222. bool hasLessMp = carrier->turns > other->turns || carrier->moveRemains < other->moveRemains;
  223. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  224. #ifdef VCMI_TRACE_PATHFINDER
  225. logAi->trace("Check hero exhange at %s, %s -> %s", carrier->coord.toString(), other->actor->hero->name, carrier->actor->hero->name);
  226. #endif
  227. if(hasLessMp && hasLessExperience)
  228. return;
  229. auto newActor = carrier->actor->exchange(other->actor);
  230. auto chainNodeOptional = getOrCreateNode(carrier->coord, carrier->layer, newActor);
  231. if(!chainNodeOptional)
  232. return;
  233. auto chainNode = chainNodeOptional.get();
  234. if(chainNode->locked)
  235. return;
  236. #ifdef VCMI_TRACE_PATHFINDER
  237. logAi->trace("Hero exhange at %s, %s -> %s", carrier->coord.toString(), other->actor->hero->name, carrier->actor->hero->name);
  238. #endif
  239. commitExchange(chainNode, carrier, other);
  240. heroChain.push_back(chainNode);
  241. }
  242. }
  243. void AINodeStorage::commitExchange(
  244. AIPathNode * exchangeNode,
  245. AIPathNode * carrierParentNode,
  246. AIPathNode * otherParentNode) const
  247. {
  248. auto carrierActor = carrierParentNode->actor;
  249. auto exchangeActor = exchangeNode->actor;
  250. auto otherActor = otherParentNode->actor;
  251. auto armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  252. auto turns = carrierParentNode->turns;
  253. auto cost = carrierParentNode->cost;
  254. auto movementLeft = carrierParentNode->moveRemains;
  255. if(carrierParentNode->turns < otherParentNode->turns)
  256. {
  257. int moveRemains = exchangeActor->hero->maxMovePoints(exchangeNode->layer);
  258. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  259. + carrierParentNode->moveRemains / (float)moveRemains;
  260. turns = otherParentNode->turns;
  261. cost = waitingCost;
  262. movementLeft = moveRemains;
  263. }
  264. if(exchangeNode->turns != 0xFF && exchangeNode->cost < cost)
  265. return;
  266. #ifdef VCMI_TRACE_PATHFINDER
  267. logAi->trace(
  268. "Accepted hero exhange at %s, carrier %s, mp cost %f",
  269. exchangeNode->coord.toString(),
  270. carrierActor->hero->name,
  271. cost);
  272. #endif
  273. commit(exchangeNode, carrierParentNode, carrierParentNode->action, turns, movementLeft, cost);
  274. exchangeNode->theNodeBefore = carrierParentNode;
  275. exchangeNode->chainOther = otherParentNode;
  276. exchangeNode->armyLoss = armyLoss;
  277. exchangeNode->manaCost = carrierParentNode->manaCost;
  278. }
  279. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  280. {
  281. auto aiNode = getAINode(node);
  282. return aiNode->actor->hero;
  283. }
  284. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  285. {
  286. std::set<const CGHeroInstance *> heroes;
  287. for(auto actor : actors)
  288. {
  289. if(actor->hero)
  290. heroes.insert(actor->hero);
  291. }
  292. return heroes;
  293. }
  294. void AINodeStorage::setHeroes(std::vector<HeroPtr> heroes, const VCAI * _ai)
  295. {
  296. cb = _ai->myCb.get();
  297. ai = _ai;
  298. for(auto & hero : heroes)
  299. {
  300. uint64_t mask = 1 << actors.size();
  301. actors.push_back(std::make_shared<HeroActor>(hero.get(), mask));
  302. }
  303. }
  304. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  305. const PathNodeInfo & source,
  306. const PathfinderConfig * pathfinderConfig,
  307. const CPathfinderHelper * pathfinderHelper)
  308. {
  309. std::vector<CGPathNode *> neighbours;
  310. if(source.isNodeObjectVisitable())
  311. {
  312. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  313. auto srcNode = getAINode(source.node);
  314. for(auto & neighbour : accessibleExits)
  315. {
  316. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  317. if(!node)
  318. continue;
  319. neighbours.push_back(node.get());
  320. }
  321. }
  322. if(source.isInitialPosition)
  323. {
  324. calculateTownPortalTeleportations(source, neighbours);
  325. }
  326. return neighbours;
  327. }
  328. void AINodeStorage::calculateTownPortalTeleportations(
  329. const PathNodeInfo & source,
  330. std::vector<CGPathNode *> & neighbours)
  331. {
  332. SpellID spellID = SpellID::TOWN_PORTAL;
  333. const CSpell * townPortal = spellID.toSpell();
  334. auto srcNode = getAINode(source.node);
  335. auto hero = srcNode->actor->hero;
  336. if(hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal))
  337. {
  338. auto towns = cb->getTownsInfo(false);
  339. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  340. {
  341. return cb->getPlayerRelations(hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  342. });
  343. if(!towns.size())
  344. {
  345. return;
  346. }
  347. // TODO: Copy/Paste from TownPortalMechanics
  348. auto skillLevel = hero->getSpellSchoolLevel(townPortal);
  349. auto movementCost = GameConstants::BASE_MOVEMENT_COST * (skillLevel >= 3 ? 2 : 3);
  350. if(hero->movement < movementCost)
  351. {
  352. return;
  353. }
  354. if(skillLevel < SecSkillLevel::ADVANCED)
  355. {
  356. const CGTownInstance * nearestTown = *vstd::minElementByFun(towns, [&](const CGTownInstance * t) -> int
  357. {
  358. return hero->visitablePos().dist2dSQ(t->visitablePos());
  359. });
  360. towns = std::vector<const CGTownInstance *>{ nearestTown };
  361. }
  362. for(const CGTownInstance * targetTown : towns)
  363. {
  364. if(targetTown->visitingHero)
  365. continue;
  366. auto nodeOptional = getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, srcNode->actor->castActor);
  367. if(nodeOptional)
  368. {
  369. #ifdef VCMI_TRACE_PATHFINDER
  370. logAi->trace("Adding town portal node at %s", targetTown->name);
  371. #endif
  372. AIPathNode * node = nodeOptional.get();
  373. node->theNodeBefore = source.node;
  374. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  375. node->moveRemains = source.node->moveRemains;
  376. neighbours.push_back(node);
  377. }
  378. }
  379. }
  380. }
  381. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  382. {
  383. auto pos = destination.coord;
  384. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  385. auto destinationNode = getAINode(destination.node);
  386. for(const AIPathNode & node : chains)
  387. {
  388. auto sameNode = node.actor == destinationNode->actor;
  389. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN)
  390. {
  391. continue;
  392. }
  393. if(node.danger <= destinationNode->danger && destinationNode->actor == node.actor->battleActor)
  394. {
  395. if(node.cost < destinationNode->cost)
  396. {
  397. #ifdef VCMI_TRACE_PATHFINDER
  398. logAi->trace(
  399. "Block ineficient move %s:->%s, mask=%i, mp diff: %i",
  400. source.coord.toString(),
  401. destination.coord.toString(),
  402. destinationNode->actor->chainMask,
  403. node.moveRemains - destinationNode->moveRemains);
  404. #endif
  405. return true;
  406. }
  407. }
  408. }
  409. return false;
  410. }
  411. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  412. {
  413. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  414. for(const AIPathNode & node : chains)
  415. {
  416. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  417. && node.actor && node.actor->hero == hero.h)
  418. {
  419. return true;
  420. }
  421. }
  422. return false;
  423. }
  424. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  425. {
  426. std::vector<AIPath> paths;
  427. paths.reserve(NUM_CHAINS / 4);
  428. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  429. for(const AIPathNode & node : chains)
  430. {
  431. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  432. {
  433. continue;
  434. }
  435. AIPath path;
  436. path.targetHero = node.actor->hero;
  437. path.heroArmy = node.actor->creatureSet;
  438. path.armyLoss = node.armyLoss;
  439. path.targetObjectDanger = evaluateDanger(pos, path.targetHero);
  440. fillChainInfo(&node, path);
  441. paths.push_back(path);
  442. }
  443. return paths;
  444. }
  445. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path) const
  446. {
  447. while(node != nullptr)
  448. {
  449. if(!node->actor->hero || node->coord == node->actor->hero->visitablePos())
  450. return;
  451. AIPathNodeInfo pathNode;
  452. pathNode.cost = node->cost;
  453. pathNode.targetHero = node->actor->hero;
  454. pathNode.turns = node->turns;
  455. pathNode.danger = node->danger;
  456. pathNode.coord = node->coord;
  457. path.nodes.push_back(pathNode);
  458. path.specialAction = node->specialAction;
  459. if(node->chainOther)
  460. fillChainInfo(node->chainOther, path);
  461. node = getAINode(node->theNodeBefore);
  462. }
  463. }
  464. AIPath::AIPath()
  465. : nodes({})
  466. {
  467. }
  468. int3 AIPath::firstTileToGet() const
  469. {
  470. if(nodes.size())
  471. {
  472. return nodes.back().coord;
  473. }
  474. return int3(-1, -1, -1);
  475. }
  476. uint64_t AIPath::getPathDanger() const
  477. {
  478. if(nodes.size())
  479. {
  480. return nodes.front().danger;
  481. }
  482. return 0;
  483. }
  484. float AIPath::movementCost() const
  485. {
  486. if(nodes.size())
  487. {
  488. return nodes.front().cost;
  489. }
  490. // TODO: boost:optional?
  491. return 0.0;
  492. }
  493. uint64_t AIPath::getHeroStrength() const
  494. {
  495. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  496. }
  497. uint64_t AIPath::getTotalDanger(HeroPtr hero) const
  498. {
  499. uint64_t pathDanger = getPathDanger();
  500. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  501. return danger;
  502. }