Fuzzy.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. /*
  2. * Fuzzy.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 "Fuzzy.h"
  12. #include <limits>
  13. #include "../../lib/mapObjects/MapObjects.h"
  14. #include "../../lib/mapObjects/CommonConstructors.h"
  15. #include "../../lib/CCreatureHandler.h"
  16. #include "../../lib/CPathfinder.h"
  17. #include "../../lib/CGameStateFwd.h"
  18. #include "../../lib/VCMI_Lib.h"
  19. #include "../../CCallback.h"
  20. #include "VCAI.h"
  21. #include "MapObjectsEvaluator.h"
  22. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  23. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  24. struct BankConfig;
  25. class CBankInfo;
  26. class Engine;
  27. class InputVariable;
  28. class CGTownInstance;
  29. FuzzyHelper * fh;
  30. extern boost::thread_specific_ptr<CCallback> cb;
  31. extern boost::thread_specific_ptr<VCAI> ai;
  32. engineBase::engineBase()
  33. {
  34. engine.addRuleBlock(&rules);
  35. }
  36. void engineBase::configure()
  37. {
  38. engine.configure("Minimum", "Maximum", "Minimum", "AlgebraicSum", "Centroid", "General");
  39. logAi->info(engine.toString());
  40. }
  41. void engineBase::addRule(const std::string & txt)
  42. {
  43. rules.addRule(fl::Rule::parse(txt, &engine));
  44. }
  45. struct armyStructure
  46. {
  47. float walkers, shooters, flyers;
  48. ui32 maxSpeed;
  49. };
  50. armyStructure evaluateArmyStructure(const CArmedInstance * army)
  51. {
  52. ui64 totalStrenght = army->getArmyStrength();
  53. double walkersStrenght = 0;
  54. double flyersStrenght = 0;
  55. double shootersStrenght = 0;
  56. ui32 maxSpeed = 0;
  57. for(auto s : army->Slots())
  58. {
  59. bool walker = true;
  60. if(s.second->type->hasBonusOfType(Bonus::SHOOTER))
  61. {
  62. shootersStrenght += s.second->getPower();
  63. walker = false;
  64. }
  65. if(s.second->type->hasBonusOfType(Bonus::FLYING))
  66. {
  67. flyersStrenght += s.second->getPower();
  68. walker = false;
  69. }
  70. if(walker)
  71. walkersStrenght += s.second->getPower();
  72. vstd::amax(maxSpeed, s.second->type->valOfBonuses(Bonus::STACKS_SPEED));
  73. }
  74. armyStructure as;
  75. as.walkers = walkersStrenght / totalStrenght;
  76. as.shooters = shootersStrenght / totalStrenght;
  77. as.flyers = flyersStrenght / totalStrenght;
  78. as.maxSpeed = maxSpeed;
  79. assert(as.walkers || as.flyers || as.shooters);
  80. return as;
  81. }
  82. float HeroMovementGoalEngineBase::calculateTurnDistanceInputValue(const CGHeroInstance * h, int3 tile) const
  83. {
  84. float turns = 0.0f;
  85. float distance = CPathfinderHelper::getMovementCost(h, tile);
  86. if(distance)
  87. {
  88. if(distance < h->movement) //we can move there within one turn
  89. turns = (fl::scalar)distance / h->movement;
  90. else
  91. turns = 1 + (fl::scalar)(distance - h->movement) / h->maxMovePoints(true); //bool on land?
  92. }
  93. return turns;
  94. }
  95. ui64 FuzzyHelper::estimateBankDanger(const CBank * bank)
  96. {
  97. //this one is not fuzzy anymore, just calculate weighted average
  98. auto objectInfo = VLC->objtypeh->getHandlerFor(bank->ID, bank->subID)->getObjectInfo(bank->appearance);
  99. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  100. ui64 totalStrength = 0;
  101. ui8 totalChance = 0;
  102. for(auto config : bankInfo->getPossibleGuards())
  103. {
  104. totalStrength += config.second.totalStrength * config.first;
  105. totalChance += config.first;
  106. }
  107. return totalStrength / std::max<ui8>(totalChance, 1); //avoid division by zero
  108. }
  109. TacticalAdvantageEngine::TacticalAdvantageEngine()
  110. {
  111. try
  112. {
  113. ourShooters = new fl::InputVariable("OurShooters");
  114. ourWalkers = new fl::InputVariable("OurWalkers");
  115. ourFlyers = new fl::InputVariable("OurFlyers");
  116. enemyShooters = new fl::InputVariable("EnemyShooters");
  117. enemyWalkers = new fl::InputVariable("EnemyWalkers");
  118. enemyFlyers = new fl::InputVariable("EnemyFlyers");
  119. //Tactical advantage calculation
  120. std::vector<fl::InputVariable *> helper =
  121. {
  122. ourShooters, ourWalkers, ourFlyers, enemyShooters, enemyWalkers, enemyFlyers
  123. };
  124. for(auto val : helper)
  125. {
  126. engine.addInputVariable(val);
  127. val->addTerm(new fl::Ramp("FEW", 0.6, 0.0));
  128. val->addTerm(new fl::Ramp("MANY", 0.4, 1));
  129. val->setRange(0.0, 1.0);
  130. }
  131. ourSpeed = new fl::InputVariable("OurSpeed");
  132. enemySpeed = new fl::InputVariable("EnemySpeed");
  133. helper = { ourSpeed, enemySpeed };
  134. for(auto val : helper)
  135. {
  136. engine.addInputVariable(val);
  137. val->addTerm(new fl::Ramp("LOW", 6.5, 3));
  138. val->addTerm(new fl::Triangle("MEDIUM", 5.5, 10.5));
  139. val->addTerm(new fl::Ramp("HIGH", 8.5, 16));
  140. val->setRange(0, 25);
  141. }
  142. castleWalls = new fl::InputVariable("CastleWalls");
  143. engine.addInputVariable(castleWalls);
  144. {
  145. fl::Rectangle * none = new fl::Rectangle("NONE", CGTownInstance::NONE, CGTownInstance::NONE + (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f);
  146. castleWalls->addTerm(none);
  147. fl::Trapezoid * medium = new fl::Trapezoid("MEDIUM", (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f, CGTownInstance::FORT,
  148. CGTownInstance::CITADEL, CGTownInstance::CITADEL + (CGTownInstance::CASTLE - CGTownInstance::CITADEL) * 0.5f);
  149. castleWalls->addTerm(medium);
  150. fl::Ramp * high = new fl::Ramp("HIGH", CGTownInstance::CITADEL - 0.1, CGTownInstance::CASTLE);
  151. castleWalls->addTerm(high);
  152. castleWalls->setRange(CGTownInstance::NONE, CGTownInstance::CASTLE);
  153. }
  154. bankPresent = new fl::InputVariable("Bank");
  155. engine.addInputVariable(bankPresent);
  156. {
  157. fl::Rectangle * termFalse = new fl::Rectangle("FALSE", 0.0, 0.5f);
  158. bankPresent->addTerm(termFalse);
  159. fl::Rectangle * termTrue = new fl::Rectangle("TRUE", 0.5f, 1);
  160. bankPresent->addTerm(termTrue);
  161. bankPresent->setRange(0, 1);
  162. }
  163. threat = new fl::OutputVariable("Threat");
  164. engine.addOutputVariable(threat);
  165. threat->addTerm(new fl::Ramp("LOW", 1, MIN_AI_STRENGHT));
  166. threat->addTerm(new fl::Triangle("MEDIUM", 0.8, 1.2));
  167. threat->addTerm(new fl::Ramp("HIGH", 1, 1.5));
  168. threat->setRange(MIN_AI_STRENGHT, 1.5);
  169. addRule("if OurShooters is MANY and EnemySpeed is LOW then Threat is LOW");
  170. addRule("if OurShooters is MANY and EnemyShooters is FEW then Threat is LOW");
  171. addRule("if OurSpeed is LOW and EnemyShooters is MANY then Threat is HIGH");
  172. addRule("if OurSpeed is HIGH and EnemyShooters is MANY then Threat is LOW");
  173. addRule("if OurWalkers is FEW and EnemyShooters is MANY then Threat is somewhat LOW");
  174. addRule("if OurShooters is MANY and EnemySpeed is HIGH then Threat is somewhat HIGH");
  175. //just to cover all cases
  176. addRule("if OurShooters is FEW and EnemySpeed is HIGH then Threat is MEDIUM");
  177. addRule("if EnemySpeed is MEDIUM then Threat is MEDIUM");
  178. addRule("if EnemySpeed is LOW and OurShooters is FEW then Threat is MEDIUM");
  179. addRule("if Bank is TRUE and OurShooters is MANY then Threat is somewhat HIGH");
  180. addRule("if Bank is TRUE and EnemyShooters is MANY then Threat is LOW");
  181. addRule("if CastleWalls is HIGH and OurWalkers is MANY then Threat is very HIGH");
  182. addRule("if CastleWalls is HIGH and OurFlyers is MANY and OurShooters is MANY then Threat is MEDIUM");
  183. addRule("if CastleWalls is MEDIUM and OurShooters is MANY and EnemyWalkers is MANY then Threat is LOW");
  184. }
  185. catch(fl::Exception & pe)
  186. {
  187. logAi->error("initTacticalAdvantage: %s", pe.getWhat());
  188. }
  189. configure();
  190. }
  191. float TacticalAdvantageEngine::getTacticalAdvantage(const CArmedInstance * we, const CArmedInstance * enemy)
  192. {
  193. float output = 1;
  194. try
  195. {
  196. armyStructure ourStructure = evaluateArmyStructure(we);
  197. armyStructure enemyStructure = evaluateArmyStructure(enemy);
  198. ourWalkers->setValue(ourStructure.walkers);
  199. ourShooters->setValue(ourStructure.shooters);
  200. ourFlyers->setValue(ourStructure.flyers);
  201. ourSpeed->setValue(ourStructure.maxSpeed);
  202. enemyWalkers->setValue(enemyStructure.walkers);
  203. enemyShooters->setValue(enemyStructure.shooters);
  204. enemyFlyers->setValue(enemyStructure.flyers);
  205. enemySpeed->setValue(enemyStructure.maxSpeed);
  206. bool bank = dynamic_cast<const CBank *>(enemy);
  207. if(bank)
  208. bankPresent->setValue(1);
  209. else
  210. bankPresent->setValue(0);
  211. const CGTownInstance * fort = dynamic_cast<const CGTownInstance *>(enemy);
  212. if(fort)
  213. castleWalls->setValue(fort->fortLevel());
  214. else
  215. castleWalls->setValue(0);
  216. engine.process();
  217. output = threat->getValue();
  218. }
  219. catch(fl::Exception & fe)
  220. {
  221. logAi->error("getTacticalAdvantage: %s ", fe.getWhat());
  222. }
  223. if(output < 0 || (output != output))
  224. {
  225. fl::InputVariable * tab[] = { bankPresent, castleWalls, ourWalkers, ourShooters, ourFlyers, ourSpeed, enemyWalkers, enemyShooters, enemyFlyers, enemySpeed };
  226. std::string names[] = { "bankPresent", "castleWalls", "ourWalkers", "ourShooters", "ourFlyers", "ourSpeed", "enemyWalkers", "enemyShooters", "enemyFlyers", "enemySpeed" };
  227. std::stringstream log("Warning! Fuzzy engine doesn't cover this set of parameters: ");
  228. for(int i = 0; i < boost::size(tab); i++)
  229. log << names[i] << ": " << tab[i]->getValue() << " ";
  230. logAi->error(log.str());
  231. assert(false);
  232. }
  233. return output;
  234. }
  235. //std::shared_ptr<AbstractGoal> chooseSolution (std::vector<std::shared_ptr<AbstractGoal>> & vec)
  236. Goals::TSubgoal FuzzyHelper::chooseSolution(Goals::TGoalVec vec)
  237. {
  238. if(vec.empty()) //no possibilities found
  239. return sptr(Goals::Invalid());
  240. ai->cachedSectorMaps.clear();
  241. //a trick to switch between heroes less often - calculatePaths is costly
  242. auto sortByHeroes = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  243. {
  244. return lhs->hero.h < rhs->hero.h;
  245. };
  246. boost::sort(vec, sortByHeroes);
  247. for(auto g : vec)
  248. {
  249. setPriority(g);
  250. }
  251. auto compareGoals = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  252. {
  253. return lhs->priority < rhs->priority;
  254. };
  255. return *boost::max_element(vec, compareGoals);
  256. }
  257. float FuzzyHelper::evaluate(Goals::Explore & g)
  258. {
  259. return 1;
  260. }
  261. float FuzzyHelper::evaluate(Goals::RecruitHero & g)
  262. {
  263. return 1;
  264. }
  265. HeroMovementGoalEngineBase::HeroMovementGoalEngineBase()
  266. {
  267. try
  268. {
  269. strengthRatio = new fl::InputVariable("strengthRatio"); //hero must be strong enough to defeat guards
  270. heroStrength = new fl::InputVariable("heroStrength"); //we want to use weakest possible hero
  271. turnDistance = new fl::InputVariable("turnDistance"); //we want to use hero who is near
  272. missionImportance = new fl::InputVariable("lockedMissionImportance"); //we may want to preempt hero with low-priority mission
  273. value = new fl::OutputVariable("Value");
  274. value->setMinimum(0);
  275. value->setMaximum(5);
  276. std::vector<fl::InputVariable *> helper = { strengthRatio, heroStrength, turnDistance, missionImportance };
  277. for(auto val : helper)
  278. {
  279. engine.addInputVariable(val);
  280. }
  281. engine.addOutputVariable(value);
  282. strengthRatio->addTerm(new fl::Ramp("LOW", SAFE_ATTACK_CONSTANT, 0));
  283. strengthRatio->addTerm(new fl::Ramp("HIGH", SAFE_ATTACK_CONSTANT, SAFE_ATTACK_CONSTANT * 3));
  284. strengthRatio->setRange(0, SAFE_ATTACK_CONSTANT * 3);
  285. //strength compared to our main hero
  286. heroStrength->addTerm(new fl::Ramp("LOW", 0.2, 0));
  287. heroStrength->addTerm(new fl::Triangle("MEDIUM", 0.2, 0.8));
  288. heroStrength->addTerm(new fl::Ramp("HIGH", 0.5, 1));
  289. heroStrength->setRange(0.0, 1.0);
  290. turnDistance->addTerm(new fl::Ramp("SHORT", 0.5, 0));
  291. turnDistance->addTerm(new fl::Triangle("MEDIUM", 0.1, 0.8));
  292. turnDistance->addTerm(new fl::Ramp("LONG", 0.5, 3));
  293. turnDistance->setRange(0.0, 3.0);
  294. missionImportance->addTerm(new fl::Ramp("LOW", 2.5, 0));
  295. missionImportance->addTerm(new fl::Triangle("MEDIUM", 2, 3));
  296. missionImportance->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  297. missionImportance->setRange(0.0, 5.0);
  298. //an issue: in 99% cases this outputs center of mass (2.5) regardless of actual input :/
  299. //should be same as "mission Importance" to keep consistency
  300. value->addTerm(new fl::Ramp("LOW", 2.5, 0));
  301. value->addTerm(new fl::Triangle("MEDIUM", 2, 3)); //can't be center of mass :/
  302. value->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  303. value->setRange(0.0, 5.0);
  304. //use unarmed scouts if possible
  305. addRule("if strengthRatio is HIGH and heroStrength is LOW then Value is very HIGH");
  306. //we may want to use secondary hero(es) rather than main hero
  307. addRule("if strengthRatio is HIGH and heroStrength is MEDIUM then Value is somewhat HIGH");
  308. addRule("if strengthRatio is HIGH and heroStrength is HIGH then Value is somewhat LOW");
  309. //don't assign targets to heroes who are too weak, but prefer targets of our main hero (in case we need to gather army)
  310. addRule("if strengthRatio is LOW and heroStrength is LOW then Value is very LOW");
  311. //attempt to arm secondary heroes is not stupid
  312. addRule("if strengthRatio is LOW and heroStrength is MEDIUM then Value is somewhat HIGH");
  313. addRule("if strengthRatio is LOW and heroStrength is HIGH then Value is LOW");
  314. //do not cancel important goals
  315. addRule("if lockedMissionImportance is HIGH then Value is very LOW");
  316. addRule("if lockedMissionImportance is MEDIUM then Value is somewhat LOW");
  317. addRule("if lockedMissionImportance is LOW then Value is HIGH");
  318. //pick nearby objects if it's easy, avoid long walks
  319. addRule("if turnDistance is SHORT then Value is HIGH");
  320. addRule("if turnDistance is MEDIUM then Value is MEDIUM");
  321. addRule("if turnDistance is LONG then Value is LOW");
  322. }
  323. catch(fl::Exception & fe)
  324. {
  325. logAi->error("HeroMovementGoalEngineBase: %s", fe.getWhat());
  326. }
  327. }
  328. void HeroMovementGoalEngineBase::setSharedFuzzyVariables(Goals::AbstractGoal & goal)
  329. {
  330. float turns = calculateTurnDistanceInputValue(goal.hero.h, goal.tile);
  331. float missionImportanceData = 0;
  332. if(vstd::contains(ai->lockedHeroes, goal.hero))
  333. missionImportanceData = ai->lockedHeroes[goal.hero]->priority;
  334. float strengthRatioData = 10.0f; //we are much stronger than enemy
  335. ui64 danger = evaluateDanger(goal.tile, goal.hero.h);
  336. if(danger)
  337. strengthRatioData = (fl::scalar)goal.hero.h->getTotalStrength() / danger;
  338. try
  339. {
  340. strengthRatio->setValue(strengthRatioData);
  341. heroStrength->setValue((fl::scalar)goal.hero->getTotalStrength() / ai->primaryHero()->getTotalStrength());
  342. turnDistance->setValue(turns);
  343. missionImportance->setValue(missionImportanceData);
  344. }
  345. catch(fl::Exception & fe)
  346. {
  347. logAi->error("HeroMovementGoalEngineBase::setSharedFuzzyVariables: %s", fe.getWhat());
  348. }
  349. }
  350. float FuzzyHelper::evaluate(Goals::VisitTile & g)
  351. {
  352. return visitTileEngine.evaluate(g);
  353. }
  354. float FuzzyHelper::evaluate(Goals::VisitObj & g)
  355. {
  356. return getObjEngine.evaluate(g);
  357. }
  358. float FuzzyHelper::evaluate(Goals::VisitHero & g)
  359. {
  360. auto obj = cb->getObj(ObjectInstanceID(g.objid)); //we assume for now that these goals are similar
  361. if(!obj)
  362. return -100; //hero died in the meantime
  363. //TODO: consider direct copy (constructor?)
  364. g.setpriority(Goals::VisitTile(obj->visitablePos()).sethero(g.hero).setisAbstract(g.isAbstract).accept(this));
  365. return g.priority;
  366. }
  367. float FuzzyHelper::evaluate(Goals::GatherArmy & g)
  368. {
  369. //the more army we need, the more important goal
  370. //the more army we lack, the less important goal
  371. float army = g.hero->getArmyStrength();
  372. float ratio = g.value / std::max(g.value - army, 2000.0f); //2000 is about the value of hero recruited from tavern
  373. return 5 * (ratio / (ratio + 2)); //so 50% army gives 2.5, asymptotic 5
  374. }
  375. float FuzzyHelper::evaluate(Goals::ClearWayTo & g)
  376. {
  377. if(!g.hero.h)
  378. throw cannotFulfillGoalException("ClearWayTo called without hero!");
  379. int3 t = ai->getCachedSectorMap(g.hero)->firstTileToGet(g.hero, g.tile);
  380. if(t.valid())
  381. {
  382. if(isSafeToVisit(g.hero, t))
  383. {
  384. g.setpriority(Goals::VisitTile(g.tile).sethero(g.hero).setisAbstract(g.isAbstract).accept(this));
  385. }
  386. else
  387. {
  388. g.setpriority (Goals::GatherArmy(evaluateDanger(t, g.hero.h)*SAFE_ATTACK_CONSTANT).
  389. sethero(g.hero).setisAbstract(true).accept(this));
  390. }
  391. return g.priority;
  392. }
  393. else
  394. return -1;
  395. }
  396. float FuzzyHelper::evaluate(Goals::BuildThis & g)
  397. {
  398. return g.priority; //TODO
  399. }
  400. float FuzzyHelper::evaluate(Goals::DigAtTile & g)
  401. {
  402. return 0;
  403. }
  404. float FuzzyHelper::evaluate(Goals::CollectRes & g)
  405. {
  406. return g.priority; //handled by ResourceManager
  407. }
  408. float FuzzyHelper::evaluate(Goals::Build & g)
  409. {
  410. return 0;
  411. }
  412. float FuzzyHelper::evaluate(Goals::BuyArmy & g)
  413. {
  414. return g.priority;
  415. }
  416. float FuzzyHelper::evaluate(Goals::Invalid & g)
  417. {
  418. return -1e10;
  419. }
  420. float FuzzyHelper::evaluate(Goals::AbstractGoal & g)
  421. {
  422. logAi->warn("Cannot evaluate goal %s", g.name());
  423. return g.priority;
  424. }
  425. void FuzzyHelper::setPriority(Goals::TSubgoal & g) //calls evaluate - Visitor pattern
  426. {
  427. g->setpriority(g->accept(this)); //this enforces returned value is set
  428. }
  429. GetObjEngine::GetObjEngine()
  430. {
  431. try
  432. {
  433. objectValue = new fl::InputVariable("objectValue"); //value of that object type known by AI
  434. engine.addInputVariable(objectValue);
  435. //objectValue ranges are based on checking RMG priorities of some objects and trying to guess sane value ranges
  436. objectValue->addTerm(new fl::Ramp("LOW", 3000, 0)); //I have feeling that concave shape might work well instead of ramp for objectValue FL terms
  437. objectValue->addTerm(new fl::Triangle("MEDIUM", 2500, 6000));
  438. objectValue->addTerm(new fl::Ramp("HIGH", 5000, 20000));
  439. objectValue->setRange(0, 20000); //relic artifact value is border value by design, even better things are scaled down.
  440. addRule("if objectValue is HIGH then value is HIGH");
  441. addRule("if objectValue is MEDIUM then value is MEDIUM");
  442. addRule("if objectValue is LOW then value is LOW");
  443. }
  444. catch(fl::Exception & fe)
  445. {
  446. logAi->error("FindWanderTarget: %s", fe.getWhat());
  447. }
  448. configure();
  449. }
  450. float GetObjEngine::evaluate(Goals::AbstractGoal & goal)
  451. {
  452. auto g = dynamic_cast<Goals::VisitObj &>(goal);
  453. if(!g.hero)
  454. return 0;
  455. auto obj = cb->getObj(ObjectInstanceID(g.objid));
  456. boost::optional<int> objValueKnownByAI = MapObjectsEvaluator::getInstance().getObjectValue(obj->ID, obj->subID);
  457. int objValue = 0;
  458. if(objValueKnownByAI != boost::none) //consider adding value manipulation based on object instances on map
  459. {
  460. objValue = std::min(std::max(objValueKnownByAI.get(), 0), 20000);
  461. }
  462. else
  463. {
  464. MapObjectsEvaluator::getInstance().addObjectData(obj->ID, obj->subID, 0);
  465. logGlobal->warn("AI met object type it doesn't know - ID: " + std::to_string(obj->ID) + ", subID: " + std::to_string(obj->subID) + " - adding to database with value " + std::to_string(objValue));
  466. }
  467. setSharedFuzzyVariables(goal);
  468. float output = -1.0f;
  469. try
  470. {
  471. objectValue->setValue(objValue);
  472. engine.process();
  473. output = value->getValue();
  474. }
  475. catch(fl::Exception & fe)
  476. {
  477. logAi->error("evaluate getWanderTargetObjectValue: %s", fe.getWhat());
  478. }
  479. assert(output >= 0.0f);
  480. return output;
  481. }
  482. VisitTileEngine::VisitTileEngine() //so far no VisitTile-specific variables that are not shared with HeroMovementGoalEngineBase
  483. {
  484. configure();
  485. }
  486. float VisitTileEngine::evaluate(Goals::AbstractGoal & goal)
  487. {
  488. auto g = dynamic_cast<Goals::VisitTile &>(goal);
  489. //we assume that hero is already set and we want to choose most suitable one for the mission
  490. if(!g.hero)
  491. return 0;
  492. //assert(cb->isInTheMap(g.tile));
  493. setSharedFuzzyVariables(goal);
  494. try
  495. {
  496. engine.process();
  497. g.priority = value->getValue();
  498. }
  499. catch(fl::Exception & fe)
  500. {
  501. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  502. }
  503. assert(g.priority >= 0);
  504. return g.priority;
  505. }