ObjectGraph.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. /*
  2. * ObjectGraph.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 "ObjectGraph.h"
  12. #include "AIPathfinderConfig.h"
  13. #include "../../../lib/CRandomGenerator.h"
  14. #include "../../../CCallback.h"
  15. #include "../../../lib/mapping/CMap.h"
  16. #include "../Engine/Nullkiller.h"
  17. #include "../../../lib/logging/VisualLogger.h"
  18. #include "Actions/QuestAction.h"
  19. #include "../pforeach.h"
  20. namespace NKAI
  21. {
  22. struct ConnectionCostInfo
  23. {
  24. float totalCost = 0;
  25. float avg = 0;
  26. int connectionsCount = 0;
  27. };
  28. class ObjectGraphCalculator
  29. {
  30. private:
  31. ObjectGraph * target;
  32. const Nullkiller * ai;
  33. std::mutex syncLock;
  34. std::map<const CGHeroInstance *, HeroRole> actors;
  35. std::map<const CGHeroInstance *, const CGObjectInstance *> actorObjectMap;
  36. std::vector<std::unique_ptr<CGBoat>> temporaryBoats;
  37. std::vector<std::unique_ptr<CGHeroInstance>> temporaryActorHeroes;
  38. public:
  39. ObjectGraphCalculator(ObjectGraph * target, const Nullkiller * ai)
  40. :ai(ai), target(target), syncLock()
  41. {
  42. }
  43. void setGraphObjects()
  44. {
  45. for(auto obj : ai->memory->visitableObjs)
  46. {
  47. if(obj && obj->isVisitable() && obj->ID != Obj::HERO && obj->ID != Obj::EVENT)
  48. {
  49. addObjectActor(obj);
  50. }
  51. }
  52. for(auto town : ai->cb->getTownsInfo())
  53. {
  54. addObjectActor(town);
  55. }
  56. }
  57. void calculateConnections()
  58. {
  59. updatePaths();
  60. std::vector<AIPath> pathCache;
  61. foreach_tile_pos(ai->cb.get(), [this, &pathCache](const CPlayerSpecificInfoCallback * cb, const int3 & pos)
  62. {
  63. calculateConnections(pos, pathCache);
  64. });
  65. removeExtraConnections();
  66. }
  67. float getNeighborConnectionsCost(const int3 & pos, std::vector<AIPath> & pathCache)
  68. {
  69. float neighborCost = std::numeric_limits<float>::max();
  70. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  71. {
  72. logAi->trace("Checking junction %s", pos.toString());
  73. }
  74. foreach_neighbour(
  75. ai->cb.get(),
  76. pos,
  77. [this, &neighborCost, &pathCache](const CPlayerSpecificInfoCallback * cb, const int3 & neighbor)
  78. {
  79. ai->pathfinder->calculatePathInfo(pathCache, neighbor);
  80. auto costTotal = this->getConnectionsCost(pathCache);
  81. if(costTotal.connectionsCount > 2 && costTotal.avg < neighborCost)
  82. {
  83. neighborCost = costTotal.avg;
  84. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  85. {
  86. logAi->trace("Better node found at %s", neighbor.toString());
  87. }
  88. }
  89. });
  90. return neighborCost;
  91. }
  92. void addMinimalDistanceJunctions()
  93. {
  94. pforeachTilePaths(ai->cb->getMapSize(), ai, [this](const int3 & pos, std::vector<AIPath> & paths)
  95. {
  96. if(target->hasNodeAt(pos))
  97. return;
  98. if(ai->cb->getGuardingCreaturePosition(pos).valid())
  99. return;
  100. ConnectionCostInfo currentCost = getConnectionsCost(paths);
  101. if(currentCost.connectionsCount <= 2)
  102. return;
  103. float neighborCost = getNeighborConnectionsCost(pos, paths);
  104. if(currentCost.avg < neighborCost)
  105. {
  106. addJunctionActor(pos);
  107. }
  108. });
  109. }
  110. private:
  111. void updatePaths()
  112. {
  113. PathfinderSettings ps;
  114. ps.mainTurnDistanceLimit = 5;
  115. ps.scoutTurnDistanceLimit = 1;
  116. ps.allowBypassObjects = false;
  117. ai->pathfinder->updatePaths(actors, ps);
  118. }
  119. void calculateConnections(const int3 & pos, std::vector<AIPath> & pathCache)
  120. {
  121. if(target->hasNodeAt(pos))
  122. {
  123. foreach_neighbour(
  124. ai->cb.get(),
  125. pos,
  126. [this, &pos, &pathCache](const CPlayerSpecificInfoCallback * cb, const int3 & neighbor)
  127. {
  128. if(target->hasNodeAt(neighbor))
  129. {
  130. ai->pathfinder->calculatePathInfo(pathCache, neighbor);
  131. for(auto & path : pathCache)
  132. {
  133. if(pos == path.targetHero->visitablePos())
  134. {
  135. target->tryAddConnection(pos, neighbor, path.movementCost(), path.getTotalDanger());
  136. }
  137. }
  138. }
  139. });
  140. auto obj = ai->cb->getTopObj(pos);
  141. if(obj && obj->ID == Obj::BOAT)
  142. {
  143. ai->pathfinder->calculatePathInfo(pathCache, pos);
  144. for(AIPath & path : pathCache)
  145. {
  146. auto from = path.targetHero->visitablePos();
  147. auto fromObj = actorObjectMap[path.targetHero];
  148. auto fromTile = cb->getTile(from);
  149. auto danger = ai->pathfinder->getStorage()->evaluateDanger(pos, path.targetHero, true);
  150. auto updated = target->tryAddConnection(
  151. from,
  152. pos,
  153. path.movementCost(),
  154. danger);
  155. if(NKAI_GRAPH_TRACE_LEVEL >= 2 && updated)
  156. {
  157. logAi->trace(
  158. "Connected %s[%s] -> %s[%s] through [%s], cost %2f",
  159. fromObj ? fromObj->getObjectName() : "J", from.toString(),
  160. "Boat", pos.toString(),
  161. pos.toString(),
  162. path.movementCost());
  163. }
  164. }
  165. }
  166. return;
  167. }
  168. auto guardPos = ai->cb->getGuardingCreaturePosition(pos);
  169. ai->pathfinder->calculatePathInfo(pathCache, pos);
  170. for(AIPath & path1 : pathCache)
  171. {
  172. for(AIPath & path2 : pathCache)
  173. {
  174. if(path1.targetHero == path2.targetHero)
  175. continue;
  176. auto pos1 = path1.targetHero->visitablePos();
  177. auto pos2 = path2.targetHero->visitablePos();
  178. if(guardPos.valid() && guardPos != pos1 && guardPos != pos2)
  179. continue;
  180. auto obj1 = actorObjectMap[path1.targetHero];
  181. auto obj2 = actorObjectMap[path2.targetHero];
  182. auto tile1 = cb->getTile(pos1);
  183. auto tile2 = cb->getTile(pos2);
  184. if(tile2->isWater() && !tile1->isWater())
  185. {
  186. if(!cb->getTile(pos)->isWater())
  187. continue;
  188. auto startingObjIsBoatOrShipyard = obj1 && (obj1->ID == Obj::BOAT || obj1->ID == Obj::SHIPYARD);
  189. if(!startingObjIsBoatOrShipyard)
  190. continue;
  191. }
  192. auto danger = ai->pathfinder->getStorage()->evaluateDanger(pos2, path1.targetHero, true);
  193. auto updated = target->tryAddConnection(
  194. pos1,
  195. pos2,
  196. path1.movementCost() + path2.movementCost(),
  197. danger);
  198. if(NKAI_GRAPH_TRACE_LEVEL >= 2 && updated)
  199. {
  200. logAi->trace(
  201. "Connected %s[%s] -> %s[%s] through [%s], cost %2f",
  202. obj1 ? obj1->getObjectName() : "J", pos1.toString(),
  203. obj2 ? obj2->getObjectName() : "J", pos2.toString(),
  204. pos.toString(),
  205. path1.movementCost() + path2.movementCost());
  206. }
  207. }
  208. }
  209. }
  210. bool isExtraConnection(float direct, float side1, float side2) const
  211. {
  212. float sideRatio = (side1 + side2) / direct;
  213. return sideRatio < 1.25f && direct > side1 && direct > side2;
  214. }
  215. void removeExtraConnections()
  216. {
  217. std::vector<std::pair<int3, int3>> connectionsToRemove;
  218. for(auto & actor : temporaryActorHeroes)
  219. {
  220. auto pos = actor->visitablePos();
  221. auto & currentNode = target->getNode(pos);
  222. target->iterateConnections(pos, [this, &pos, &connectionsToRemove, &currentNode](int3 n1, ObjectLink o1)
  223. {
  224. target->iterateConnections(n1, [&pos, &o1, &currentNode, &connectionsToRemove, this](int3 n2, ObjectLink o2)
  225. {
  226. auto direct = currentNode.connections.find(n2);
  227. if(direct != currentNode.connections.end() && isExtraConnection(direct->second.cost, o1.cost, o2.cost))
  228. {
  229. connectionsToRemove.push_back({pos, n2});
  230. }
  231. });
  232. });
  233. }
  234. vstd::removeDuplicates(connectionsToRemove);
  235. for(auto & c : connectionsToRemove)
  236. {
  237. target->removeConnection(c.first, c.second);
  238. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  239. {
  240. logAi->trace("Remove ineffective connection %s->%s", c.first.toString(), c.second.toString());
  241. }
  242. }
  243. }
  244. void addObjectActor(const CGObjectInstance * obj)
  245. {
  246. auto objectActor = temporaryActorHeroes.emplace_back(std::make_unique<CGHeroInstance>(obj->cb)).get();
  247. CRandomGenerator rng;
  248. auto visitablePos = obj->visitablePos();
  249. objectActor->setOwner(ai->playerID); // lets avoid having multiple colors
  250. objectActor->initHero(rng, static_cast<HeroTypeID>(0));
  251. objectActor->pos = objectActor->convertFromVisitablePos(visitablePos);
  252. objectActor->initObj(rng);
  253. if(cb->getTile(visitablePos)->isWater())
  254. {
  255. objectActor->boat = temporaryBoats.emplace_back(std::make_unique<CGBoat>(objectActor->cb)).get();
  256. }
  257. assert(objectActor->visitablePos() == visitablePos);
  258. actorObjectMap[objectActor] = obj;
  259. actors[objectActor] = obj->ID == Obj::TOWN || obj->ID == Obj::SHIPYARD || obj->ID == Obj::BOAT ? HeroRole::MAIN : HeroRole::SCOUT;
  260. target->addObject(obj);
  261. }
  262. void addJunctionActor(const int3 & visitablePos)
  263. {
  264. std::lock_guard<std::mutex> lock(syncLock);
  265. auto internalCb = temporaryActorHeroes.front()->cb;
  266. auto objectActor = temporaryActorHeroes.emplace_back(std::make_unique<CGHeroInstance>(internalCb)).get();
  267. CRandomGenerator rng;
  268. objectActor->setOwner(ai->playerID); // lets avoid having multiple colors
  269. objectActor->initHero(rng, static_cast<HeroTypeID>(0));
  270. objectActor->pos = objectActor->convertFromVisitablePos(visitablePos);
  271. objectActor->initObj(rng);
  272. if(ai->cb->getTile(visitablePos)->isWater())
  273. {
  274. objectActor->boat = temporaryBoats.emplace_back(std::make_unique<CGBoat>(objectActor->cb)).get();
  275. }
  276. assert(objectActor->visitablePos() == visitablePos);
  277. actorObjectMap[objectActor] = nullptr;
  278. actors[objectActor] = HeroRole::SCOUT;
  279. target->registerJunction(visitablePos);
  280. }
  281. ConnectionCostInfo getConnectionsCost(std::vector<AIPath> & paths) const
  282. {
  283. std::map<int3, float> costs;
  284. for(auto & path : paths)
  285. {
  286. auto fromPos = path.targetHero->visitablePos();
  287. auto cost = costs.find(fromPos);
  288. if(cost == costs.end())
  289. {
  290. costs.emplace(fromPos, path.movementCost());
  291. }
  292. else
  293. {
  294. if(path.movementCost() < cost->second)
  295. {
  296. costs[fromPos] = path.movementCost();
  297. }
  298. }
  299. }
  300. ConnectionCostInfo result;
  301. for(auto & cost : costs)
  302. {
  303. result.totalCost += cost.second;
  304. result.connectionsCount++;
  305. }
  306. if(result.connectionsCount)
  307. {
  308. result.avg = result.totalCost / result.connectionsCount;
  309. }
  310. return result;
  311. }
  312. };
  313. bool ObjectGraph::tryAddConnection(
  314. const int3 & from,
  315. const int3 & to,
  316. float cost,
  317. uint64_t danger)
  318. {
  319. return nodes[from].connections[to].update(cost, danger);
  320. }
  321. void ObjectGraph::removeConnection(const int3 & from, const int3 & to)
  322. {
  323. nodes[from].connections.erase(to);
  324. }
  325. void ObjectGraph::updateGraph(const Nullkiller * ai)
  326. {
  327. auto cb = ai->cb;
  328. ObjectGraphCalculator calculator(this, ai);
  329. calculator.setGraphObjects();
  330. calculator.calculateConnections();
  331. calculator.addMinimalDistanceJunctions();
  332. calculator.calculateConnections();
  333. if(NKAI_GRAPH_TRACE_LEVEL >= 1)
  334. dumpToLog("graph");
  335. }
  336. void ObjectGraph::addObject(const CGObjectInstance * obj)
  337. {
  338. nodes[obj->visitablePos()].init(obj);
  339. }
  340. void ObjectGraph::registerJunction(const int3 & pos)
  341. {
  342. nodes[pos].initJunction();
  343. }
  344. void ObjectGraph::removeObject(const CGObjectInstance * obj)
  345. {
  346. nodes[obj->visitablePos()].objectExists = false;
  347. if(obj->ID == Obj::BOAT)
  348. {
  349. vstd::erase_if(nodes[obj->visitablePos()].connections, [&](const std::pair<int3, ObjectLink> & link) -> bool
  350. {
  351. auto tile = cb->getTile(link.first, false);
  352. return tile && tile->isWater();
  353. });
  354. }
  355. }
  356. void ObjectGraph::connectHeroes(const Nullkiller * ai)
  357. {
  358. for(auto obj : ai->memory->visitableObjs)
  359. {
  360. if(obj && obj->ID == Obj::HERO)
  361. {
  362. addObject(obj);
  363. }
  364. }
  365. for(auto & node : nodes)
  366. {
  367. auto pos = node.first;
  368. auto paths = ai->pathfinder->getPathInfo(pos);
  369. for(AIPath & path : paths)
  370. {
  371. if(path.getFirstBlockedAction())
  372. continue;
  373. auto heroPos = path.targetHero->visitablePos();
  374. nodes[pos].connections[heroPos].update(
  375. path.movementCost(),
  376. path.getPathDanger());
  377. nodes[heroPos].connections[pos].update(
  378. path.movementCost(),
  379. path.getPathDanger());
  380. }
  381. }
  382. }
  383. void ObjectGraph::dumpToLog(std::string visualKey) const
  384. {
  385. logVisual->updateWithLock(visualKey, [&](IVisualLogBuilder & logBuilder)
  386. {
  387. for(auto & tile : nodes)
  388. {
  389. for(auto & node : tile.second.connections)
  390. {
  391. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  392. {
  393. logAi->trace(
  394. "%s -> %s: %f !%d",
  395. node.first.toString(),
  396. tile.first.toString(),
  397. node.second.cost,
  398. node.second.danger);
  399. }
  400. logBuilder.addLine(tile.first, node.first);
  401. }
  402. }
  403. });
  404. }
  405. bool GraphNodeComparer::operator()(const GraphPathNodePointer & lhs, const GraphPathNodePointer & rhs) const
  406. {
  407. return pathNodes.at(lhs.coord)[lhs.nodeType].cost > pathNodes.at(rhs.coord)[rhs.nodeType].cost;
  408. }
  409. GraphPaths::GraphPaths()
  410. : visualKey(""), graph(), pathNodes()
  411. {
  412. }
  413. void GraphPaths::calculatePaths(const CGHeroInstance * targetHero, const Nullkiller * ai)
  414. {
  415. graph.copyFrom(*ai->baseGraph);
  416. graph.connectHeroes(ai);
  417. visualKey = std::to_string(ai->playerID) + ":" + targetHero->getNameTranslated();
  418. pathNodes.clear();
  419. GraphNodeComparer cmp(pathNodes);
  420. GraphPathNode::TFibHeap pq(cmp);
  421. pathNodes[targetHero->visitablePos()][GrapthPathNodeType::NORMAL].cost = 0;
  422. pq.emplace(GraphPathNodePointer(targetHero->visitablePos(), GrapthPathNodeType::NORMAL));
  423. while(!pq.empty())
  424. {
  425. GraphPathNodePointer pos = pq.top();
  426. pq.pop();
  427. auto & node = getOrCreateNode(pos);
  428. std::shared_ptr<SpecialAction> transitionAction;
  429. if(node.obj)
  430. {
  431. if(node.obj->ID == Obj::QUEST_GUARD
  432. || node.obj->ID == Obj::BORDERGUARD
  433. || node.obj->ID == Obj::BORDER_GATE)
  434. {
  435. auto questObj = dynamic_cast<const IQuestObject *>(node.obj);
  436. auto questInfo = QuestInfo(questObj->quest, node.obj, pos.coord);
  437. if(node.obj->ID == Obj::QUEST_GUARD
  438. && questObj->quest->mission == Rewardable::Limiter{}
  439. && questObj->quest->killTarget == ObjectInstanceID::NONE)
  440. {
  441. continue;
  442. }
  443. auto questAction = std::make_shared<AIPathfinding::QuestAction>(questInfo);
  444. if(!questAction->canAct(targetHero))
  445. {
  446. transitionAction = questAction;
  447. }
  448. }
  449. }
  450. node.isInQueue = false;
  451. graph.iterateConnections(pos.coord, [this, ai, &pos, &node, &transitionAction, &pq](int3 target, ObjectLink o)
  452. {
  453. auto targetNodeType = o.danger || transitionAction ? GrapthPathNodeType::BATTLE : pos.nodeType;
  454. auto targetPointer = GraphPathNodePointer(target, targetNodeType);
  455. auto & targetNode = getOrCreateNode(targetPointer);
  456. if(targetNode.tryUpdate(pos, node, o))
  457. {
  458. targetNode.specialAction = transitionAction;
  459. auto targetGraphNode = graph.getNode(target);
  460. if(targetGraphNode.objID.hasValue())
  461. {
  462. targetNode.obj = ai->cb->getObj(targetGraphNode.objID, false);
  463. if(targetNode.obj && targetNode.obj->ID == Obj::HERO)
  464. return;
  465. }
  466. if(targetNode.isInQueue)
  467. {
  468. pq.increase(targetNode.handle);
  469. }
  470. else
  471. {
  472. targetNode.handle = pq.emplace(targetPointer);
  473. targetNode.isInQueue = true;
  474. }
  475. }
  476. });
  477. }
  478. }
  479. void GraphPaths::dumpToLog() const
  480. {
  481. logVisual->updateWithLock(visualKey, [&](IVisualLogBuilder & logBuilder)
  482. {
  483. for(auto & tile : pathNodes)
  484. {
  485. for(auto & node : tile.second)
  486. {
  487. if(!node.previous.valid())
  488. continue;
  489. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  490. {
  491. logAi->trace(
  492. "%s -> %s: %f !%d",
  493. node.previous.coord.toString(),
  494. tile.first.toString(),
  495. node.cost,
  496. node.danger);
  497. }
  498. logBuilder.addLine(node.previous.coord, tile.first);
  499. }
  500. }
  501. });
  502. }
  503. bool GraphPathNode::tryUpdate(const GraphPathNodePointer & pos, const GraphPathNode & prev, const ObjectLink & link)
  504. {
  505. auto newCost = prev.cost + link.cost;
  506. if(newCost < cost)
  507. {
  508. previous = pos;
  509. danger = prev.danger + link.danger;
  510. cost = newCost;
  511. return true;
  512. }
  513. return false;
  514. }
  515. void GraphPaths::addChainInfo(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const
  516. {
  517. auto nodes = pathNodes.find(tile);
  518. if(nodes == pathNodes.end())
  519. return;
  520. for(auto & node : nodes->second)
  521. {
  522. if(!node.reachable())
  523. continue;
  524. std::vector<GraphPathNodePointer> tilesToPass;
  525. uint64_t danger = node.danger;
  526. float cost = node.cost;
  527. bool allowBattle = false;
  528. auto current = GraphPathNodePointer(nodes->first, node.nodeType);
  529. while(true)
  530. {
  531. auto currentTile = pathNodes.find(current.coord);
  532. if(currentTile == pathNodes.end())
  533. break;
  534. auto currentNode = currentTile->second[current.nodeType];
  535. if(!currentNode.previous.valid())
  536. break;
  537. allowBattle = allowBattle || currentNode.nodeType == GrapthPathNodeType::BATTLE;
  538. vstd::amax(danger, currentNode.danger);
  539. vstd::amax(cost, currentNode.cost);
  540. tilesToPass.push_back(current);
  541. if(currentNode.cost < 2.0f)
  542. break;
  543. current = currentNode.previous;
  544. }
  545. if(tilesToPass.empty())
  546. continue;
  547. auto entryPaths = ai->pathfinder->getPathInfo(tilesToPass.back().coord);
  548. for(auto & path : entryPaths)
  549. {
  550. if(path.targetHero != hero)
  551. continue;
  552. for(auto graphTile = tilesToPass.rbegin(); graphTile != tilesToPass.rend(); graphTile++)
  553. {
  554. AIPathNodeInfo n;
  555. n.coord = graphTile->coord;
  556. n.cost = cost;
  557. n.turns = static_cast<ui8>(cost) + 1; // just in case lets select worst scenario
  558. n.danger = danger;
  559. n.targetHero = hero;
  560. n.parentIndex = -1;
  561. n.specialAction = getNode(*graphTile).specialAction;
  562. for(auto & node : path.nodes)
  563. {
  564. node.parentIndex++;
  565. }
  566. path.nodes.insert(path.nodes.begin(), n);
  567. }
  568. path.armyLoss += ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), danger);
  569. path.targetObjectDanger = ai->pathfinder->getStorage()->evaluateDanger(tile, path.targetHero, !allowBattle);
  570. path.targetObjectArmyLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  571. paths.push_back(path);
  572. }
  573. }
  574. }
  575. void GraphPaths::quickAddChainInfoWithBlocker(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const
  576. {
  577. auto nodes = pathNodes.find(tile);
  578. if(nodes == pathNodes.end())
  579. return;
  580. for(auto & targetNode : nodes->second)
  581. {
  582. if(!targetNode.reachable())
  583. continue;
  584. std::vector<GraphPathNodePointer> tilesToPass;
  585. uint64_t danger = targetNode.danger;
  586. float cost = targetNode.cost;
  587. bool allowBattle = false;
  588. auto current = GraphPathNodePointer(nodes->first, targetNode.nodeType);
  589. while(true)
  590. {
  591. auto currentTile = pathNodes.find(current.coord);
  592. if(currentTile == pathNodes.end())
  593. break;
  594. auto currentNode = currentTile->second[current.nodeType];
  595. allowBattle = allowBattle || currentNode.nodeType == GrapthPathNodeType::BATTLE;
  596. vstd::amax(danger, currentNode.danger);
  597. vstd::amax(cost, currentNode.cost);
  598. tilesToPass.push_back(current);
  599. if(currentNode.cost < 2.0f)
  600. break;
  601. current = currentNode.previous;
  602. }
  603. if(tilesToPass.empty())
  604. continue;
  605. auto entryPaths = ai->pathfinder->getPathInfo(tilesToPass.back().coord);
  606. for(auto & entryPath : entryPaths)
  607. {
  608. if(entryPath.targetHero != hero)
  609. continue;
  610. auto & path = paths.emplace_back();
  611. path.targetHero = entryPath.targetHero;
  612. path.heroArmy = entryPath.heroArmy;
  613. path.exchangeCount = entryPath.exchangeCount;
  614. path.armyLoss = entryPath.armyLoss + ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), danger);
  615. path.targetObjectDanger = ai->pathfinder->getStorage()->evaluateDanger(tile, path.targetHero, !allowBattle);
  616. path.targetObjectArmyLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  617. AIPathNodeInfo n;
  618. n.targetHero = hero;
  619. n.parentIndex = -1;
  620. // final node
  621. n.coord = tile;
  622. n.cost = targetNode.cost;
  623. n.danger = targetNode.danger;
  624. n.parentIndex = path.nodes.size();
  625. path.nodes.push_back(n);
  626. for(auto entryNode = entryPath.nodes.rbegin(); entryNode != entryPath.nodes.rend(); entryNode++)
  627. {
  628. auto blocker = ai->objectClusterizer->getBlocker(*entryNode);
  629. if(blocker)
  630. {
  631. // blocker node
  632. path.nodes.push_back(*entryNode);
  633. path.nodes.back().parentIndex = path.nodes.size() - 1;
  634. break;
  635. }
  636. }
  637. if(!path.nodes.empty())
  638. continue;
  639. for(auto graphTile = tilesToPass.rbegin(); graphTile != tilesToPass.rend(); graphTile++)
  640. {
  641. auto & node = getNode(*graphTile);
  642. n.coord = graphTile->coord;
  643. n.cost = node.cost;
  644. n.turns = static_cast<ui8>(node.cost);
  645. n.danger = node.danger;
  646. n.specialAction = node.specialAction;
  647. n.parentIndex = path.nodes.size();
  648. auto blocker = ai->objectClusterizer->getBlocker(n);
  649. if(!blocker)
  650. continue;
  651. // blocker node
  652. path.nodes.push_back(n);
  653. break;
  654. }
  655. }
  656. }
  657. }
  658. }