ObjectGraph.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  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 <= 2)
  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 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 startingObjIsBoat = (obj1 && obj1->ID == Obj::BOAT) || target->isVirtualBoat(pos1);
  189. if(!startingObjIsBoat)
  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::BOAT ? HeroRole::MAIN : HeroRole::SCOUT;
  260. target->addObject(obj);
  261. auto shipyard = dynamic_cast<const IShipyard *>(obj);
  262. if(shipyard && shipyard->bestLocation().valid())
  263. {
  264. int3 virtualBoat = shipyard->bestLocation();
  265. addJunctionActor(virtualBoat, true);
  266. target->addVirtualBoat(virtualBoat, obj);
  267. }
  268. }
  269. void addJunctionActor(const int3 & visitablePos, bool isVirtualBoat = false)
  270. {
  271. std::lock_guard<std::mutex> lock(syncLock);
  272. auto internalCb = temporaryActorHeroes.front()->cb;
  273. auto objectActor = temporaryActorHeroes.emplace_back(std::make_unique<CGHeroInstance>(internalCb)).get();
  274. CRandomGenerator rng;
  275. objectActor->setOwner(ai->playerID); // lets avoid having multiple colors
  276. objectActor->initHero(rng, static_cast<HeroTypeID>(0));
  277. objectActor->pos = objectActor->convertFromVisitablePos(visitablePos);
  278. objectActor->initObj(rng);
  279. if(isVirtualBoat || ai->cb->getTile(visitablePos)->isWater())
  280. {
  281. objectActor->boat = temporaryBoats.emplace_back(std::make_unique<CGBoat>(objectActor->cb)).get();
  282. }
  283. assert(objectActor->visitablePos() == visitablePos);
  284. actorObjectMap[objectActor] = nullptr;
  285. actors[objectActor] = isVirtualBoat ? HeroRole::MAIN : HeroRole::SCOUT;
  286. target->registerJunction(visitablePos);
  287. }
  288. ConnectionCostInfo getConnectionsCost(std::vector<AIPath> & paths) const
  289. {
  290. std::map<int3, float> costs;
  291. for(auto & path : paths)
  292. {
  293. auto fromPos = path.targetHero->visitablePos();
  294. auto cost = costs.find(fromPos);
  295. if(cost == costs.end())
  296. {
  297. costs.emplace(fromPos, path.movementCost());
  298. }
  299. else
  300. {
  301. if(path.movementCost() < cost->second)
  302. {
  303. costs[fromPos] = path.movementCost();
  304. }
  305. }
  306. }
  307. ConnectionCostInfo result;
  308. for(auto & cost : costs)
  309. {
  310. result.totalCost += cost.second;
  311. result.connectionsCount++;
  312. }
  313. if(result.connectionsCount)
  314. {
  315. result.avg = result.totalCost / result.connectionsCount;
  316. }
  317. return result;
  318. }
  319. };
  320. bool ObjectGraph::tryAddConnection(
  321. const int3 & from,
  322. const int3 & to,
  323. float cost,
  324. uint64_t danger)
  325. {
  326. auto result = nodes[from].connections[to].update(cost, danger);
  327. auto & connection = nodes[from].connections[to];
  328. if(result && isVirtualBoat(to) && !connection.specialAction)
  329. {
  330. connection.specialAction = std::make_shared<AIPathfinding::BuildBoatActionFactory>(virtualBoats[to]);
  331. }
  332. return result;
  333. }
  334. void ObjectGraph::removeConnection(const int3 & from, const int3 & to)
  335. {
  336. nodes[from].connections.erase(to);
  337. }
  338. void ObjectGraph::updateGraph(const Nullkiller * ai)
  339. {
  340. auto cb = ai->cb;
  341. ObjectGraphCalculator calculator(this, ai);
  342. calculator.setGraphObjects();
  343. calculator.calculateConnections();
  344. calculator.addMinimalDistanceJunctions();
  345. calculator.calculateConnections();
  346. if(NKAI_GRAPH_TRACE_LEVEL >= 1)
  347. dumpToLog("graph");
  348. }
  349. void ObjectGraph::addObject(const CGObjectInstance * obj)
  350. {
  351. if(!hasNodeAt(obj->visitablePos()))
  352. nodes[obj->visitablePos()].init(obj);
  353. }
  354. void ObjectGraph::addVirtualBoat(const int3 & pos, const CGObjectInstance * shipyard)
  355. {
  356. if(!isVirtualBoat(pos))
  357. {
  358. virtualBoats[pos] = shipyard->id;
  359. }
  360. }
  361. void ObjectGraph::registerJunction(const int3 & pos)
  362. {
  363. if(!hasNodeAt(pos))
  364. nodes[pos].initJunction();
  365. }
  366. void ObjectGraph::removeObject(const CGObjectInstance * obj)
  367. {
  368. nodes[obj->visitablePos()].objectExists = false;
  369. if(obj->ID == Obj::BOAT && !isVirtualBoat(obj->visitablePos()))
  370. {
  371. vstd::erase_if(nodes[obj->visitablePos()].connections, [&](const std::pair<int3, ObjectLink> & link) -> bool
  372. {
  373. auto tile = cb->getTile(link.first, false);
  374. return tile && tile->isWater();
  375. });
  376. }
  377. }
  378. void ObjectGraph::connectHeroes(const Nullkiller * ai)
  379. {
  380. for(auto obj : ai->memory->visitableObjs)
  381. {
  382. if(obj && obj->ID == Obj::HERO)
  383. {
  384. addObject(obj);
  385. }
  386. }
  387. for(auto & node : nodes)
  388. {
  389. auto pos = node.first;
  390. auto paths = ai->pathfinder->getPathInfo(pos);
  391. for(AIPath & path : paths)
  392. {
  393. if(path.getFirstBlockedAction())
  394. continue;
  395. auto heroPos = path.targetHero->visitablePos();
  396. nodes[pos].connections[heroPos].update(
  397. path.movementCost(),
  398. path.getPathDanger());
  399. nodes[heroPos].connections[pos].update(
  400. path.movementCost(),
  401. path.getPathDanger());
  402. }
  403. }
  404. }
  405. void ObjectGraph::dumpToLog(std::string visualKey) const
  406. {
  407. logVisual->updateWithLock(visualKey, [&](IVisualLogBuilder & logBuilder)
  408. {
  409. for(auto & tile : nodes)
  410. {
  411. for(auto & node : tile.second.connections)
  412. {
  413. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  414. {
  415. logAi->trace(
  416. "%s -> %s: %f !%d",
  417. node.first.toString(),
  418. tile.first.toString(),
  419. node.second.cost,
  420. node.second.danger);
  421. }
  422. logBuilder.addLine(tile.first, node.first);
  423. }
  424. }
  425. });
  426. }
  427. bool GraphNodeComparer::operator()(const GraphPathNodePointer & lhs, const GraphPathNodePointer & rhs) const
  428. {
  429. return pathNodes.at(lhs.coord)[lhs.nodeType].cost > pathNodes.at(rhs.coord)[rhs.nodeType].cost;
  430. }
  431. GraphPaths::GraphPaths()
  432. : visualKey(""), graph(), pathNodes()
  433. {
  434. }
  435. std::shared_ptr<SpecialAction> getCompositeAction(
  436. const Nullkiller * ai,
  437. std::shared_ptr<ISpecialActionFactory> linkActionFactory,
  438. std::shared_ptr<SpecialAction> transitionAction)
  439. {
  440. if(!linkActionFactory)
  441. return transitionAction;
  442. auto linkAction = linkActionFactory->create(ai);
  443. if(!transitionAction)
  444. return linkAction;
  445. std::vector<std::shared_ptr<const SpecialAction>> actionsArray = {
  446. transitionAction,
  447. linkAction
  448. };
  449. return std::make_shared<CompositeAction>(actionsArray);
  450. }
  451. void GraphPaths::calculatePaths(const CGHeroInstance * targetHero, const Nullkiller * ai, uint8_t scanDepth)
  452. {
  453. graph.copyFrom(*ai->baseGraph);
  454. graph.connectHeroes(ai);
  455. visualKey = std::to_string(ai->playerID) + ":" + targetHero->getNameTranslated();
  456. pathNodes.clear();
  457. GraphNodeComparer cmp(pathNodes);
  458. GraphPathNode::TFibHeap pq(cmp);
  459. pathNodes[targetHero->visitablePos()][GrapthPathNodeType::NORMAL].cost = 0;
  460. pq.emplace(GraphPathNodePointer(targetHero->visitablePos(), GrapthPathNodeType::NORMAL));
  461. while(!pq.empty())
  462. {
  463. GraphPathNodePointer pos = pq.top();
  464. pq.pop();
  465. auto & node = getOrCreateNode(pos);
  466. std::shared_ptr<SpecialAction> transitionAction;
  467. if(node.obj)
  468. {
  469. if(node.obj->ID == Obj::QUEST_GUARD
  470. || node.obj->ID == Obj::BORDERGUARD
  471. || node.obj->ID == Obj::BORDER_GATE)
  472. {
  473. auto questObj = dynamic_cast<const IQuestObject *>(node.obj);
  474. auto questInfo = QuestInfo(questObj->quest, node.obj, pos.coord);
  475. if(node.obj->ID == Obj::QUEST_GUARD
  476. && questObj->quest->mission == Rewardable::Limiter{}
  477. && questObj->quest->killTarget == ObjectInstanceID::NONE)
  478. {
  479. continue;
  480. }
  481. auto questAction = std::make_shared<AIPathfinding::QuestAction>(questInfo);
  482. if(!questAction->canAct(ai, targetHero))
  483. {
  484. transitionAction = questAction;
  485. }
  486. }
  487. }
  488. node.isInQueue = false;
  489. graph.iterateConnections(pos.coord, [this, ai, &pos, &node, &transitionAction, &pq, scanDepth](int3 target, const ObjectLink & o)
  490. {
  491. auto compositeAction = getCompositeAction(ai, o.specialAction, transitionAction);
  492. auto targetNodeType = o.danger || compositeAction ? GrapthPathNodeType::BATTLE : pos.nodeType;
  493. auto targetPointer = GraphPathNodePointer(target, targetNodeType);
  494. auto & targetNode = getOrCreateNode(targetPointer);
  495. if(targetNode.tryUpdate(pos, node, o))
  496. {
  497. if(targetNode.cost > scanDepth)
  498. {
  499. return;
  500. }
  501. targetNode.specialAction = compositeAction;
  502. auto targetGraphNode = graph.getNode(target);
  503. if(targetGraphNode.objID.hasValue())
  504. {
  505. targetNode.obj = ai->cb->getObj(targetGraphNode.objID, false);
  506. if(targetNode.obj && targetNode.obj->ID == Obj::HERO)
  507. return;
  508. }
  509. if(targetNode.isInQueue)
  510. {
  511. pq.increase(targetNode.handle);
  512. }
  513. else
  514. {
  515. targetNode.handle = pq.emplace(targetPointer);
  516. targetNode.isInQueue = true;
  517. }
  518. }
  519. });
  520. }
  521. }
  522. void GraphPaths::dumpToLog() const
  523. {
  524. logVisual->updateWithLock(visualKey, [&](IVisualLogBuilder & logBuilder)
  525. {
  526. for(auto & tile : pathNodes)
  527. {
  528. for(auto & node : tile.second)
  529. {
  530. if(!node.previous.valid())
  531. continue;
  532. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  533. {
  534. logAi->trace(
  535. "%s -> %s: %f !%d",
  536. node.previous.coord.toString(),
  537. tile.first.toString(),
  538. node.cost,
  539. node.danger);
  540. }
  541. logBuilder.addLine(node.previous.coord, tile.first);
  542. }
  543. }
  544. });
  545. }
  546. bool GraphPathNode::tryUpdate(const GraphPathNodePointer & pos, const GraphPathNode & prev, const ObjectLink & link)
  547. {
  548. auto newCost = prev.cost + link.cost;
  549. if(newCost < cost)
  550. {
  551. previous = pos;
  552. danger = prev.danger + link.danger;
  553. cost = newCost;
  554. return true;
  555. }
  556. return false;
  557. }
  558. void GraphPaths::addChainInfo(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const
  559. {
  560. auto nodes = pathNodes.find(tile);
  561. if(nodes == pathNodes.end())
  562. return;
  563. for(auto & node : nodes->second)
  564. {
  565. if(!node.reachable())
  566. continue;
  567. std::vector<GraphPathNodePointer> tilesToPass;
  568. uint64_t danger = node.danger;
  569. float cost = node.cost;
  570. bool allowBattle = false;
  571. auto current = GraphPathNodePointer(nodes->first, node.nodeType);
  572. while(true)
  573. {
  574. auto currentTile = pathNodes.find(current.coord);
  575. if(currentTile == pathNodes.end())
  576. break;
  577. auto currentNode = currentTile->second[current.nodeType];
  578. if(!currentNode.previous.valid())
  579. break;
  580. allowBattle = allowBattle || currentNode.nodeType == GrapthPathNodeType::BATTLE;
  581. vstd::amax(danger, currentNode.danger);
  582. vstd::amax(cost, currentNode.cost);
  583. tilesToPass.push_back(current);
  584. if(currentNode.cost < 2.0f)
  585. break;
  586. current = currentNode.previous;
  587. }
  588. if(tilesToPass.empty())
  589. continue;
  590. auto entryPaths = ai->pathfinder->getPathInfo(tilesToPass.back().coord);
  591. for(auto & path : entryPaths)
  592. {
  593. if(path.targetHero != hero)
  594. continue;
  595. for(auto graphTile = tilesToPass.rbegin(); graphTile != tilesToPass.rend(); graphTile++)
  596. {
  597. AIPathNodeInfo n;
  598. n.coord = graphTile->coord;
  599. n.cost = cost;
  600. n.turns = static_cast<ui8>(cost) + 1; // just in case lets select worst scenario
  601. n.danger = danger;
  602. n.targetHero = hero;
  603. n.parentIndex = -1;
  604. n.specialAction = getNode(*graphTile).specialAction;
  605. if(n.specialAction)
  606. {
  607. n.actionIsBlocked = !n.specialAction->canAct(ai, n);
  608. }
  609. for(auto & node : path.nodes)
  610. {
  611. node.parentIndex++;
  612. }
  613. path.nodes.insert(path.nodes.begin(), n);
  614. }
  615. path.armyLoss += ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), danger);
  616. path.targetObjectDanger = ai->pathfinder->getStorage()->evaluateDanger(tile, path.targetHero, !allowBattle);
  617. path.targetObjectArmyLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  618. paths.push_back(path);
  619. }
  620. }
  621. }
  622. void GraphPaths::quickAddChainInfoWithBlocker(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const
  623. {
  624. auto nodes = pathNodes.find(tile);
  625. if(nodes == pathNodes.end())
  626. return;
  627. for(auto & targetNode : nodes->second)
  628. {
  629. if(!targetNode.reachable())
  630. continue;
  631. std::vector<GraphPathNodePointer> tilesToPass;
  632. uint64_t danger = targetNode.danger;
  633. float cost = targetNode.cost;
  634. bool allowBattle = false;
  635. auto current = GraphPathNodePointer(nodes->first, targetNode.nodeType);
  636. while(true)
  637. {
  638. auto currentTile = pathNodes.find(current.coord);
  639. if(currentTile == pathNodes.end())
  640. break;
  641. auto currentNode = currentTile->second[current.nodeType];
  642. allowBattle = allowBattle || currentNode.nodeType == GrapthPathNodeType::BATTLE;
  643. vstd::amax(danger, currentNode.danger);
  644. vstd::amax(cost, currentNode.cost);
  645. tilesToPass.push_back(current);
  646. if(currentNode.cost < 2.0f)
  647. break;
  648. current = currentNode.previous;
  649. }
  650. if(tilesToPass.empty())
  651. continue;
  652. auto entryPaths = ai->pathfinder->getPathInfo(tilesToPass.back().coord);
  653. for(auto & entryPath : entryPaths)
  654. {
  655. if(entryPath.targetHero != hero)
  656. continue;
  657. auto & path = paths.emplace_back();
  658. path.targetHero = entryPath.targetHero;
  659. path.heroArmy = entryPath.heroArmy;
  660. path.exchangeCount = entryPath.exchangeCount;
  661. path.armyLoss = entryPath.armyLoss + ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), danger);
  662. path.targetObjectDanger = ai->pathfinder->getStorage()->evaluateDanger(tile, path.targetHero, !allowBattle);
  663. path.targetObjectArmyLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  664. AIPathNodeInfo n;
  665. n.targetHero = hero;
  666. n.parentIndex = -1;
  667. // final node
  668. n.coord = tile;
  669. n.cost = targetNode.cost;
  670. n.danger = targetNode.danger;
  671. n.parentIndex = path.nodes.size();
  672. path.nodes.push_back(n);
  673. for(auto entryNode = entryPath.nodes.rbegin(); entryNode != entryPath.nodes.rend(); entryNode++)
  674. {
  675. auto blocker = ai->objectClusterizer->getBlocker(*entryNode);
  676. if(blocker)
  677. {
  678. // blocker node
  679. path.nodes.push_back(*entryNode);
  680. path.nodes.back().parentIndex = path.nodes.size() - 1;
  681. break;
  682. }
  683. }
  684. if(path.nodes.size() > 1)
  685. continue;
  686. for(auto graphTile = tilesToPass.rbegin(); graphTile != tilesToPass.rend(); graphTile++)
  687. {
  688. auto & node = getNode(*graphTile);
  689. n.coord = graphTile->coord;
  690. n.cost = node.cost;
  691. n.turns = static_cast<ui8>(node.cost);
  692. n.danger = node.danger;
  693. n.specialAction = node.specialAction;
  694. n.parentIndex = path.nodes.size();
  695. if(n.specialAction)
  696. {
  697. n.actionIsBlocked = !n.specialAction->canAct(ai, n);
  698. }
  699. auto blocker = ai->objectClusterizer->getBlocker(n);
  700. if(!blocker)
  701. continue;
  702. // blocker node
  703. path.nodes.push_back(n);
  704. break;
  705. }
  706. }
  707. }
  708. }
  709. }