2
0

ObjectGraph.cpp 22 KB

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