AINodeStorage.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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 = playerID;
  33. const PlayerColor fowPlayer = ai->playerID;
  34. const int3 sizes = gs->getMapSize();
  35. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(fowPlayer)->fogOfWarMap;
  36. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  37. const bool useFlying = options.useFlying;
  38. const bool useWaterWalking = options.useWaterWalking;
  39. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  40. {
  41. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  42. {
  43. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  44. {
  45. const TerrainTile * tile = &gs->map->getTile(pos);
  46. switch(tile->terType)
  47. {
  48. case ETerrainType::ROCK:
  49. break;
  50. case ETerrainType::WATER:
  51. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  52. if(useFlying)
  53. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  54. if(useWaterWalking)
  55. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  56. break;
  57. default:
  58. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  59. if(useFlying)
  60. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  61. break;
  62. }
  63. }
  64. }
  65. }
  66. }
  67. void AINodeStorage::clear()
  68. {
  69. actors.clear();
  70. heroChainPass = EHeroChainPass::INITIAL;
  71. heroChainTurn = 0;
  72. heroChainMaxTurns = 1;
  73. }
  74. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  75. {
  76. return static_cast<const AIPathNode *>(node);
  77. }
  78. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  79. {
  80. auto aiNode = static_cast<AIPathNode *>(node);
  81. updater(aiNode);
  82. }
  83. boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
  84. const int3 & pos,
  85. const EPathfindingLayer layer,
  86. const ChainActor * actor)
  87. {
  88. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  89. for(AIPathNode & node : chains)
  90. {
  91. if(node.actor == actor)
  92. {
  93. return &node;
  94. }
  95. if(!node.actor)
  96. {
  97. node.actor = actor;
  98. return &node;
  99. }
  100. }
  101. return boost::none;
  102. }
  103. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  104. {
  105. if(heroChainPass)
  106. {
  107. calculateTownPortalTeleportations(heroChain);
  108. return heroChain;
  109. }
  110. std::vector<CGPathNode *> initialNodes;
  111. for(auto actorPtr : actors)
  112. {
  113. ChainActor * actor = actorPtr.get();
  114. AIPathNode * initialNode =
  115. getOrCreateNode(actor->initialPosition, actor->layer, actor)
  116. .get();
  117. initialNode->turns = actor->initialTurn;
  118. initialNode->moveRemains = actor->initialMovement;
  119. initialNode->danger = 0;
  120. initialNode->cost = actor->initialTurn;
  121. initialNode->action = CGPathNode::ENodeAction::NORMAL;
  122. if(actor->isMovable)
  123. {
  124. initialNodes.push_back(initialNode);
  125. }
  126. else
  127. {
  128. initialNode->locked = true;
  129. }
  130. }
  131. calculateTownPortalTeleportations(initialNodes);
  132. return initialNodes;
  133. }
  134. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility)
  135. {
  136. for(int i = 0; i < NUM_CHAINS; i++)
  137. {
  138. AIPathNode & heroNode = nodes[coord.x][coord.y][coord.z][layer][i];
  139. heroNode.actor = nullptr;
  140. heroNode.danger = 0;
  141. heroNode.manaCost = 0;
  142. heroNode.specialAction.reset();
  143. heroNode.armyLoss = 0;
  144. heroNode.chainOther = nullptr;
  145. heroNode.update(coord, layer, accessibility);
  146. }
  147. }
  148. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  149. {
  150. const AIPathNode * srcNode = getAINode(source.node);
  151. updateAINode(destination.node, [&](AIPathNode * dstNode)
  152. {
  153. commit(dstNode, srcNode, destination.action, destination.turn, destination.movementLeft, destination.cost);
  154. if(srcNode->specialAction || srcNode->chainOther)
  155. {
  156. // there is some action on source tile which should be performed before we can bypass it
  157. destination.node->theNodeBefore = source.node;
  158. }
  159. if(dstNode->specialAction && dstNode->actor)
  160. {
  161. dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
  162. }
  163. });
  164. }
  165. void AINodeStorage::commit(
  166. AIPathNode * destination,
  167. const AIPathNode * source,
  168. CGPathNode::ENodeAction action,
  169. int turn,
  170. int movementLeft,
  171. float cost) const
  172. {
  173. destination->action = action;
  174. destination->cost = cost;
  175. destination->moveRemains = movementLeft;
  176. destination->turns = turn;
  177. destination->armyLoss = source->armyLoss;
  178. destination->manaCost = source->manaCost;
  179. destination->danger = source->danger;
  180. destination->theNodeBefore = source->theNodeBefore;
  181. destination->chainOther = nullptr;
  182. #if AI_TRACE_LEVEL >= 2
  183. logAi->trace(
  184. "Commited %s -> %s, cost: %f, turn: %s, mp: %d, hero: %s, mask: %x, army: %lld",
  185. source->coord.toString(),
  186. destination->coord.toString(),
  187. destination->cost,
  188. std::to_string(destination->turns),
  189. destination->moveRemains,
  190. destination->actor->toString(),
  191. destination->actor->chainMask,
  192. destination->actor->armyValue);
  193. #endif
  194. }
  195. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  196. const PathNodeInfo & source,
  197. const PathfinderConfig * pathfinderConfig,
  198. const CPathfinderHelper * pathfinderHelper)
  199. {
  200. std::vector<CGPathNode *> neighbours;
  201. neighbours.reserve(16);
  202. const AIPathNode * srcNode = getAINode(source.node);
  203. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  204. for(auto & neighbour : accessibleNeighbourTiles)
  205. {
  206. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  207. {
  208. auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
  209. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  210. continue;
  211. neighbours.push_back(nextNode.get());
  212. }
  213. }
  214. return neighbours;
  215. }
  216. bool AINodeStorage::increaseHeroChainTurnLimit()
  217. {
  218. if(heroChainTurn >= heroChainMaxTurns)
  219. return false;
  220. heroChainTurn++;
  221. return true;
  222. }
  223. EPathfindingLayer phisycalLayers[2] = {EPathfindingLayer::LAND, EPathfindingLayer::SAIL};
  224. bool AINodeStorage::calculateHeroChainFinal()
  225. {
  226. heroChainPass = EHeroChainPass::FINAL;
  227. heroChain.resize(0);
  228. for(auto layer : phisycalLayers)
  229. {
  230. foreach_tile_pos([&](const int3 & pos)
  231. {
  232. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  233. for(AIPathNode & node : chains)
  234. {
  235. if(node.turns > heroChainTurn
  236. && node.action != CGPathNode::ENodeAction::UNKNOWN
  237. && node.actor->actorExchangeCount > 1
  238. && !hasBetterChain(&node, &node, chains))
  239. {
  240. heroChain.push_back(&node);
  241. }
  242. }
  243. });
  244. }
  245. return heroChain.size();
  246. }
  247. bool AINodeStorage::calculateHeroChain()
  248. {
  249. heroChainPass = EHeroChainPass::CHAIN;
  250. heroChain.resize(0);
  251. std::vector<AIPathNode *> existingChains;
  252. std::vector<ExchangeCandidate> newChains;
  253. existingChains.reserve(NUM_CHAINS);
  254. newChains.reserve(NUM_CHAINS);
  255. for(auto layer : phisycalLayers)
  256. {
  257. foreach_tile_pos([&](const int3 & pos)
  258. {
  259. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  260. existingChains.resize(0);
  261. newChains.resize(0);
  262. for(AIPathNode & node : chains)
  263. {
  264. if(node.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  265. existingChains.push_back(&node);
  266. }
  267. for(AIPathNode * node : existingChains)
  268. {
  269. if(node->actor->isMovable)
  270. {
  271. calculateHeroChain(node, existingChains, newChains);
  272. }
  273. }
  274. cleanupInefectiveChains(newChains);
  275. addHeroChain(newChains);
  276. });
  277. }
  278. return heroChain.size();
  279. }
  280. bool AINodeStorage::selectFirstActor()
  281. {
  282. if(!actors.size())
  283. return false;
  284. auto strongest = *vstd::maxElementByFun(actors, [](std::shared_ptr<ChainActor> actor) -> uint64_t
  285. {
  286. return actor->armyValue;
  287. });
  288. chainMask = strongest->chainMask;
  289. return true;
  290. }
  291. bool AINodeStorage::selectNextActor()
  292. {
  293. auto currentActor = std::find_if(actors.begin(), actors.end(), [&](std::shared_ptr<ChainActor> actor)-> bool
  294. {
  295. return actor->chainMask == chainMask;
  296. });
  297. auto nextActor = actors.end();
  298. for(auto actor = actors.begin(); actor != actors.end(); actor++)
  299. {
  300. if(actor->get()->armyValue > currentActor->get()->armyValue
  301. || actor->get()->armyValue == currentActor->get()->armyValue && actor <= currentActor)
  302. {
  303. continue;
  304. }
  305. if(nextActor == actors.end()
  306. || actor->get()->armyValue > nextActor->get()->armyValue)
  307. {
  308. nextActor = actor;
  309. }
  310. }
  311. if(nextActor != actors.end())
  312. {
  313. chainMask = nextActor->get()->chainMask;
  314. return true;
  315. }
  316. return false;
  317. }
  318. void AINodeStorage::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  319. {
  320. vstd::erase_if(result, [&](const ExchangeCandidate & chainInfo) -> bool
  321. {
  322. auto pos = chainInfo.coord;
  323. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  324. return hasBetterChain(chainInfo.carrierParent, &chainInfo, chains)
  325. || hasBetterChain(chainInfo.carrierParent, &chainInfo, result);
  326. });
  327. }
  328. void AINodeStorage::calculateHeroChain(
  329. AIPathNode * srcNode,
  330. const std::vector<AIPathNode *> & variants,
  331. std::vector<ExchangeCandidate> & result) const
  332. {
  333. for(AIPathNode * node : variants)
  334. {
  335. if(node == srcNode || !node->actor)
  336. continue;
  337. if((node->actor->chainMask & chainMask) == 0 && (srcNode->actor->chainMask & chainMask) == 0)
  338. continue;
  339. if(node->turns > heroChainTurn
  340. || (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  341. || (node->actor->chainMask & srcNode->actor->chainMask) != 0)
  342. {
  343. #if AI_TRACE_LEVEL >= 2
  344. logAi->trace(
  345. "Skip exchange %s[%x] -> %s[%x] at %s because of %s",
  346. node->actor->toString(),
  347. node->actor->chainMask,
  348. srcNode->actor->toString(),
  349. srcNode->actor->chainMask,
  350. srcNode->coord.toString(),
  351. (node->turns > heroChainTurn
  352. ? "turn limit"
  353. : (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  354. ? "action unknown"
  355. : "chain mask"));
  356. #endif
  357. continue;
  358. }
  359. #if AI_TRACE_LEVEL >= 2
  360. logAi->trace(
  361. "Thy exchange %s[%x] -> %s[%x] at %s",
  362. node->actor->toString(),
  363. node->actor->chainMask,
  364. srcNode->actor->toString(),
  365. srcNode->actor->chainMask,
  366. srcNode->coord.toString());
  367. #endif
  368. calculateHeroChain(srcNode, node, result);
  369. }
  370. }
  371. void AINodeStorage::calculateHeroChain(
  372. AIPathNode * carrier,
  373. AIPathNode * other,
  374. std::vector<ExchangeCandidate> & result) const
  375. {
  376. if(carrier->armyLoss < carrier->actor->armyValue
  377. && (carrier->action != CGPathNode::BATTLE || (carrier->actor->allowBattle && carrier->specialAction))
  378. && carrier->action != CGPathNode::BLOCKING_VISIT
  379. && other->armyLoss < other->actor->armyValue
  380. && carrier->actor->canExchange(other->actor))
  381. {
  382. #if AI_TRACE_LEVEL >= 2
  383. logAi->trace(
  384. "Exchange allowed %s[%x] -> %s[%x] at %s",
  385. other->actor->toString(),
  386. other->actor->chainMask,
  387. carrier->actor->toString(),
  388. carrier->actor->chainMask,
  389. carrier->coord.toString());
  390. #endif
  391. if(other->actor->isMovable)
  392. {
  393. bool hasLessMp = carrier->turns > other->turns || carrier->moveRemains < other->moveRemains;
  394. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  395. if(hasLessMp && hasLessExperience)
  396. {
  397. #if AI_TRACE_LEVEL >= 2
  398. logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
  399. #endif
  400. return;
  401. }
  402. }
  403. auto newActor = carrier->actor->exchange(other->actor);
  404. result.push_back(calculateExchange(newActor, carrier, other));
  405. }
  406. }
  407. void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
  408. {
  409. for(const ExchangeCandidate & chainInfo : result)
  410. {
  411. auto carrier = chainInfo.carrierParent;
  412. auto newActor = chainInfo.actor;
  413. auto other = chainInfo.otherParent;
  414. auto chainNodeOptional = getOrCreateNode(carrier->coord, carrier->layer, newActor);
  415. if(!chainNodeOptional)
  416. {
  417. #if AI_TRACE_LEVEL >= 2
  418. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  419. #endif
  420. continue;
  421. }
  422. auto exchangeNode = chainNodeOptional.get();
  423. if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
  424. {
  425. #if AI_TRACE_LEVEL >= 2
  426. logAi->trace("Exchange at %s node is already in use. Blocked.", carrier->coord.toString());
  427. #endif
  428. continue;
  429. }
  430. if(exchangeNode->turns != 0xFF && exchangeNode->cost < chainInfo.cost)
  431. {
  432. #if AI_TRACE_LEVEL >= 2
  433. logAi->trace(
  434. "Exchange at %s is is not effective enough. %f < %f",
  435. exchangeNode->coord.toString(),
  436. exchangeNode->cost,
  437. chainInfo.cost);
  438. #endif
  439. continue;
  440. }
  441. commit(exchangeNode, carrier, carrier->action, chainInfo.turns, chainInfo.moveRemains, chainInfo.cost);
  442. if(carrier->specialAction || carrier->chainOther)
  443. {
  444. // there is some action on source tile which should be performed before we can bypass it
  445. exchangeNode->theNodeBefore = carrier;
  446. }
  447. exchangeNode->chainOther = other;
  448. exchangeNode->armyLoss = chainInfo.armyLoss;
  449. #if AI_TRACE_LEVEL >= 2
  450. logAi->trace(
  451. "Chain accepted at %s %s -> %s, mask %x, cost %f, turn: %s, mp: %d, army %i",
  452. exchangeNode->coord.toString(),
  453. other->actor->toString(),
  454. exchangeNode->actor->toString(),
  455. exchangeNode->actor->chainMask,
  456. exchangeNode->cost,
  457. std::to_string(exchangeNode->turns),
  458. exchangeNode->moveRemains,
  459. exchangeNode->actor->armyValue);
  460. #endif
  461. heroChain.push_back(exchangeNode);
  462. }
  463. }
  464. ExchangeCandidate AINodeStorage::calculateExchange(
  465. ChainActor * exchangeActor,
  466. AIPathNode * carrierParentNode,
  467. AIPathNode * otherParentNode) const
  468. {
  469. ExchangeCandidate candidate;
  470. candidate.layer = carrierParentNode->layer;
  471. candidate.coord = carrierParentNode->coord;
  472. candidate.carrierParent = carrierParentNode;
  473. candidate.otherParent = otherParentNode;
  474. candidate.actor = exchangeActor;
  475. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  476. candidate.turns = carrierParentNode->turns;
  477. candidate.cost = carrierParentNode->cost + otherParentNode->cost / 1000.0;
  478. candidate.moveRemains = carrierParentNode->moveRemains;
  479. if(carrierParentNode->turns < otherParentNode->turns)
  480. {
  481. int moveRemains = exchangeActor->hero->maxMovePoints(carrierParentNode->layer);
  482. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  483. + carrierParentNode->moveRemains / (float)moveRemains;
  484. candidate.turns = otherParentNode->turns;
  485. candidate.cost += waitingCost;
  486. candidate.moveRemains = moveRemains;
  487. }
  488. return candidate;
  489. }
  490. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  491. {
  492. auto aiNode = getAINode(node);
  493. return aiNode->actor->hero;
  494. }
  495. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  496. {
  497. std::set<const CGHeroInstance *> heroes;
  498. for(auto actor : actors)
  499. {
  500. if(actor->hero)
  501. heroes.insert(actor->hero);
  502. }
  503. return heroes;
  504. }
  505. void AINodeStorage::setHeroes(std::vector<HeroPtr> heroes, const VCAI * _ai)
  506. {
  507. cb = _ai->myCb.get();
  508. ai = _ai;
  509. playerID = ai->playerID;
  510. for(auto & hero : heroes)
  511. {
  512. uint64_t mask = 1 << actors.size();
  513. auto actor = std::make_shared<HeroActor>(hero.get(), mask, ai);
  514. if(hero->tempOwner != ai->playerID)
  515. {
  516. bool onLand = !actor->hero->boat;
  517. actor->initialMovement = actor->hero->maxMovePoints(onLand);
  518. }
  519. playerID = hero->tempOwner;
  520. actors.push_back(actor);
  521. }
  522. }
  523. void AINodeStorage::setTownsAndDwellings(
  524. const std::vector<const CGTownInstance *> & towns,
  525. const std::set<const CGObjectInstance *> & visitableObjs)
  526. {
  527. for(auto town : towns)
  528. {
  529. uint64_t mask = 1 << actors.size();
  530. if(!town->garrisonHero && town->getUpperArmy()->getArmyStrength())
  531. {
  532. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  533. }
  534. }
  535. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  536. auto waitForGrowth = dayOfWeek > 4;
  537. for(auto obj: visitableObjs)
  538. {
  539. const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  540. if(dwelling)
  541. {
  542. uint64_t mask = 1 << actors.size();
  543. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  544. if(dwellingActor->creatureSet->getArmyStrength())
  545. {
  546. actors.push_back(dwellingActor);
  547. }
  548. if(waitForGrowth)
  549. {
  550. mask = 1 << actors.size();
  551. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  552. if(dwellingActor->creatureSet->getArmyStrength())
  553. {
  554. actors.push_back(dwellingActor);
  555. }
  556. }
  557. }
  558. }*/
  559. }
  560. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  561. const PathNodeInfo & source,
  562. const PathfinderConfig * pathfinderConfig,
  563. const CPathfinderHelper * pathfinderHelper)
  564. {
  565. std::vector<CGPathNode *> neighbours;
  566. if(source.isNodeObjectVisitable())
  567. {
  568. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  569. auto srcNode = getAINode(source.node);
  570. for(auto & neighbour : accessibleExits)
  571. {
  572. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  573. if(!node)
  574. continue;
  575. neighbours.push_back(node.get());
  576. }
  577. }
  578. return neighbours;
  579. }
  580. struct TowmPortalFinder
  581. {
  582. const std::vector<CGPathNode *> & initialNodes;
  583. SecSkillLevel::SecSkillLevel townPortalSkillLevel;
  584. uint64_t movementNeeded;
  585. const ChainActor * actor;
  586. const CGHeroInstance * hero;
  587. std::vector<const CGTownInstance *> targetTowns;
  588. AINodeStorage * nodeStorage;
  589. SpellID spellID;
  590. const CSpell * townPortal;
  591. TowmPortalFinder(
  592. const ChainActor * actor,
  593. const std::vector<CGPathNode *> & initialNodes,
  594. std::vector<const CGTownInstance *> targetTowns,
  595. AINodeStorage * nodeStorage)
  596. :actor(actor), initialNodes(initialNodes), hero(actor->hero),
  597. targetTowns(targetTowns), nodeStorage(nodeStorage)
  598. {
  599. spellID = SpellID::TOWN_PORTAL;
  600. townPortal = spellID.toSpell();
  601. // TODO: Copy/Paste from TownPortalMechanics
  602. townPortalSkillLevel = SecSkillLevel::SecSkillLevel(hero->getSpellSchoolLevel(townPortal));
  603. movementNeeded = GameConstants::BASE_MOVEMENT_COST * (townPortalSkillLevel >= SecSkillLevel::EXPERT ? 2 : 3);
  604. }
  605. bool actorCanCastTownPortal()
  606. {
  607. return hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal);
  608. }
  609. CGPathNode * getBestInitialNodeForTownPortal(const CGTownInstance * targetTown)
  610. {
  611. CGPathNode * bestNode = nullptr;
  612. for(CGPathNode * node : initialNodes)
  613. {
  614. auto aiNode = nodeStorage->getAINode(node);
  615. if(aiNode->actor->baseActor != actor
  616. || node->layer != EPathfindingLayer::LAND
  617. || node->moveRemains < movementNeeded)
  618. {
  619. continue;
  620. }
  621. if(townPortalSkillLevel < SecSkillLevel::ADVANCED)
  622. {
  623. const CGTownInstance * nearestTown = *vstd::minElementByFun(targetTowns, [&](const CGTownInstance * t) -> int
  624. {
  625. return node->coord.dist2dSQ(t->visitablePos());
  626. });
  627. if(targetTown != nearestTown)
  628. continue;
  629. }
  630. if(!bestNode || bestNode->cost > node->cost)
  631. bestNode = node;
  632. }
  633. return bestNode;
  634. }
  635. boost::optional<AIPathNode *> createTownPortalNode(const CGTownInstance * targetTown)
  636. {
  637. auto bestNode = getBestInitialNodeForTownPortal(targetTown);
  638. if(!bestNode)
  639. return boost::none;
  640. auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor);
  641. if(!nodeOptional)
  642. return boost::none;
  643. AIPathNode * node = nodeOptional.get();
  644. float movementCost = (float)movementNeeded / (float)hero->maxMovePoints(EPathfindingLayer::LAND);
  645. movementCost += bestNode->cost;
  646. if(node->action == CGPathNode::UNKNOWN || node->cost > movementCost)
  647. {
  648. nodeStorage->commit(
  649. node,
  650. nodeStorage->getAINode(bestNode),
  651. CGPathNode::TELEPORT_NORMAL,
  652. bestNode->turns,
  653. bestNode->moveRemains - movementNeeded,
  654. movementCost);
  655. node->theNodeBefore = bestNode;
  656. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  657. }
  658. return nodeOptional;
  659. }
  660. };
  661. void AINodeStorage::calculateTownPortalTeleportations(std::vector<CGPathNode *> & initialNodes)
  662. {
  663. std::set<const ChainActor *> actorsOfInitial;
  664. for(const CGPathNode * node : initialNodes)
  665. {
  666. auto aiNode = getAINode(node);
  667. actorsOfInitial.insert(aiNode->actor->baseActor);
  668. }
  669. for(const ChainActor * actor : actorsOfInitial)
  670. {
  671. if(!actor->hero)
  672. continue;
  673. auto towns = cb->getTownsInfo(false);
  674. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  675. {
  676. return cb->getPlayerRelations(actor->hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  677. });
  678. if(!towns.size())
  679. {
  680. return; // no towns no need to run loop further
  681. }
  682. TowmPortalFinder townPortalFinder(actor, initialNodes, towns, this);
  683. if(townPortalFinder.actorCanCastTownPortal())
  684. {
  685. for(const CGTownInstance * targetTown : towns)
  686. {
  687. // TODO: allow to hide visiting hero in garrison
  688. if(targetTown->visitingHero && targetTown->visitingHero != actor->hero)
  689. continue;
  690. auto nodeOptional = townPortalFinder.createTownPortalNode(targetTown);
  691. if(nodeOptional)
  692. {
  693. #if AI_TRACE_LEVEL >= 1
  694. logAi->trace("Adding town portal node at %s", targetTown->name);
  695. #endif
  696. initialNodes.push_back(nodeOptional.get());
  697. }
  698. }
  699. }
  700. }
  701. }
  702. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  703. {
  704. auto pos = destination.coord;
  705. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  706. return hasBetterChain(source.node, getAINode(destination.node), chains);
  707. }
  708. template<class NodeRange>
  709. bool AINodeStorage::hasBetterChain(
  710. const CGPathNode * source,
  711. const AIPathNode * candidateNode,
  712. const NodeRange & chains) const
  713. {
  714. auto candidateActor = candidateNode->actor;
  715. for(const AIPathNode & node : chains)
  716. {
  717. auto sameNode = node.actor == candidateNode->actor;
  718. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor->hero)
  719. {
  720. continue;
  721. }
  722. if(node.danger <= candidateNode->danger && candidateNode->actor == node.actor->battleActor)
  723. {
  724. if(node.cost < candidateNode->cost)
  725. {
  726. #if AI_TRACE_LEVEL >= 2
  727. logAi->trace(
  728. "Block ineficient battle move %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  729. source->coord.toString(),
  730. candidateNode->coord.toString(),
  731. candidateNode->actor->hero->name,
  732. candidateNode->actor->chainMask,
  733. candidateNode->actor->armyValue,
  734. node.moveRemains - candidateNode->moveRemains);
  735. #endif
  736. return true;
  737. }
  738. }
  739. if(candidateActor->chainMask != node.actor->chainMask)
  740. continue;
  741. auto nodeActor = node.actor;
  742. auto nodeArmyValue = nodeActor->armyValue - node.armyLoss;
  743. auto candidateArmyValue = candidateActor->armyValue - candidateNode->armyLoss;
  744. if(nodeArmyValue > candidateArmyValue
  745. && node.cost <= candidateNode->cost)
  746. {
  747. #if AI_TRACE_LEVEL >= 2
  748. logAi->trace(
  749. "Block ineficient move because of stronger army %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  750. source->coord.toString(),
  751. candidateNode->coord.toString(),
  752. candidateNode->actor->hero->name,
  753. candidateNode->actor->chainMask,
  754. candidateNode->actor->armyValue,
  755. node.moveRemains - candidateNode->moveRemains);
  756. #endif
  757. return true;
  758. }
  759. /*if(nodeArmyValue == candidateArmyValue
  760. && nodeActor->heroFightingStrength >= candidateActor->heroFightingStrength
  761. && node.cost <= candidateNode->cost)
  762. {
  763. if(nodeActor->heroFightingStrength == candidateActor->heroFightingStrength
  764. && node.cost == candidateNode->cost
  765. && &node < candidateNode)
  766. {
  767. continue;
  768. }
  769. #if AI_TRACE_LEVEL >= 2
  770. logAi->trace(
  771. "Block ineficient move because of stronger hero %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  772. source->coord.toString(),
  773. candidateNode->coord.toString(),
  774. candidateNode->actor->hero->name,
  775. candidateNode->actor->chainMask,
  776. candidateNode->actor->armyValue,
  777. node.moveRemains - candidateNode->moveRemains);
  778. #endif
  779. return true;
  780. }*/
  781. }
  782. return false;
  783. }
  784. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  785. {
  786. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  787. for(const AIPathNode & node : chains)
  788. {
  789. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  790. && node.actor && node.actor->hero == hero.h)
  791. {
  792. return true;
  793. }
  794. }
  795. return false;
  796. }
  797. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  798. {
  799. std::vector<AIPath> paths;
  800. paths.reserve(NUM_CHAINS / 4);
  801. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  802. for(const AIPathNode & node : chains)
  803. {
  804. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  805. {
  806. continue;
  807. }
  808. AIPath path;
  809. path.targetHero = node.actor->hero;
  810. path.heroArmy = node.actor->creatureSet;
  811. path.armyLoss = node.armyLoss;
  812. path.targetObjectDanger = evaluateDanger(pos, path.targetHero);
  813. path.targetObjectArmyLoss = evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  814. path.chainMask = node.actor->chainMask;
  815. path.exchangeCount = node.actor->actorExchangeCount;
  816. fillChainInfo(&node, path, -1);
  817. paths.push_back(path);
  818. }
  819. return paths;
  820. }
  821. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  822. {
  823. while(node != nullptr)
  824. {
  825. if(!node->actor->hero)
  826. return;
  827. if(node->chainOther)
  828. fillChainInfo(node->chainOther, path, parentIndex);
  829. //if(node->actor->hero->visitablePos() != node->coord)
  830. {
  831. AIPathNodeInfo pathNode;
  832. pathNode.cost = node->cost;
  833. pathNode.targetHero = node->actor->hero;
  834. pathNode.chainMask = node->actor->chainMask;
  835. pathNode.specialAction = node->specialAction;
  836. pathNode.turns = node->turns;
  837. pathNode.danger = node->danger;
  838. pathNode.coord = node->coord;
  839. pathNode.parentIndex = parentIndex;
  840. parentIndex = path.nodes.size();
  841. path.nodes.push_back(pathNode);
  842. }
  843. path.specialAction = node->specialAction;
  844. node = getAINode(node->theNodeBefore);
  845. }
  846. }
  847. AIPath::AIPath()
  848. : nodes({})
  849. {
  850. }
  851. std::shared_ptr<const ISpecialAction> AIPath::getFirstBlockedAction() const
  852. {
  853. for(auto node : nodes)
  854. {
  855. if(node.specialAction && !node.specialAction->canAct(node.targetHero))
  856. return node.specialAction;
  857. }
  858. return std::shared_ptr<const ISpecialAction>();
  859. }
  860. int3 AIPath::firstTileToGet() const
  861. {
  862. if(nodes.size())
  863. {
  864. return nodes.back().coord;
  865. }
  866. return int3(-1, -1, -1);
  867. }
  868. int3 AIPath::targetTile() const
  869. {
  870. if(nodes.size())
  871. {
  872. return targetNode().coord;
  873. }
  874. return int3(-1, -1, -1);
  875. }
  876. const AIPathNodeInfo & AIPath::firstNode() const
  877. {
  878. return nodes.back();
  879. }
  880. const AIPathNodeInfo & AIPath::targetNode() const
  881. {
  882. auto & node = nodes.front();
  883. return targetHero == node.targetHero ? node : nodes.at(1);
  884. }
  885. uint64_t AIPath::getPathDanger() const
  886. {
  887. if(nodes.empty())
  888. return 0;
  889. return targetNode().danger;
  890. }
  891. float AIPath::movementCost() const
  892. {
  893. if(nodes.empty())
  894. return 0.0f;
  895. return targetNode().cost;
  896. }
  897. uint8_t AIPath::turn() const
  898. {
  899. if(nodes.empty())
  900. return 0;
  901. return targetNode().turns;
  902. }
  903. uint64_t AIPath::getHeroStrength() const
  904. {
  905. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  906. }
  907. uint64_t AIPath::getTotalDanger() const
  908. {
  909. uint64_t pathDanger = getPathDanger();
  910. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  911. return danger;
  912. }
  913. uint64_t AIPath::getTotalArmyLoss() const
  914. {
  915. return armyLoss + targetObjectArmyLoss;
  916. }
  917. std::string AIPath::toString() const
  918. {
  919. std::stringstream str;
  920. str << targetHero->name << "[" << std::hex << chainMask << std::dec << "]" << ": ";
  921. for(auto node : nodes)
  922. str << node.targetHero->name << "[" << std::hex << node.chainMask << std::dec << "]" << "->" << node.coord.toString() << "; ";
  923. return str.str();
  924. }