1
0
mirror of https://github.com/vcmi/vcmi.git synced 2024-12-14 10:12:59 +02:00
vcmi/AI/Nullkiller/Pathfinding/AINodeStorage.cpp

1576 lines
39 KiB
C++
Raw Normal View History

2021-05-15 18:22:44 +02:00
/*
* AINodeStorage.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "AINodeStorage.h"
#include "Actions/TownPortalAction.h"
#include "../Goals/Goals.h"
2021-05-16 14:39:38 +02:00
#include "../AIGateway.h"
#include "../Engine/Nullkiller.h"
2021-05-15 18:22:44 +02:00
#include "../../../CCallback.h"
#include "../../../lib/mapping/CMap.h"
#include "../../../lib/mapObjects/MapObjects.h"
#include "../../../lib/pathfinder/CPathfinder.h"
#include "../../../lib/pathfinder/PathfinderUtil.h"
#include "../../../lib/pathfinder/PathfinderOptions.h"
2021-05-15 18:22:44 +02:00
#include "../../../lib/CPlayerState.h"
2022-09-26 20:01:07 +02:00
namespace NKAI
{
2024-03-23 11:44:15 +02:00
std::shared_ptr<boost::multi_array<AIPathNode, 4>> AISharedStorage::shared;
uint32_t AISharedStorage::version = 0;
boost::mutex AISharedStorage::locker;
std::set<int3> committedTiles;
std::set<int3> committedTilesInitial;
const uint64_t FirstActorMask = 1;
2021-05-16 14:08:39 +02:00
const uint64_t MIN_ARMY_STRENGTH_FOR_CHAIN = 5000;
const uint64_t MIN_ARMY_STRENGTH_FOR_NEXT_ACTOR = 1000;
2022-09-06 20:14:22 +02:00
const uint64_t CHAIN_MAX_DEPTH = 4;
2021-05-16 14:08:39 +02:00
const bool DO_NOT_SAVE_TO_COMMITTED_TILES = false;
AISharedStorage::AISharedStorage(int3 sizes)
{
if(!shared){
2024-03-23 11:44:15 +02:00
shared.reset(new boost::multi_array<AIPathNode, 4>(
boost::extents[sizes.z][sizes.x][sizes.y][AIPathfinding::NUM_CHAINS]));
nodes = shared;
2024-03-23 11:44:15 +02:00
foreach_tile_pos([&](const int3 & pos)
{
for(auto i = 0; i < AIPathfinding::NUM_CHAINS; i++)
{
auto & node = get(pos)[i];
node.version = -1;
node.coord = pos;
}
});
}
else
nodes = shared;
}
AISharedStorage::~AISharedStorage()
{
nodes.reset();
if(shared && shared.use_count() == 1)
{
shared.reset();
}
}
void AIPathNode::addSpecialAction(std::shared_ptr<const SpecialAction> action)
{
if(!specialAction)
{
specialAction = action;
}
else
{
auto parts = specialAction->getParts();
if(parts.empty())
{
parts.push_back(specialAction);
}
parts.push_back(action);
specialAction = std::make_shared<CompositeAction>(parts);
}
}
AINodeStorage::AINodeStorage(const Nullkiller * ai, const int3 & Sizes)
: sizes(Sizes), ai(ai), cb(ai->cb.get()), nodes(Sizes)
2021-05-15 18:22:44 +02:00
{
accessibility = std::make_unique<boost::multi_array<EPathAccessibility, 4>>(
2024-03-23 11:44:15 +02:00
boost::extents[sizes.z][sizes.x][sizes.y][EPathfindingLayer::NUM_LAYERS]);
dangerEvaluator.reset(new FuzzyHelper(ai));
2021-05-15 18:22:44 +02:00
}
AINodeStorage::~AINodeStorage() = default;
2021-05-15 18:22:49 +02:00
void AINodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs)
2021-05-15 18:22:44 +02:00
{
if(heroChainPass != EHeroChainPass::INITIAL)
2021-05-15 20:01:48 +02:00
return;
2021-05-15 18:22:44 +02:00
2024-03-23 11:44:15 +02:00
AISharedStorage::version++;
2021-05-15 20:01:48 +02:00
//TODO: fix this code duplication with NodeStorage::initialize, problem is to keep `resetTile` inline
const PlayerColor fowPlayer = ai->playerID;
const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(fowPlayer)->fogOfWarMap;
const int3 sizes = gs->getMapSize();
2021-05-15 18:22:44 +02:00
//Each thread gets different x, but an array of y located next to each other in memory
2024-03-24 13:16:46 +02:00
tbb::parallel_for(tbb::blocked_range<size_t>(0, sizes.x), [&](const tbb::blocked_range<size_t>& r)
2021-05-15 18:22:44 +02:00
{
int3 pos;
for(pos.z = 0; pos.z < sizes.z; ++pos.z)
2021-05-15 18:22:44 +02:00
{
const bool useFlying = options.useFlying;
const bool useWaterWalking = options.useWaterWalking;
const PlayerColor player = playerID;
for(pos.x = r.begin(); pos.x != r.end(); ++pos.x)
2021-05-15 18:22:44 +02:00
{
for(pos.y = 0; pos.y < sizes.y; ++pos.y)
2021-05-15 18:22:44 +02:00
{
2022-09-25 08:07:22 +02:00
const TerrainTile & tile = gs->map->getTile(pos);
if (!tile.terType->isPassable())
continue;
2022-09-25 08:07:22 +02:00
if (tile.terType->isWater())
{
resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
if (useFlying)
resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
if (useWaterWalking)
resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
}
else
{
resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
if (useFlying)
resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
}
2021-05-15 18:22:44 +02:00
}
}
}
});
2021-05-15 18:22:44 +02:00
}
2021-05-15 18:23:01 +02:00
void AINodeStorage::clear()
2021-05-15 18:22:49 +02:00
{
actors.clear();
committedTiles.clear();
heroChainPass = EHeroChainPass::INITIAL;
heroChainTurn = 0;
heroChainMaxTurns = 1;
2021-05-16 14:01:34 +02:00
turnDistanceLimit[HeroRole::MAIN] = 255;
turnDistanceLimit[HeroRole::SCOUT] = 255;
2021-05-15 18:22:49 +02:00
}
2023-04-16 19:42:56 +02:00
std::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
2021-05-15 19:59:43 +02:00
const int3 & pos,
const EPathfindingLayer layer,
const ChainActor * actor)
2021-05-15 18:22:44 +02:00
{
int bucketIndex = ((uintptr_t)actor + static_cast<uint32_t>(layer)) % AIPathfinding::BUCKET_COUNT;
2022-09-06 20:14:22 +02:00
int bucketOffset = bucketIndex * AIPathfinding::BUCKET_SIZE;
2024-03-23 11:44:15 +02:00
auto chains = nodes.get(pos);
2024-03-23 11:44:15 +02:00
if(blocked(pos, layer))
{
2023-04-16 19:42:56 +02:00
return std::nullopt;
}
2022-09-06 20:14:22 +02:00
for(auto i = AIPathfinding::BUCKET_SIZE - 1; i >= 0; i--)
2021-05-15 18:22:44 +02:00
{
AIPathNode & node = chains[i + bucketOffset];
2024-03-23 11:44:15 +02:00
if(node.version != AISharedStorage::version)
2021-05-15 18:22:44 +02:00
{
2024-03-23 11:44:15 +02:00
node.reset(layer, getAccessibility(pos, layer));
node.version = AISharedStorage::version;
node.actor = actor;
2021-05-15 18:22:44 +02:00
return &node;
}
2024-03-23 11:44:15 +02:00
if(node.actor == actor && node.layer == layer)
2021-05-15 18:22:44 +02:00
{
return &node;
}
}
2023-04-16 19:42:56 +02:00
return std::nullopt;
2021-05-15 18:22:44 +02:00
}
2021-05-15 18:22:49 +02:00
std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
2021-05-15 18:22:44 +02:00
{
2021-05-15 20:01:48 +02:00
if(heroChainPass)
2022-09-06 20:14:22 +02:00
{
if(heroChainTurn == 0)
calculateTownPortalTeleportations(heroChain);
2021-05-16 13:07:54 +02:00
2021-05-15 20:01:48 +02:00
return heroChain;
2021-05-16 13:07:54 +02:00
}
2021-05-15 20:01:48 +02:00
2021-05-15 18:22:49 +02:00
std::vector<CGPathNode *> initialNodes;
for(auto actorPtr : actors)
{
2021-05-15 19:59:43 +02:00
ChainActor * actor = actorPtr.get();
2021-05-15 18:22:44 +02:00
auto allocated = getOrCreateNode(actor->initialPosition, actor->layer, actor);
if(!allocated)
2021-05-16 13:58:56 +02:00
continue;
2023-04-16 19:42:56 +02:00
AIPathNode * initialNode = allocated.value();
2021-05-16 13:58:56 +02:00
initialNode->pq = nullptr;
2021-05-15 18:22:49 +02:00
initialNode->turns = actor->initialTurn;
initialNode->moveRemains = actor->initialMovement;
initialNode->danger = 0;
initialNode->setCost(actor->initialTurn);
initialNode->action = EPathNodeAction::NORMAL;
2021-05-15 18:22:44 +02:00
2021-05-15 18:22:49 +02:00
if(actor->isMovable)
{
initialNodes.push_back(initialNode);
}
else
{
initialNode->locked = true;
}
}
2022-09-06 20:14:22 +02:00
if(heroChainTurn == 0)
calculateTownPortalTeleportations(initialNodes);
2021-05-16 13:07:54 +02:00
2021-05-15 18:22:49 +02:00
return initialNodes;
2021-05-15 18:22:44 +02:00
}
void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
{
const AIPathNode * srcNode = getAINode(source.node);
updateAINode(destination.node, [&](AIPathNode * dstNode)
{
2021-05-15 20:01:48 +02:00
commit(dstNode, srcNode, destination.action, destination.turn, destination.movementLeft, destination.cost);
2021-05-15 18:22:44 +02:00
2021-05-15 20:54:28 +02:00
if(srcNode->specialAction || srcNode->chainOther)
{
// there is some action on source tile which should be performed before we can bypass it
destination.node->theNodeBefore = source.node;
}
2021-05-15 18:22:49 +02:00
if(dstNode->specialAction && dstNode->actor)
2021-05-15 18:22:44 +02:00
{
2021-05-15 18:22:49 +02:00
dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
2021-05-15 18:22:44 +02:00
}
});
}
2021-05-15 20:01:48 +02:00
void AINodeStorage::commit(
AIPathNode * destination,
const AIPathNode * source,
EPathNodeAction action,
2021-05-15 20:01:48 +02:00
int turn,
int movementLeft,
float cost,
bool saveToCommitted) const
2021-05-15 20:01:48 +02:00
{
2021-05-15 20:04:11 +02:00
destination->action = action;
destination->setCost(cost);
2021-05-15 20:01:48 +02:00
destination->moveRemains = movementLeft;
destination->turns = turn;
destination->armyLoss = source->armyLoss;
destination->manaCost = source->manaCost;
destination->danger = source->danger;
destination->theNodeBefore = source->theNodeBefore;
2021-05-15 20:04:48 +02:00
destination->chainOther = nullptr;
2021-05-16 13:09:49 +02:00
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
2021-05-16 13:09:49 +02:00
logAi->trace(
"Committed %s -> %s, layer: %d, cost: %f, turn: %s, mp: %d, hero: %s, mask: %x, army: %lld",
2021-05-16 13:09:49 +02:00
source->coord.toString(),
destination->coord.toString(),
2023-09-24 12:07:42 +02:00
destination->layer,
2021-05-16 13:58:56 +02:00
destination->getCost(),
2021-05-16 13:09:49 +02:00
std::to_string(destination->turns),
destination->moveRemains,
destination->actor->toString(),
destination->actor->chainMask,
destination->actor->armyValue);
#endif
if(saveToCommitted && destination->turns <= heroChainTurn)
{
committedTiles.insert(destination->coord);
}
if(destination->turns == source->turns)
{
destination->dayFlags = source->dayFlags;
}
2021-05-15 20:01:48 +02:00
}
2024-03-23 11:44:15 +02:00
void AINodeStorage::calculateNeighbours(
std::vector<CGPathNode *> & result,
2021-05-15 18:22:44 +02:00
const PathNodeInfo & source,
2024-03-23 11:44:15 +02:00
EPathfindingLayer layer,
2021-05-15 18:22:44 +02:00
const PathfinderConfig * pathfinderConfig,
const CPathfinderHelper * pathfinderHelper)
{
NeighbourTilesVector accessibleNeighbourTiles;
2024-03-23 11:44:15 +02:00
result.clear();
pathfinderHelper->calculateNeighbourTiles(accessibleNeighbourTiles, source);
2021-05-15 18:22:44 +02:00
const AIPathNode * srcNode = getAINode(source.node);
for(auto & neighbour : accessibleNeighbourTiles)
{
if(getAccessibility(neighbour, layer) == EPathAccessibility::NOT_SET)
{
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
logAi->trace(
"Node %s rejected for %s, layer %d because of inaccessibility",
neighbour.toString(),
source.coord.toString(),
static_cast<int32_t>(layer));
#endif
continue;
}
2024-03-23 11:44:15 +02:00
auto nextNode = getOrCreateNode(neighbour, layer, srcNode->actor);
2021-05-15 18:22:44 +02:00
if(!nextNode)
{
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
logAi->trace(
"Failed to allocate node at %s[%d]",
neighbour.toString(),
static_cast<int32_t>(layer));
#endif
2024-03-23 11:44:15 +02:00
continue;
}
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
logAi->trace(
"Node %s added to neighbors of %s, layer %d",
neighbour.toString(),
source.coord.toString(),
static_cast<int32_t>(layer));
#endif
2021-05-15 18:22:44 +02:00
2024-03-23 11:44:15 +02:00
result.push_back(nextNode.value());
2021-05-15 18:22:44 +02:00
}
}
constexpr std::array phisycalLayers = {EPathfindingLayer::LAND, EPathfindingLayer::SAIL};
bool AINodeStorage::increaseHeroChainTurnLimit()
{
if(heroChainTurn >= heroChainMaxTurns)
return false;
heroChainTurn++;
committedTiles.clear();
for(auto layer : phisycalLayers)
{
foreach_tile_pos([&](const int3 & pos)
{
2024-03-23 11:44:15 +02:00
iterateValidNodesUntil(pos, layer, [&](AIPathNode & node)
{
if(node.turns <= heroChainTurn && node.action != EPathNodeAction::UNKNOWN)
{
committedTiles.insert(pos);
2024-03-23 11:44:15 +02:00
return true;
}
2024-03-23 11:44:15 +02:00
return false;
});
});
}
return true;
}
bool AINodeStorage::calculateHeroChainFinal()
{
heroChainPass = EHeroChainPass::FINAL;
heroChain.resize(0);
for(auto layer : phisycalLayers)
{
foreach_tile_pos([&](const int3 & pos)
{
2024-03-23 11:44:15 +02:00
iterateValidNodes(pos, layer, [&](AIPathNode & node)
{
if(node.turns > heroChainTurn
&& !node.locked
&& node.action != EPathNodeAction::UNKNOWN
&& node.actor->actorExchangeCount > 1
2024-03-23 11:44:15 +02:00
&& !hasBetterChain(&node, node))
{
heroChain.push_back(&node);
}
2024-03-23 11:44:15 +02:00
});
});
}
return heroChain.size();
}
struct DelayedWork
2021-05-15 20:01:48 +02:00
{
AIPathNode * carrier;
AIPathNode * other;
DelayedWork()
{
}
DelayedWork(AIPathNode * carrier, AIPathNode * other) : carrier(carrier), other(other)
{
}
};
2021-05-15 20:01:48 +02:00
class HeroChainCalculationTask
{
private:
AINodeStorage & storage;
2021-05-15 20:54:58 +02:00
std::vector<AIPathNode *> existingChains;
std::vector<ExchangeCandidate> newChains;
uint64_t chainMask;
int heroChainTurn;
std::vector<CGPathNode *> heroChain;
const std::vector<int3> & tiles;
std::vector<DelayedWork> delayedWork;
public:
HeroChainCalculationTask(
2024-03-25 17:05:24 +02:00
AINodeStorage & storage, const std::vector<int3> & tiles, uint64_t chainMask, int heroChainTurn)
:existingChains(), newChains(), delayedWork(), storage(storage), chainMask(chainMask), heroChainTurn(heroChainTurn), heroChain(), tiles(tiles)
{
2022-09-06 20:14:22 +02:00
existingChains.reserve(AIPathfinding::NUM_CHAINS);
newChains.reserve(AIPathfinding::NUM_CHAINS);
}
2021-05-15 20:04:48 +02:00
2024-03-24 13:16:46 +02:00
void execute(const tbb::blocked_range<size_t>& r)
{
2022-12-09 14:16:23 +02:00
std::random_device randomDevice;
std::mt19937 randomEngine(randomDevice());
for(int i = r.begin(); i != r.end(); i++)
{
auto & pos = tiles[i];
2021-05-15 20:01:48 +02:00
for(auto layer : phisycalLayers)
{
2024-03-23 11:44:15 +02:00
existingChains.clear();
2024-03-23 11:44:15 +02:00
storage.iterateValidNodes(pos, layer, [this](AIPathNode & node)
{
if(node.turns <= heroChainTurn && node.action != EPathNodeAction::UNKNOWN)
existingChains.push_back(&node);
});
if(existingChains.empty())
continue;
2021-05-15 20:04:48 +02:00
newChains.clear();
2021-05-15 20:04:48 +02:00
2022-12-09 14:16:23 +02:00
std::shuffle(existingChains.begin(), existingChains.end(), randomEngine);
for(AIPathNode * node : existingChains)
{
if(node->actor->isMovable)
{
calculateHeroChain(node, existingChains, newChains);
}
}
2021-05-15 20:54:58 +02:00
for(auto delayed = delayedWork.begin(); delayed != delayedWork.end();)
{
auto newActor = delayed->carrier->actor->tryExchangeNoLock(delayed->other->actor);
if(!newActor.lockAcquired) continue;
if(newActor.actor)
{
newChains.push_back(calculateExchange(newActor.actor, delayed->carrier, delayed->other));
}
delayed++;
}
delayedWork.clear();
cleanupInefectiveChains(newChains);
addHeroChain(newChains);
}
}
}
2021-05-15 20:01:48 +02:00
void calculateHeroChain(
AIPathNode * srcNode,
const std::vector<AIPathNode *> & variants,
std::vector<ExchangeCandidate> & result);
void calculateHeroChain(
AIPathNode * carrier,
AIPathNode * other,
std::vector<ExchangeCandidate> & result);
void cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const;
void addHeroChain(const std::vector<ExchangeCandidate> & result);
ExchangeCandidate calculateExchange(
ChainActor * exchangeActor,
AIPathNode * carrierParentNode,
AIPathNode * otherParentNode) const;
void flushResult(std::vector<CGPathNode *> & result)
{
vstd::concatenate(result, heroChain);
}
};
bool AINodeStorage::calculateHeroChain()
{
2022-12-09 14:16:23 +02:00
std::random_device randomDevice;
std::mt19937 randomEngine(randomDevice());
heroChainPass = EHeroChainPass::CHAIN;
heroChain.clear();
std::vector<int3> data(committedTiles.begin(), committedTiles.end());
if(data.size() > 100)
{
2021-05-16 14:10:35 +02:00
boost::mutex resultMutex;
2022-12-09 14:16:23 +02:00
std::shuffle(data.begin(), data.end(), randomEngine);
2024-03-24 13:16:46 +02:00
tbb::parallel_for(tbb::blocked_range<size_t>(0, data.size()), [&](const tbb::blocked_range<size_t>& r)
{
//auto r = blocked_range<size_t>(0, data.size());
HeroChainCalculationTask task(*this, data, chainMask, heroChainTurn);
task.execute(r);
{
2021-05-16 14:10:35 +02:00
boost::lock_guard<boost::mutex> resultLock(resultMutex);
task.flushResult(heroChain);
}
});
}
else
{
2024-03-24 13:16:46 +02:00
auto r = tbb::blocked_range<size_t>(0, data.size());
HeroChainCalculationTask task(*this, data, chainMask, heroChainTurn);
task.execute(r);
task.flushResult(heroChain);
}
committedTiles.clear();
return !heroChain.empty();
2021-05-15 20:01:48 +02:00
}
bool AINodeStorage::selectFirstActor()
{
if(actors.empty())
return false;
auto strongest = *vstd::maxElementByFun(actors, [](std::shared_ptr<ChainActor> actor) -> uint64_t
{
return actor->armyValue;
});
chainMask = strongest->chainMask;
committedTilesInitial = committedTiles;
return true;
}
bool AINodeStorage::selectNextActor()
{
auto currentActor = std::find_if(actors.begin(), actors.end(), [&](std::shared_ptr<ChainActor> actor)-> bool
{
return actor->chainMask == chainMask;
});
auto nextActor = actors.end();
for(auto actor = actors.begin(); actor != actors.end(); actor++)
{
if(actor->get()->armyValue > currentActor->get()->armyValue
|| (actor->get()->armyValue == currentActor->get()->armyValue && actor <= currentActor))
{
continue;
}
if(nextActor == actors.end()
|| actor->get()->armyValue > nextActor->get()->armyValue)
{
nextActor = actor;
}
}
if(nextActor != actors.end())
{
2021-05-16 14:08:39 +02:00
if(nextActor->get()->armyValue < MIN_ARMY_STRENGTH_FOR_NEXT_ACTOR)
return false;
chainMask = nextActor->get()->chainMask;
committedTiles = committedTilesInitial;
return true;
}
return false;
}
uint64_t AINodeStorage::evaluateArmyLoss(const CGHeroInstance * hero, uint64_t armyValue, uint64_t danger) const
{
float fightingStrength = ai->heroManager->getFightingStrengthCached(hero);
double ratio = (double)danger / (armyValue * fightingStrength);
return (uint64_t)(armyValue * ratio * ratio);
}
void HeroChainCalculationTask::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
2021-05-15 20:54:58 +02:00
{
vstd::erase_if(result, [&](const ExchangeCandidate & chainInfo) -> bool
2021-05-15 20:54:58 +02:00
{
2024-03-23 11:44:15 +02:00
auto isNotEffective = storage.hasBetterChain(chainInfo.carrierParent, chainInfo)
|| storage.hasBetterChain(chainInfo.carrierParent, chainInfo, result);
2021-05-15 20:54:58 +02:00
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
if(isNotEffective)
{
logAi->trace(
"Skip exchange %s[%x] -> %s[%x] at %s is inefficient",
chainInfo.otherParent->actor->toString(),
chainInfo.otherParent->actor->chainMask,
chainInfo.carrierParent->actor->toString(),
chainInfo.carrierParent->actor->chainMask,
chainInfo.carrierParent->coord.toString());
}
#endif
return isNotEffective;
2021-05-15 20:54:58 +02:00
});
}
void HeroChainCalculationTask::calculateHeroChain(
2021-05-15 20:54:58 +02:00
AIPathNode * srcNode,
const std::vector<AIPathNode *> & variants,
std::vector<ExchangeCandidate> & result)
2021-05-15 19:59:43 +02:00
{
2021-05-15 20:04:48 +02:00
for(AIPathNode * node : variants)
2021-05-15 19:59:43 +02:00
{
2024-03-23 11:44:15 +02:00
if(node == srcNode || !node->actor || node->version != AISharedStorage::version)
continue;
if((node->actor->chainMask & chainMask) == 0 && (srcNode->actor->chainMask & chainMask) == 0)
continue;
2022-09-06 20:14:22 +02:00
if(node->actor->actorExchangeCount + srcNode->actor->actorExchangeCount > CHAIN_MAX_DEPTH)
continue;
if(node->action == EPathNodeAction::BATTLE
|| node->action == EPathNodeAction::TELEPORT_BATTLE
|| node->action == EPathNodeAction::TELEPORT_NORMAL
|| node->action == EPathNodeAction::TELEPORT_BLOCKING_VISIT)
{
continue;
}
if(node->turns > heroChainTurn
|| (node->action == EPathNodeAction::UNKNOWN && node->actor->hero)
2021-05-15 20:56:08 +02:00
|| (node->actor->chainMask & srcNode->actor->chainMask) != 0)
2021-05-15 19:59:43 +02:00
{
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
logAi->trace(
"Skip exchange %s[%x] -> %s[%x] at %s because of %s",
node->actor->toString(),
node->actor->chainMask,
srcNode->actor->toString(),
srcNode->actor->chainMask,
srcNode->coord.toString(),
(node->turns > heroChainTurn
? "turn limit"
: (node->action == EPathNodeAction::UNKNOWN && node->actor->hero)
? "action unknown"
: "chain mask"));
#endif
2021-05-15 19:59:43 +02:00
continue;
}
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
2021-05-15 20:04:48 +02:00
logAi->trace(
2021-05-16 13:09:49 +02:00
"Thy exchange %s[%x] -> %s[%x] at %s",
2021-05-15 20:54:28 +02:00
node->actor->toString(),
2021-05-15 20:04:48 +02:00
node->actor->chainMask,
2021-05-15 20:54:28 +02:00
srcNode->actor->toString(),
2021-05-15 20:04:48 +02:00
srcNode->actor->chainMask,
srcNode->coord.toString());
#endif
2021-05-15 20:54:58 +02:00
calculateHeroChain(srcNode, node, result);
2021-05-15 19:59:43 +02:00
}
}
void HeroChainCalculationTask::calculateHeroChain(
2021-05-15 20:54:58 +02:00
AIPathNode * carrier,
AIPathNode * other,
std::vector<ExchangeCandidate> & result)
2021-05-15 20:56:08 +02:00
{
if(carrier->armyLoss < carrier->actor->armyValue
&& (carrier->action != EPathNodeAction::BATTLE || (carrier->actor->allowBattle && carrier->specialAction))
&& carrier->action != EPathNodeAction::BLOCKING_VISIT
&& (other->armyLoss == 0 || other->armyLoss < other->actor->armyValue))
2021-05-15 19:59:43 +02:00
{
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
2021-05-15 20:04:48 +02:00
logAi->trace(
2021-05-16 13:09:49 +02:00
"Exchange allowed %s[%x] -> %s[%x] at %s",
2021-05-15 20:54:28 +02:00
other->actor->toString(),
2021-05-15 20:04:48 +02:00
other->actor->chainMask,
2021-05-15 20:54:28 +02:00
carrier->actor->toString(),
2021-05-15 20:04:48 +02:00
carrier->actor->chainMask,
carrier->coord.toString());
#endif
if(other->actor->isMovable)
2021-05-15 20:04:48 +02:00
{
2021-05-16 13:22:37 +02:00
bool hasLessMp = carrier->turns > other->turns || (carrier->turns == other->turns && carrier->moveRemains < other->moveRemains);
bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
if(hasLessMp && hasLessExperience)
{
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
logAi->trace("Exchange at %s is inefficient. Blocked.", carrier->coord.toString());
2021-05-15 20:04:48 +02:00
#endif
return;
}
2021-05-15 20:04:48 +02:00
}
2021-05-15 19:59:43 +02:00
auto newActor = carrier->actor->tryExchangeNoLock(other->actor);
2021-05-15 20:54:58 +02:00
if(!newActor.lockAcquired) delayedWork.push_back(DelayedWork(carrier, other));
if(newActor.actor) result.push_back(calculateExchange(newActor.actor, carrier, other));
2021-05-15 20:54:58 +02:00
}
}
void HeroChainCalculationTask::addHeroChain(const std::vector<ExchangeCandidate> & result)
2021-05-15 20:54:58 +02:00
{
for(const ExchangeCandidate & chainInfo : result)
{
auto carrier = chainInfo.carrierParent;
auto newActor = chainInfo.actor;
auto other = chainInfo.otherParent;
auto chainNodeOptional = storage.getOrCreateNode(carrier->coord, carrier->layer, newActor);
2021-05-15 19:59:43 +02:00
if(!chainNodeOptional)
2021-05-15 20:04:48 +02:00
{
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
2021-05-15 20:04:48 +02:00
logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
#endif
2021-05-15 20:54:58 +02:00
continue;
2021-05-15 20:04:48 +02:00
}
2021-05-15 19:59:43 +02:00
2023-04-16 19:42:56 +02:00
auto exchangeNode = chainNodeOptional.value();
2021-05-15 19:59:43 +02:00
if(exchangeNode->action != EPathNodeAction::UNKNOWN)
2021-05-15 20:04:48 +02:00
{
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
logAi->trace(
"Skip exchange %s[%x] -> %s[%x] at %s because node is in use",
other->actor->toString(),
other->actor->chainMask,
carrier->actor->toString(),
carrier->actor->chainMask,
carrier->coord.toString());
2021-05-15 20:01:48 +02:00
#endif
2021-05-15 20:54:58 +02:00
continue;
2021-05-15 20:04:48 +02:00
}
2021-05-15 20:01:48 +02:00
if(exchangeNode->turns != 0xFF && exchangeNode->getCost() < chainInfo.getCost())
2021-05-15 20:04:48 +02:00
{
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
2021-05-15 20:04:48 +02:00
logAi->trace(
"Skip exchange %s[%x] -> %s[%x] at %s because not effective enough. %f < %f",
other->actor->toString(),
other->actor->chainMask,
carrier->actor->toString(),
carrier->actor->chainMask,
carrier->coord.toString(),
exchangeNode->getCost(),
2021-05-16 13:58:56 +02:00
chainInfo.getCost());
2021-05-15 20:04:48 +02:00
#endif
2021-05-15 20:54:58 +02:00
continue;
2021-05-15 20:04:48 +02:00
}
2021-05-15 20:54:58 +02:00
storage.commit(
exchangeNode,
carrier,
carrier->action,
chainInfo.turns,
chainInfo.moveRemains,
chainInfo.getCost(),
DO_NOT_SAVE_TO_COMMITTED_TILES);
2021-05-15 20:54:58 +02:00
2021-05-16 13:07:54 +02:00
if(carrier->specialAction || carrier->chainOther)
{
// there is some action on source tile which should be performed before we can bypass it
exchangeNode->theNodeBefore = carrier;
}
if(exchangeNode->actor->actorAction)
{
exchangeNode->theNodeBefore = carrier;
exchangeNode->addSpecialAction(exchangeNode->actor->actorAction);
}
2021-05-15 20:54:58 +02:00
exchangeNode->chainOther = other;
exchangeNode->armyLoss = chainInfo.armyLoss;
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
2021-05-15 20:54:58 +02:00
logAi->trace(
2021-05-16 13:09:49 +02:00
"Chain accepted at %s %s -> %s, mask %x, cost %f, turn: %s, mp: %d, army %i",
2021-05-15 20:54:58 +02:00
exchangeNode->coord.toString(),
other->actor->toString(),
exchangeNode->actor->toString(),
exchangeNode->actor->chainMask,
2021-05-16 13:58:56 +02:00
exchangeNode->getCost(),
2021-05-16 13:09:49 +02:00
std::to_string(exchangeNode->turns),
exchangeNode->moveRemains,
2021-05-15 20:56:08 +02:00
exchangeNode->actor->armyValue);
2021-05-15 20:54:58 +02:00
#endif
heroChain.push_back(exchangeNode);
2021-05-15 20:01:48 +02:00
}
}
ExchangeCandidate HeroChainCalculationTask::calculateExchange(
2021-05-15 20:54:58 +02:00
ChainActor * exchangeActor,
2021-05-15 20:01:48 +02:00
AIPathNode * carrierParentNode,
AIPathNode * otherParentNode) const
{
2021-05-15 20:54:58 +02:00
ExchangeCandidate candidate;
2021-05-15 20:54:58 +02:00
candidate.layer = carrierParentNode->layer;
candidate.coord = carrierParentNode->coord;
candidate.carrierParent = carrierParentNode;
candidate.otherParent = otherParentNode;
candidate.actor = exchangeActor;
candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
candidate.turns = carrierParentNode->turns;
candidate.setCost(carrierParentNode->getCost() + otherParentNode->getCost() / 1000.0);
2021-05-15 20:54:58 +02:00
candidate.moveRemains = carrierParentNode->moveRemains;
2024-02-12 12:31:27 +02:00
candidate.danger = carrierParentNode->danger;
2021-05-15 20:01:48 +02:00
if(carrierParentNode->turns < otherParentNode->turns)
{
int moveRemains = exchangeActor->maxMovePoints(carrierParentNode->layer);
2021-05-15 20:01:48 +02:00
float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
+ carrierParentNode->moveRemains / (float)moveRemains;
2021-05-15 19:59:43 +02:00
2021-05-15 20:54:58 +02:00
candidate.turns = otherParentNode->turns;
candidate.setCost(candidate.getCost() + waitingCost);
2021-05-15 20:54:58 +02:00
candidate.moveRemains = moveRemains;
2021-05-15 19:59:43 +02:00
}
2021-05-15 20:01:48 +02:00
2021-05-15 20:54:58 +02:00
return candidate;
2021-05-15 19:59:43 +02:00
}
2021-05-15 18:22:49 +02:00
const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
{
std::set<const CGHeroInstance *> heroes;
for(auto actor : actors)
{
if(actor->hero)
2021-05-15 18:23:01 +02:00
heroes.insert(actor->hero);
2021-05-15 18:22:49 +02:00
}
return heroes;
}
bool AINodeStorage::isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
{
if(heroChainPass == EHeroChainPass::CHAIN && destination.node->turns > heroChainTurn)
{
return true;
}
auto aiNode = getAINode(destination.node);
2021-05-16 14:01:34 +02:00
if(heroChainPass != EHeroChainPass::CHAIN
&& destination.node->turns > turnDistanceLimit[aiNode->actor->heroRole])
{
2021-05-16 14:01:34 +02:00
return true;
}
return false;
}
void AINodeStorage::setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes)
2021-05-15 18:22:44 +02:00
{
playerID = ai->playerID;
2021-05-15 18:22:49 +02:00
for(auto & hero : heroes)
{
// do not allow our own heroes in garrison to act on map
if(hero.first->getOwner() == ai->playerID
&& hero.first->inTownGarrison
&& (ai->isHeroLocked(hero.first) || ai->heroManager->heroCapReached()))
{
continue;
}
uint64_t mask = FirstActorMask << actors.size();
auto actor = std::make_shared<HeroActor>(hero.first, hero.second, mask, ai);
2021-05-16 12:53:32 +02:00
if(actor->hero->tempOwner != ai->playerID)
2021-05-16 12:53:32 +02:00
{
2023-04-18 16:33:44 +02:00
bool onLand = !actor->hero->boat || actor->hero->boat->layer != EPathfindingLayer::SAIL;
actor->initialMovement = actor->hero->movementPointsLimit(onLand);
2021-05-16 12:53:32 +02:00
}
2021-05-15 18:22:49 +02:00
playerID = actor->hero->tempOwner;
2021-05-16 12:53:32 +02:00
actors.push_back(actor);
}
}
void AINodeStorage::setTownsAndDwellings(
const std::vector<const CGTownInstance *> & towns,
2021-05-15 20:54:28 +02:00
const std::set<const CGObjectInstance *> & visitableObjs)
{
for(auto town : towns)
{
uint64_t mask = FirstActorMask << actors.size();
// TODO: investigate logix of second condition || ai->nullkiller->getHeroLockedReason(town->garrisonHero) != HeroLockedReason::DEFENCE
// check defence imrove
if(!town->garrisonHero)
{
actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
}
}
2021-05-15 20:56:08 +02:00
/*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
auto waitForGrowth = dayOfWeek > 4;*/
for(auto obj: visitableObjs)
{
if(obj->ID == Obj::HILL_FORT)
{
uint64_t mask = FirstActorMask << actors.size();
actors.push_back(std::make_shared<HillFortActor>(obj, mask));
}
/*const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
if(dwelling)
{
uint64_t mask = 1 << actors.size();
auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
if(dwellingActor->creatureSet->getArmyStrength())
{
actors.push_back(dwellingActor);
}
if(waitForGrowth)
{
mask = 1 << actors.size();
dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
if(dwellingActor->creatureSet->getArmyStrength())
{
actors.push_back(dwellingActor);
}
}
}*/
}
2021-05-15 18:22:44 +02:00
}
std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
const PathNodeInfo & source,
const PathfinderConfig * pathfinderConfig,
const CPathfinderHelper * pathfinderHelper)
{
std::vector<CGPathNode *> neighbours;
if(source.isNodeObjectVisitable())
{
auto accessibleExits = pathfinderHelper->getTeleportExits(source);
auto srcNode = getAINode(source.node);
for(auto & neighbour : accessibleExits)
{
2021-05-15 18:22:49 +02:00
auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
2021-05-15 18:22:44 +02:00
if(!node)
continue;
2023-04-16 19:42:56 +02:00
neighbours.push_back(node.value());
2021-05-15 18:22:44 +02:00
}
}
return neighbours;
}
struct TownPortalFinder
2021-05-16 13:07:54 +02:00
{
2021-05-16 13:09:49 +02:00
const std::vector<CGPathNode *> & initialNodes;
2023-10-05 17:18:14 +02:00
MasteryLevel::Type townPortalSkillLevel;
2021-05-16 13:09:49 +02:00
uint64_t movementNeeded;
const ChainActor * actor;
const CGHeroInstance * hero;
std::vector<const CGTownInstance *> targetTowns;
AINodeStorage * nodeStorage;
2021-05-16 13:07:54 +02:00
2021-05-16 13:09:49 +02:00
SpellID spellID;
const CSpell * townPortal;
TownPortalFinder(
2021-05-16 13:09:49 +02:00
const ChainActor * actor,
const std::vector<CGPathNode *> & initialNodes,
std::vector<const CGTownInstance *> targetTowns,
AINodeStorage * nodeStorage)
:actor(actor), initialNodes(initialNodes), hero(actor->hero),
targetTowns(targetTowns), nodeStorage(nodeStorage)
{
spellID = SpellID::TOWN_PORTAL;
townPortal = spellID.toSpell();
// TODO: Copy/Paste from TownPortalMechanics
2023-10-05 17:18:14 +02:00
townPortalSkillLevel = MasteryLevel::Type(hero->getSpellSchoolLevel(townPortal));
movementNeeded = GameConstants::BASE_MOVEMENT_COST * (townPortalSkillLevel >= MasteryLevel::EXPERT ? 2 : 3);
2021-05-16 13:09:49 +02:00
}
bool actorCanCastTownPortal()
{
return hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal);
}
CGPathNode * getBestInitialNodeForTownPortal(const CGTownInstance * targetTown)
{
for(CGPathNode * node : initialNodes)
{
auto aiNode = nodeStorage->getAINode(node);
if(aiNode->actor->baseActor != actor
|| node->layer != EPathfindingLayer::LAND
|| node->moveRemains < movementNeeded)
{
continue;
}
if(townPortalSkillLevel < MasteryLevel::ADVANCED)
2021-05-16 13:09:49 +02:00
{
const CGTownInstance * nearestTown = *vstd::minElementByFun(targetTowns, [&](const CGTownInstance * t) -> int
{
return node->coord.dist2dSQ(t->visitablePos());
});
if(targetTown != nearestTown)
continue;
}
2022-09-06 20:14:22 +02:00
return node;
2021-05-16 13:09:49 +02:00
}
2022-09-06 20:14:22 +02:00
return nullptr;
2021-05-16 13:09:49 +02:00
}
2023-04-16 19:42:56 +02:00
std::optional<AIPathNode *> createTownPortalNode(const CGTownInstance * targetTown)
2021-05-16 13:09:49 +02:00
{
auto bestNode = getBestInitialNodeForTownPortal(targetTown);
if(!bestNode)
2023-04-16 19:42:56 +02:00
return std::nullopt;
2021-05-16 13:09:49 +02:00
auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor);
if(!nodeOptional)
2023-04-16 19:42:56 +02:00
return std::nullopt;
2021-05-16 13:09:49 +02:00
2023-04-16 19:42:56 +02:00
AIPathNode * node = nodeOptional.value();
float movementCost = (float)movementNeeded / (float)hero->movementPointsLimit(EPathfindingLayer::LAND);
2021-05-16 13:09:49 +02:00
movementCost += bestNode->getCost();
2021-05-16 13:09:49 +02:00
if(node->action == EPathNodeAction::UNKNOWN || node->getCost() > movementCost)
2021-05-16 13:09:49 +02:00
{
nodeStorage->commit(
node,
nodeStorage->getAINode(bestNode),
EPathNodeAction::TELEPORT_NORMAL,
2021-05-16 13:09:49 +02:00
bestNode->turns,
bestNode->moveRemains - movementNeeded,
movementCost,
DO_NOT_SAVE_TO_COMMITTED_TILES);
2021-05-16 13:09:49 +02:00
node->theNodeBefore = bestNode;
node->addSpecialAction(std::make_shared<AIPathfinding::TownPortalAction>(targetTown));
2021-05-16 13:09:49 +02:00
}
return nodeOptional;
}
};
2021-05-16 13:07:54 +02:00
2022-09-06 20:14:22 +02:00
template<class TVector>
void AINodeStorage::calculateTownPortal(
const ChainActor * actor,
const std::map<const CGHeroInstance *, int> & maskMap,
const std::vector<CGPathNode *> & initialNodes,
TVector & output)
{
auto towns = cb->getTownsInfo(false);
vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
{
return cb->getPlayerRelations(actor->hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
});
if(!towns.size())
{
return; // no towns no need to run loop further
}
TownPortalFinder townPortalFinder(actor, initialNodes, towns, this);
2022-09-06 20:14:22 +02:00
if(townPortalFinder.actorCanCastTownPortal())
{
for(const CGTownInstance * targetTown : towns)
{
2024-02-03 12:20:59 +02:00
if(targetTown->visitingHero
&& targetTown->getUpperArmy()->stacksCount()
&& maskMap.find(targetTown->visitingHero.get()) != maskMap.end())
2022-09-06 20:14:22 +02:00
{
auto basicMask = maskMap.at(targetTown->visitingHero.get());
bool sameActorInTown = actor->chainMask == basicMask;
2024-02-03 12:20:59 +02:00
if(!sameActorInTown)
2022-09-06 20:14:22 +02:00
continue;
}
auto nodeOptional = townPortalFinder.createTownPortalNode(targetTown);
if(nodeOptional)
{
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 1
logAi->trace("Adding town portal node at %s", targetTown->getObjectName());
2022-09-06 20:14:22 +02:00
#endif
2023-04-16 19:42:56 +02:00
output.push_back(nodeOptional.value());
2022-09-06 20:14:22 +02:00
}
}
}
}
2021-05-16 13:07:54 +02:00
void AINodeStorage::calculateTownPortalTeleportations(std::vector<CGPathNode *> & initialNodes)
2021-05-15 18:22:44 +02:00
{
2021-05-16 13:07:54 +02:00
std::set<const ChainActor *> actorsOfInitial;
2021-05-15 18:22:44 +02:00
2021-05-16 13:07:54 +02:00
for(const CGPathNode * node : initialNodes)
{
auto aiNode = getAINode(node);
2021-05-15 18:22:44 +02:00
2022-09-06 20:14:22 +02:00
if(aiNode->actor->hero)
actorsOfInitial.insert(aiNode->actor->baseActor);
2021-05-16 13:07:54 +02:00
}
2021-05-15 18:22:44 +02:00
std::map<const CGHeroInstance *, int> maskMap;
for(std::shared_ptr<ChainActor> basicActor : actors)
{
if(basicActor->hero)
maskMap[basicActor->hero] = basicActor->chainMask;
}
2022-09-06 20:14:22 +02:00
boost::sort(initialNodes, NodeComparer<CGPathNode>());
2021-05-15 18:22:44 +02:00
2022-09-06 20:14:22 +02:00
std::vector<const ChainActor *> actorsVector(actorsOfInitial.begin(), actorsOfInitial.end());
tbb::concurrent_vector<CGPathNode *> output;
2021-05-15 18:22:44 +02:00
2024-06-17 11:43:22 +02:00
// TODO: re-enable after fixing thread races. See issue for details:
// https://github.com/vcmi/vcmi/pull/4130
#if 0
if (actorsVector.size() * initialNodes.size() > 1000)
2022-09-06 20:14:22 +02:00
{
2024-03-24 13:16:46 +02:00
tbb::parallel_for(tbb::blocked_range<size_t>(0, actorsVector.size()), [&](const tbb::blocked_range<size_t> & r)
2021-05-15 18:22:44 +02:00
{
2022-09-06 20:14:22 +02:00
for(int i = r.begin(); i != r.end(); i++)
{
2022-09-06 20:14:22 +02:00
calculateTownPortal(actorsVector[i], maskMap, initialNodes, output);
}
2022-09-06 20:14:22 +02:00
});
2021-05-15 18:22:44 +02:00
2022-09-06 20:14:22 +02:00
std::copy(output.begin(), output.end(), std::back_inserter(initialNodes));
}
else
2024-06-17 11:43:22 +02:00
#endif
2022-09-06 20:14:22 +02:00
{
for(auto actor : actorsVector)
{
calculateTownPortal(actor, maskMap, initialNodes, initialNodes);
2021-05-15 18:22:44 +02:00
}
}
}
bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
{
2024-03-23 11:44:15 +02:00
auto candidateNode = getAINode(destination.node);
2021-05-15 20:54:58 +02:00
2024-03-23 11:44:15 +02:00
return hasBetterChain(source.node, *candidateNode);
2021-05-15 20:54:58 +02:00
}
bool AINodeStorage::hasBetterChain(
2024-03-23 11:44:15 +02:00
const CGPathNode * source,
const AIPathNode & candidateNode) const
2021-05-15 20:54:58 +02:00
{
2024-03-23 11:44:15 +02:00
return iterateValidNodesUntil(
candidateNode.coord,
candidateNode.layer,
[this, &source, candidateNode](const AIPathNode & node) -> bool
{
return isOtherChainBetter(source, candidateNode, node);
});
}
2021-05-15 18:22:44 +02:00
2024-03-23 11:44:15 +02:00
template<class NodeRange>
bool AINodeStorage::hasBetterChain(
const CGPathNode * source,
const AIPathNode & candidateNode,
const NodeRange & nodes) const
{
for(const AIPathNode & node : nodes)
2021-05-15 18:22:44 +02:00
{
2024-03-23 11:44:15 +02:00
if(isOtherChainBetter(source, candidateNode, node))
return true;
}
2021-05-15 18:22:44 +02:00
2024-03-23 11:44:15 +02:00
return false;
}
2021-05-15 20:54:58 +02:00
2024-03-23 11:44:15 +02:00
bool AINodeStorage::isOtherChainBetter(
const CGPathNode * source,
const AIPathNode & candidateNode,
const AIPathNode & other) const
{
auto sameNode = other.actor == candidateNode.actor;
2021-05-15 20:54:58 +02:00
2024-03-23 11:44:15 +02:00
if(sameNode || other.action == EPathNodeAction::UNKNOWN || !other.actor || !other.actor->hero)
{
return false;
}
2021-05-15 20:56:08 +02:00
2024-03-23 11:44:15 +02:00
if(other.danger <= candidateNode.danger && candidateNode.actor == other.actor->battleActor)
{
if(other.getCost() < candidateNode.getCost())
2021-05-15 20:56:08 +02:00
{
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
2021-05-16 13:09:49 +02:00
logAi->trace(
"Block inefficient battle move %s->%s, hero: %s[%X], army %lld, mp diff: %i",
2021-05-16 13:09:49 +02:00
source->coord.toString(),
2024-03-23 11:44:15 +02:00
candidateNode.coord.toString(),
candidateNode.actor->hero->getNameTranslated(),
candidateNode.actor->chainMask,
candidateNode.actor->armyValue,
other.moveRemains - candidateNode.moveRemains);
2021-05-16 13:09:49 +02:00
#endif
2021-05-15 20:56:08 +02:00
return true;
}
2024-03-23 11:44:15 +02:00
}
2021-05-15 20:54:58 +02:00
2024-03-23 11:44:15 +02:00
if(candidateNode.actor->chainMask != other.actor->chainMask && heroChainPass != EHeroChainPass::FINAL)
return false;
auto nodeActor = other.actor;
auto nodeArmyValue = nodeActor->armyValue - other.armyLoss;
auto candidateArmyValue = candidateNode.actor->armyValue - candidateNode.armyLoss;
if(nodeArmyValue > candidateArmyValue
&& other.getCost() <= candidateNode.getCost())
{
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
logAi->trace(
"Block inefficient move because of stronger army %s->%s, hero: %s[%X], army %lld, mp diff: %i",
2024-03-23 11:44:15 +02:00
source->coord.toString(),
candidateNode.coord.toString(),
candidateNode.actor->hero->getNameTranslated(),
candidateNode.actor->chainMask,
candidateNode.actor->armyValue,
other.moveRemains - candidateNode.moveRemains);
#endif
return true;
}
if(heroChainPass == EHeroChainPass::FINAL)
{
if(nodeArmyValue == candidateArmyValue
&& nodeActor->heroFightingStrength >= candidateNode.actor->heroFightingStrength
&& other.getCost() <= candidateNode.getCost())
2021-05-15 20:54:58 +02:00
{
2024-03-23 11:44:15 +02:00
if(vstd::isAlmostEqual(nodeActor->heroFightingStrength, candidateNode.actor->heroFightingStrength)
&& vstd::isAlmostEqual(other.getCost(), candidateNode.getCost())
&& &other < &candidateNode)
2021-05-16 13:09:49 +02:00
{
2024-03-23 11:44:15 +02:00
return false;
}
2021-05-16 13:09:49 +02:00
2022-09-26 20:01:07 +02:00
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
2024-03-23 11:44:15 +02:00
logAi->trace(
"Block inefficient move because of stronger hero %s->%s, hero: %s[%X], army %lld, mp diff: %i",
2024-03-23 11:44:15 +02:00
source->coord.toString(),
candidateNode.coord.toString(),
candidateNode.actor->hero->getNameTranslated(),
candidateNode.actor->chainMask,
candidateNode.actor->armyValue,
other.moveRemains - candidateNode.moveRemains);
2021-05-16 13:09:49 +02:00
#endif
2024-03-23 11:44:15 +02:00
return true;
}
2021-05-15 18:22:44 +02:00
}
return false;
}
2021-05-15 18:22:49 +02:00
bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
2021-05-15 18:22:44 +02:00
{
2024-03-23 11:44:15 +02:00
auto chains = nodes.get(pos);
2021-05-15 18:22:49 +02:00
for(const AIPathNode & node : chains)
{
2024-03-23 11:44:15 +02:00
if(node.version == AISharedStorage::version
&& node.layer == layer
&& node.action != EPathNodeAction::UNKNOWN
&& node.actor
&& node.actor->hero == hero.h)
2021-05-15 18:22:49 +02:00
{
return true;
}
}
2021-05-15 18:22:44 +02:00
2021-05-15 18:22:49 +02:00
return false;
2021-05-15 18:22:44 +02:00
}
void AINodeStorage::calculateChainInfo(std::vector<AIPath> & paths, const int3 & pos, bool isOnLand) const
2021-05-15 18:22:44 +02:00
{
2024-03-23 11:44:15 +02:00
auto layer = isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL;
auto chains = nodes.get(pos);
2021-05-15 18:22:44 +02:00
for(const AIPathNode & node : chains)
{
2024-03-23 11:44:15 +02:00
if(node.version != AISharedStorage::version
|| node.layer != layer
|| node.action == EPathNodeAction::UNKNOWN
|| !node.actor
|| !node.actor->hero)
2021-05-15 18:22:44 +02:00
{
continue;
}
AIPath & path = paths.emplace_back();
2021-05-15 18:22:44 +02:00
2021-05-15 18:22:49 +02:00
path.targetHero = node.actor->hero;
2021-05-15 20:01:48 +02:00
path.heroArmy = node.actor->creatureSet;
path.armyLoss = node.armyLoss;
path.targetObjectDanger = evaluateDanger(pos, path.targetHero, !node.actor->allowBattle);
2024-07-18 12:37:18 +02:00
if(path.targetObjectDanger > 0)
{
if(node.theNodeBefore)
{
auto prevNode = getAINode(node.theNodeBefore);
if(node.coord == prevNode->coord && node.actor->hero == prevNode->actor->hero)
{
paths.pop_back();
continue;
}
else
{
path.armyLoss = prevNode->armyLoss;
}
}
else
{
path.armyLoss = 0;
}
}
path.targetObjectArmyLoss = evaluateArmyLoss(
path.targetHero,
getHeroArmyStrengthWithCommander(path.targetHero, path.heroArmy),
path.targetObjectDanger);
2021-05-15 20:04:48 +02:00
path.chainMask = node.actor->chainMask;
2021-05-16 12:52:30 +02:00
path.exchangeCount = node.actor->actorExchangeCount;
2021-05-15 20:01:48 +02:00
2021-05-15 20:56:31 +02:00
fillChainInfo(&node, path, -1);
2021-05-15 18:22:44 +02:00
}
}
2021-05-15 20:56:31 +02:00
void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
2021-05-15 20:01:48 +02:00
{
while(node != nullptr)
{
2021-05-15 20:04:48 +02:00
if(!node->actor->hero)
2021-05-15 20:01:48 +02:00
return;
if(node->chainOther)
2021-05-15 20:56:31 +02:00
fillChainInfo(node->chainOther, path, parentIndex);
2021-05-15 20:01:48 +02:00
2024-03-23 11:44:15 +02:00
AIPathNodeInfo pathNode;
2024-03-23 11:44:15 +02:00
pathNode.cost = node->getCost();
pathNode.targetHero = node->actor->hero;
pathNode.chainMask = node->actor->chainMask;
pathNode.specialAction = node->specialAction;
pathNode.turns = node->turns;
pathNode.danger = node->danger;
pathNode.coord = node->coord;
pathNode.parentIndex = parentIndex;
pathNode.actionIsBlocked = false;
pathNode.layer = node->layer;
2021-05-16 13:38:53 +02:00
2024-03-23 11:44:15 +02:00
if(pathNode.specialAction)
{
auto targetNode =node->theNodeBefore ? getAINode(node->theNodeBefore) : node;
2021-05-15 20:04:48 +02:00
2024-03-31 17:39:00 +02:00
pathNode.actionIsBlocked = !pathNode.specialAction->canAct(ai, targetNode);
2021-05-15 20:04:48 +02:00
}
2024-03-23 11:44:15 +02:00
parentIndex = path.nodes.size();
path.nodes.push_back(pathNode);
2021-05-15 20:01:48 +02:00
node = getAINode(node->theNodeBefore);
}
}
2021-05-15 18:22:44 +02:00
AIPath::AIPath()
: nodes({})
{
}
2021-05-16 13:38:53 +02:00
std::shared_ptr<const SpecialAction> AIPath::getFirstBlockedAction() const
{
for(auto node = nodes.rbegin(); node != nodes.rend(); node++)
{
if(node->specialAction && node->actionIsBlocked)
return node->specialAction;
}
2021-05-16 13:38:53 +02:00
return std::shared_ptr<const SpecialAction>();
}
2021-05-15 18:22:44 +02:00
int3 AIPath::firstTileToGet() const
{
if(nodes.size())
{
return nodes.back().coord;
}
return int3(-1, -1, -1);
}
int3 AIPath::targetTile() const
{
if(nodes.size())
{
2021-05-16 13:09:49 +02:00
return targetNode().coord;
}
return int3(-1, -1, -1);
}
2021-05-15 20:04:48 +02:00
const AIPathNodeInfo & AIPath::firstNode() const
{
return nodes.back();
}
2021-05-16 13:09:49 +02:00
const AIPathNodeInfo & AIPath::targetNode() const
{
auto & node = nodes.front();
return targetHero == node.targetHero ? node : nodes.at(1);
}
2021-05-15 18:22:44 +02:00
uint64_t AIPath::getPathDanger() const
{
2021-05-16 13:09:49 +02:00
if(nodes.empty())
return 0;
2021-05-15 18:22:44 +02:00
2021-05-16 13:09:49 +02:00
return targetNode().danger;
2021-05-15 18:22:44 +02:00
}
float AIPath::movementCost() const
{
2021-05-16 13:09:49 +02:00
if(nodes.empty())
return 0.0f;
2021-05-15 18:22:44 +02:00
2021-05-16 13:09:49 +02:00
return targetNode().cost;
2021-05-15 18:22:44 +02:00
}
uint8_t AIPath::turn() const
{
2021-05-16 13:09:49 +02:00
if(nodes.empty())
return 0;
2021-05-16 13:09:49 +02:00
return targetNode().turns;
}
2021-05-15 20:01:48 +02:00
uint64_t AIPath::getHeroStrength() const
{
return targetHero->getFightingStrength() * getHeroArmyStrengthWithCommander(targetHero, heroArmy);
2021-05-15 20:01:48 +02:00
}
uint64_t AIPath::getTotalDanger() const
2021-05-15 18:22:44 +02:00
{
uint64_t pathDanger = getPathDanger();
uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
return danger;
}
bool AIPath::containsHero(const CGHeroInstance * hero) const
{
if(targetHero == hero)
return true;
for(auto node : nodes)
{
if(node.targetHero == hero)
return true;
}
return false;
}
uint64_t AIPath::getTotalArmyLoss() const
{
return armyLoss + targetObjectArmyLoss;
}
std::string AIPath::toString() const
{
std::stringstream str;
2021-05-16 13:09:49 +02:00
str << targetHero->getNameTranslated() << "[" << std::hex << chainMask << std::dec << "]" << ", turn " << (int)(turn()) << ": ";
2021-05-16 13:09:49 +02:00
for(auto node : nodes)
str << node.targetHero->getNameTranslated() << "[" << std::hex << node.chainMask << std::dec << "]" << "->" << node.coord.toString() << "; ";
return str.str();
}
2022-09-26 20:01:07 +02:00
}