FuzzyEngines.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /*
  2. * FuzzyEngines.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 "FuzzyEngines.h"
  12. #include "../../lib/mapObjects/MapObjects.h"
  13. #include "VCAI.h"
  14. #include "MapObjectsEvaluator.h"
  15. #define MIN_AI_STRENGTH (0.5f) //lower when combat AI gets smarter
  16. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  17. extern boost::thread_specific_ptr<VCAI> ai;
  18. engineBase::engineBase()
  19. {
  20. engine.addRuleBlock(&rules);
  21. }
  22. void engineBase::configure()
  23. {
  24. engine.configure("Minimum", "Maximum", "Minimum", "AlgebraicSum", "Centroid", "General");
  25. logAi->info(engine.toString());
  26. }
  27. void engineBase::addRule(const std::string & txt)
  28. {
  29. rules.addRule(fl::Rule::parse(txt, &engine));
  30. }
  31. struct armyStructure
  32. {
  33. float walkers, shooters, flyers;
  34. ui32 maxSpeed;
  35. };
  36. armyStructure evaluateArmyStructure(const CArmedInstance * army)
  37. {
  38. ui64 totalStrenght = army->getArmyStrength();
  39. double walkersStrenght = 0;
  40. double flyersStrenght = 0;
  41. double shootersStrenght = 0;
  42. ui32 maxSpeed = 0;
  43. for(auto s : army->Slots())
  44. {
  45. bool walker = true;
  46. if(s.second->type->hasBonusOfType(Bonus::SHOOTER))
  47. {
  48. shootersStrenght += s.second->getPower();
  49. walker = false;
  50. }
  51. if(s.second->type->hasBonusOfType(Bonus::FLYING))
  52. {
  53. flyersStrenght += s.second->getPower();
  54. walker = false;
  55. }
  56. if(walker)
  57. walkersStrenght += s.second->getPower();
  58. vstd::amax(maxSpeed, s.second->type->valOfBonuses(Bonus::STACKS_SPEED));
  59. }
  60. armyStructure as;
  61. as.walkers = walkersStrenght / totalStrenght;
  62. as.shooters = shootersStrenght / totalStrenght;
  63. as.flyers = flyersStrenght / totalStrenght;
  64. as.maxSpeed = maxSpeed;
  65. assert(as.walkers || as.flyers || as.shooters);
  66. return as;
  67. }
  68. float HeroMovementGoalEngineBase::calculateTurnDistanceInputValue(const CGHeroInstance * h, int3 tile) const
  69. {
  70. float turns = 0.0f;
  71. float distance = distanceToTile(h, tile);
  72. if(distance)
  73. {
  74. if(distance < h->movement) //we can move there within one turn
  75. turns = (fl::scalar)distance / h->movement;
  76. else
  77. turns = 1 + (fl::scalar)(distance - h->movement) / h->maxMovePoints(true); //bool on land?
  78. }
  79. return turns;
  80. }
  81. TacticalAdvantageEngine::TacticalAdvantageEngine()
  82. {
  83. try
  84. {
  85. ourShooters = new fl::InputVariable("OurShooters");
  86. ourWalkers = new fl::InputVariable("OurWalkers");
  87. ourFlyers = new fl::InputVariable("OurFlyers");
  88. enemyShooters = new fl::InputVariable("EnemyShooters");
  89. enemyWalkers = new fl::InputVariable("EnemyWalkers");
  90. enemyFlyers = new fl::InputVariable("EnemyFlyers");
  91. //Tactical advantage calculation
  92. std::vector<fl::InputVariable *> helper =
  93. {
  94. ourShooters, ourWalkers, ourFlyers, enemyShooters, enemyWalkers, enemyFlyers
  95. };
  96. for(auto val : helper)
  97. {
  98. engine.addInputVariable(val);
  99. val->addTerm(new fl::Ramp("FEW", 0.6, 0.0));
  100. val->addTerm(new fl::Ramp("MANY", 0.4, 1));
  101. val->setRange(0.0, 1.0);
  102. }
  103. ourSpeed = new fl::InputVariable("OurSpeed");
  104. enemySpeed = new fl::InputVariable("EnemySpeed");
  105. helper = { ourSpeed, enemySpeed };
  106. for(auto val : helper)
  107. {
  108. engine.addInputVariable(val);
  109. val->addTerm(new fl::Ramp("LOW", 6.5, 3));
  110. val->addTerm(new fl::Triangle("MEDIUM", 5.5, 10.5));
  111. val->addTerm(new fl::Ramp("HIGH", 8.5, 16));
  112. val->setRange(0, 25);
  113. }
  114. castleWalls = new fl::InputVariable("CastleWalls");
  115. engine.addInputVariable(castleWalls);
  116. {
  117. fl::Rectangle * none = new fl::Rectangle("NONE", CGTownInstance::NONE, CGTownInstance::NONE + (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f);
  118. castleWalls->addTerm(none);
  119. fl::Trapezoid * medium = new fl::Trapezoid("MEDIUM", (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f, CGTownInstance::FORT,
  120. CGTownInstance::CITADEL, CGTownInstance::CITADEL + (CGTownInstance::CASTLE - CGTownInstance::CITADEL) * 0.5f);
  121. castleWalls->addTerm(medium);
  122. fl::Ramp * high = new fl::Ramp("HIGH", CGTownInstance::CITADEL - 0.1, CGTownInstance::CASTLE);
  123. castleWalls->addTerm(high);
  124. castleWalls->setRange(CGTownInstance::NONE, CGTownInstance::CASTLE);
  125. }
  126. bankPresent = new fl::InputVariable("Bank");
  127. engine.addInputVariable(bankPresent);
  128. {
  129. fl::Rectangle * termFalse = new fl::Rectangle("FALSE", 0.0, 0.5f);
  130. bankPresent->addTerm(termFalse);
  131. fl::Rectangle * termTrue = new fl::Rectangle("TRUE", 0.5f, 1);
  132. bankPresent->addTerm(termTrue);
  133. bankPresent->setRange(0, 1);
  134. }
  135. threat = new fl::OutputVariable("Threat");
  136. engine.addOutputVariable(threat);
  137. threat->addTerm(new fl::Ramp("LOW", 1, MIN_AI_STRENGTH));
  138. threat->addTerm(new fl::Triangle("MEDIUM", 0.8, 1.2));
  139. threat->addTerm(new fl::Ramp("HIGH", 1, 1.5));
  140. threat->setRange(MIN_AI_STRENGTH, 1.5);
  141. addRule("if OurShooters is MANY and EnemySpeed is LOW then Threat is LOW");
  142. addRule("if OurShooters is MANY and EnemyShooters is FEW then Threat is LOW");
  143. addRule("if OurSpeed is LOW and EnemyShooters is MANY then Threat is HIGH");
  144. addRule("if OurSpeed is HIGH and EnemyShooters is MANY then Threat is LOW");
  145. addRule("if OurWalkers is FEW and EnemyShooters is MANY then Threat is somewhat LOW");
  146. addRule("if OurShooters is MANY and EnemySpeed is HIGH then Threat is somewhat HIGH");
  147. //just to cover all cases
  148. addRule("if OurShooters is FEW and EnemySpeed is HIGH then Threat is MEDIUM");
  149. addRule("if EnemySpeed is MEDIUM then Threat is MEDIUM");
  150. addRule("if EnemySpeed is LOW and OurShooters is FEW then Threat is MEDIUM");
  151. addRule("if Bank is TRUE and OurShooters is MANY then Threat is somewhat HIGH");
  152. addRule("if Bank is TRUE and EnemyShooters is MANY then Threat is LOW");
  153. addRule("if CastleWalls is HIGH and OurWalkers is MANY then Threat is very HIGH");
  154. addRule("if CastleWalls is HIGH and OurFlyers is MANY and OurShooters is MANY then Threat is MEDIUM");
  155. addRule("if CastleWalls is MEDIUM and OurShooters is MANY and EnemyWalkers is MANY then Threat is LOW");
  156. }
  157. catch(fl::Exception & pe)
  158. {
  159. logAi->error("initTacticalAdvantage: %s", pe.getWhat());
  160. }
  161. configure();
  162. }
  163. float TacticalAdvantageEngine::getTacticalAdvantage(const CArmedInstance * we, const CArmedInstance * enemy)
  164. {
  165. float output = 1;
  166. try
  167. {
  168. armyStructure ourStructure = evaluateArmyStructure(we);
  169. armyStructure enemyStructure = evaluateArmyStructure(enemy);
  170. ourWalkers->setValue(ourStructure.walkers);
  171. ourShooters->setValue(ourStructure.shooters);
  172. ourFlyers->setValue(ourStructure.flyers);
  173. ourSpeed->setValue(ourStructure.maxSpeed);
  174. enemyWalkers->setValue(enemyStructure.walkers);
  175. enemyShooters->setValue(enemyStructure.shooters);
  176. enemyFlyers->setValue(enemyStructure.flyers);
  177. enemySpeed->setValue(enemyStructure.maxSpeed);
  178. bool bank = dynamic_cast<const CBank *>(enemy);
  179. if(bank)
  180. bankPresent->setValue(1);
  181. else
  182. bankPresent->setValue(0);
  183. const CGTownInstance * fort = dynamic_cast<const CGTownInstance *>(enemy);
  184. if(fort)
  185. castleWalls->setValue(fort->fortLevel());
  186. else
  187. castleWalls->setValue(0);
  188. engine.process();
  189. output = threat->getValue();
  190. }
  191. catch(fl::Exception & fe)
  192. {
  193. logAi->error("getTacticalAdvantage: %s ", fe.getWhat());
  194. }
  195. if(output < 0 || (output != output))
  196. {
  197. fl::InputVariable * tab[] = { bankPresent, castleWalls, ourWalkers, ourShooters, ourFlyers, ourSpeed, enemyWalkers, enemyShooters, enemyFlyers, enemySpeed };
  198. std::string names[] = { "bankPresent", "castleWalls", "ourWalkers", "ourShooters", "ourFlyers", "ourSpeed", "enemyWalkers", "enemyShooters", "enemyFlyers", "enemySpeed" };
  199. std::stringstream log("Warning! Fuzzy engine doesn't cover this set of parameters: ");
  200. for(int i = 0; i < boost::size(tab); i++)
  201. log << names[i] << ": " << tab[i]->getValue() << " ";
  202. logAi->error(log.str());
  203. assert(false);
  204. }
  205. return output;
  206. }
  207. //std::shared_ptr<AbstractGoal> chooseSolution (std::vector<std::shared_ptr<AbstractGoal>> & vec)
  208. HeroMovementGoalEngineBase::HeroMovementGoalEngineBase()
  209. {
  210. try
  211. {
  212. strengthRatio = new fl::InputVariable("strengthRatio"); //hero must be strong enough to defeat guards
  213. heroStrength = new fl::InputVariable("heroStrength"); //we want to use weakest possible hero
  214. turnDistance = new fl::InputVariable("turnDistance"); //we want to use hero who is near
  215. missionImportance = new fl::InputVariable("lockedMissionImportance"); //we may want to preempt hero with low-priority mission
  216. value = new fl::OutputVariable("Value");
  217. value->setMinimum(0);
  218. value->setMaximum(5);
  219. std::vector<fl::InputVariable *> helper = { strengthRatio, heroStrength, turnDistance, missionImportance };
  220. for(auto val : helper)
  221. {
  222. engine.addInputVariable(val);
  223. }
  224. engine.addOutputVariable(value);
  225. strengthRatio->addTerm(new fl::Ramp("LOW", SAFE_ATTACK_CONSTANT, 0));
  226. strengthRatio->addTerm(new fl::Ramp("HIGH", SAFE_ATTACK_CONSTANT, SAFE_ATTACK_CONSTANT * 3));
  227. strengthRatio->setRange(0, SAFE_ATTACK_CONSTANT * 3);
  228. //strength compared to our main hero
  229. heroStrength->addTerm(new fl::Ramp("LOW", 0.2, 0));
  230. heroStrength->addTerm(new fl::Triangle("MEDIUM", 0.2, 0.8));
  231. heroStrength->addTerm(new fl::Ramp("HIGH", 0.5, 1));
  232. heroStrength->setRange(0.0, 1.0);
  233. turnDistance->addTerm(new fl::Ramp("SHORT", 0.5, 0));
  234. turnDistance->addTerm(new fl::Triangle("MEDIUM", 0.1, 0.8));
  235. turnDistance->addTerm(new fl::Ramp("LONG", 0.5, 3));
  236. turnDistance->setRange(0.0, 3.0);
  237. missionImportance->addTerm(new fl::Ramp("LOW", 2.5, 0));
  238. missionImportance->addTerm(new fl::Triangle("MEDIUM", 2, 3));
  239. missionImportance->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  240. missionImportance->setRange(0.0, 5.0);
  241. //an issue: in 99% cases this outputs center of mass (2.5) regardless of actual input :/
  242. //should be same as "mission Importance" to keep consistency
  243. value->addTerm(new fl::Ramp("LOW", 2.5, 0));
  244. value->addTerm(new fl::Triangle("MEDIUM", 2, 3)); //can't be center of mass :/
  245. value->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  246. value->setRange(0.0, 5.0);
  247. //use unarmed scouts if possible
  248. addRule("if strengthRatio is HIGH and heroStrength is LOW then Value is very HIGH");
  249. //we may want to use secondary hero(es) rather than main hero
  250. addRule("if strengthRatio is HIGH and heroStrength is MEDIUM then Value is somewhat HIGH");
  251. addRule("if strengthRatio is HIGH and heroStrength is HIGH then Value is somewhat LOW");
  252. //don't assign targets to heroes who are too weak, but prefer targets of our main hero (in case we need to gather army)
  253. addRule("if strengthRatio is LOW and heroStrength is LOW then Value is very LOW");
  254. //attempt to arm secondary heroes is not stupid
  255. addRule("if strengthRatio is LOW and heroStrength is MEDIUM then Value is somewhat HIGH");
  256. addRule("if strengthRatio is LOW and heroStrength is HIGH then Value is LOW");
  257. //do not cancel important goals
  258. addRule("if lockedMissionImportance is HIGH then Value is very LOW");
  259. addRule("if lockedMissionImportance is MEDIUM then Value is somewhat LOW");
  260. addRule("if lockedMissionImportance is LOW then Value is HIGH");
  261. //pick nearby objects if it's easy, avoid long walks
  262. addRule("if turnDistance is SHORT then Value is HIGH");
  263. addRule("if turnDistance is MEDIUM then Value is MEDIUM");
  264. addRule("if turnDistance is LONG then Value is LOW");
  265. }
  266. catch(fl::Exception & fe)
  267. {
  268. logAi->error("HeroMovementGoalEngineBase: %s", fe.getWhat());
  269. }
  270. }
  271. void HeroMovementGoalEngineBase::setSharedFuzzyVariables(Goals::AbstractGoal & goal)
  272. {
  273. float turns = calculateTurnDistanceInputValue(goal.hero.h, goal.tile);
  274. float missionImportanceData = 0;
  275. if(vstd::contains(ai->lockedHeroes, goal.hero))
  276. missionImportanceData = ai->lockedHeroes[goal.hero]->priority;
  277. float strengthRatioData = 10.0f; //we are much stronger than enemy
  278. ui64 danger = evaluateDanger(goal.tile, goal.hero.h);
  279. if(danger)
  280. strengthRatioData = (fl::scalar)goal.hero.h->getTotalStrength() / danger;
  281. try
  282. {
  283. strengthRatio->setValue(strengthRatioData);
  284. heroStrength->setValue((fl::scalar)goal.hero->getTotalStrength() / ai->primaryHero()->getTotalStrength());
  285. turnDistance->setValue(turns);
  286. missionImportance->setValue(missionImportanceData);
  287. }
  288. catch(fl::Exception & fe)
  289. {
  290. logAi->error("HeroMovementGoalEngineBase::setSharedFuzzyVariables: %s", fe.getWhat());
  291. }
  292. }
  293. VisitObjEngine::VisitObjEngine()
  294. {
  295. try
  296. {
  297. objectValue = new fl::InputVariable("objectValue"); //value of that object type known by AI
  298. engine.addInputVariable(objectValue);
  299. //objectValue ranges are based on checking RMG priorities of some objects and trying to guess sane value ranges
  300. objectValue->addTerm(new fl::Ramp("LOW", 3000, 0)); //I have feeling that concave shape might work well instead of ramp for objectValue FL terms
  301. objectValue->addTerm(new fl::Triangle("MEDIUM", 2500, 6000));
  302. objectValue->addTerm(new fl::Ramp("HIGH", 5000, 20000));
  303. objectValue->setRange(0, 20000); //relic artifact value is border value by design, even better things are scaled down.
  304. addRule("if objectValue is HIGH then Value is HIGH");
  305. addRule("if objectValue is MEDIUM then Value is MEDIUM");
  306. addRule("if objectValue is LOW then Value is LOW");
  307. }
  308. catch(fl::Exception & fe)
  309. {
  310. logAi->error("FindWanderTarget: %s", fe.getWhat());
  311. }
  312. configure();
  313. }
  314. float VisitObjEngine::evaluate(Goals::VisitObj & goal)
  315. {
  316. if(!goal.hero)
  317. return 0;
  318. auto obj = ai->myCb->getObj(ObjectInstanceID(goal.objid));
  319. boost::optional<int> objValueKnownByAI = MapObjectsEvaluator::getInstance().getObjectValue(obj);
  320. int objValue = 0;
  321. if(objValueKnownByAI != boost::none) //consider adding value manipulation based on object instances on map
  322. {
  323. objValue = std::min(std::max(objValueKnownByAI.get(), 0), 20000);
  324. }
  325. else
  326. {
  327. MapObjectsEvaluator::getInstance().addObjectData(obj->ID, obj->subID, 0);
  328. 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));
  329. }
  330. setSharedFuzzyVariables(goal);
  331. float output = -1.0f;
  332. try
  333. {
  334. objectValue->setValue(objValue);
  335. engine.process();
  336. output = value->getValue();
  337. }
  338. catch(fl::Exception & fe)
  339. {
  340. logAi->error("evaluate getWanderTargetObjectValue: %s", fe.getWhat());
  341. }
  342. assert(output >= 0.0f);
  343. return output;
  344. }
  345. VisitTileEngine::VisitTileEngine() //so far no VisitTile-specific variables that are not shared with HeroMovementGoalEngineBase
  346. {
  347. configure();
  348. }
  349. float VisitTileEngine::evaluate(Goals::VisitTile & goal)
  350. {
  351. //we assume that hero is already set and we want to choose most suitable one for the mission
  352. if(!goal.hero)
  353. return 0;
  354. //assert(cb->isInTheMap(g.tile));
  355. setSharedFuzzyVariables(goal);
  356. try
  357. {
  358. engine.process();
  359. goal.priority = value->getValue();
  360. }
  361. catch(fl::Exception & fe)
  362. {
  363. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  364. }
  365. assert(goal.priority >= 0);
  366. return goal.priority;
  367. }