router.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /*
  2. * router.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 "callback/CBattleCallback.h"
  12. #include "callback/CDynLibHandler.h"
  13. #include "callback/IGameInfoCallback.h"
  14. #include "filesystem/Filesystem.h"
  15. #include "json/JsonUtils.h"
  16. #include "BAI/base.h"
  17. #include "BAI/model/NNModel.h"
  18. #include "BAI/model/ScriptedModel.h"
  19. #include "BAI/router.h"
  20. #include "common.h"
  21. #include <utility>
  22. namespace MMAI::BAI
  23. {
  24. using ConfigStorage = std::map<std::string, std::string>;
  25. using ModelStorage = std::map<std::string, std::unique_ptr<NNModel>>;
  26. namespace
  27. {
  28. struct ModelRepository
  29. {
  30. ModelStorage models;
  31. float temperature = 1.0;
  32. uint64_t seed = 0;
  33. std::unique_ptr<ScriptedModel> fallbackModel;
  34. std::string fallbackName;
  35. };
  36. std::unique_ptr<ModelRepository> InitModelRepository()
  37. {
  38. auto repo = std::make_unique<ModelRepository>();
  39. auto json = JsonUtils::assembleFromFiles("MMAI/CONFIG/mmai-settings.json");
  40. if(!json.isStruct())
  41. {
  42. logAi->error("Could not load MMAI config. Is MMAI mod enabled?");
  43. return repo;
  44. }
  45. JsonUtils::validate(json, "vcmi:mmaiSettings", "mmai");
  46. repo->temperature = static_cast<float>(json["temperature"].Float());
  47. repo->seed = json["seed"].Integer();
  48. for(const std::string key : {"attacker", "defender"})
  49. {
  50. std::string path = "MMAI/models/" + json["models"][key].String();
  51. // Try loading dynamic models with priority
  52. // (temporary code for a smooth migration path)
  53. const auto pos = path.rfind(".onnx");
  54. if(pos != std::string::npos)
  55. {
  56. std::string dynpath = path;
  57. dynpath.insert(pos, "-dynamic"); // insert right before ".onnx"
  58. const auto rpath = ResourcePath(dynpath, EResType::AI_MODEL);
  59. const auto * rhandler = CResourceHandler::get();
  60. if(rhandler->existsResource(rpath))
  61. path = dynpath;
  62. }
  63. logAi->debug("MMAI: Loading NN %s model from: %s", key, path);
  64. try
  65. {
  66. repo->models.try_emplace(key, std::make_unique<NNModel>(path, repo->temperature, repo->seed));
  67. }
  68. catch(std::exception & e)
  69. {
  70. logAi->error("MMAI: error loading " + key + ": " + std::string(e.what()));
  71. }
  72. }
  73. auto fallback = json["fallback"].String();
  74. logAi->debug("MMAI: preparing fallback model: %s", fallback);
  75. repo->fallbackModel = std::make_unique<ScriptedModel>(fallback);
  76. repo->fallbackName = fallback;
  77. return repo;
  78. }
  79. Schema::IModel * GetModel(const std::string & key)
  80. {
  81. static const auto MODEL_REPO = InitModelRepository();
  82. auto it = MODEL_REPO->models.find(key);
  83. if(it == MODEL_REPO->models.end())
  84. {
  85. logAi->error("MMAI: no %s model loaded, trying fallback: %s", key, MODEL_REPO->fallbackName);
  86. ASSERT(MODEL_REPO->fallbackModel, "fallback failed: model is null");
  87. return MODEL_REPO->fallbackModel.get();
  88. }
  89. return it->second.get();
  90. }
  91. }
  92. Router::Router()
  93. {
  94. std::ostringstream oss;
  95. // Store the memory address and include it in logging
  96. const auto * ptr = static_cast<const void *>(this);
  97. oss << ptr;
  98. addrstr = oss.str();
  99. info("+++ constructor +++"); // log after addrstr is set
  100. }
  101. Router::~Router()
  102. {
  103. info("--- destructor ---");
  104. cb->waitTillRealize = wasWaitingForRealize;
  105. }
  106. void Router::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB)
  107. {
  108. info("*** initBattleInterface ***");
  109. env = ENV;
  110. cb = CB;
  111. colorname = cb->getPlayerID()->toString();
  112. wasWaitingForRealize = cb->waitTillRealize;
  113. cb->waitTillRealize = false;
  114. bai.reset();
  115. }
  116. void Router::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB, AutocombatPreferences prefs)
  117. {
  118. autocombatPreferences = prefs;
  119. initBattleInterface(ENV, CB);
  120. }
  121. /*
  122. * Delegated methods
  123. */
  124. void Router::actionFinished(const BattleID & bid, const BattleAction & action)
  125. {
  126. bai->actionFinished(bid, action);
  127. }
  128. void Router::actionStarted(const BattleID & bid, const BattleAction & action)
  129. {
  130. bai->actionStarted(bid, action);
  131. }
  132. void Router::activeStack(const BattleID & bid, const CStack * astack)
  133. {
  134. bai->activeStack(bid, astack);
  135. }
  136. void Router::battleAttack(const BattleID & bid, const BattleAttack * ba)
  137. {
  138. bai->battleAttack(bid, ba);
  139. }
  140. void Router::battleCatapultAttacked(const BattleID & bid, const CatapultAttack & ca)
  141. {
  142. bai->battleCatapultAttacked(bid, ca);
  143. }
  144. void Router::battleEnd(const BattleID & bid, const BattleResult * br, QueryID queryID)
  145. {
  146. bai->battleEnd(bid, br, queryID);
  147. }
  148. void Router::battleGateStateChanged(const BattleID & bid, const EGateState state)
  149. {
  150. bai->battleGateStateChanged(bid, state);
  151. };
  152. void Router::battleLogMessage(const BattleID & bid, const std::vector<MetaString> & lines)
  153. {
  154. bai->battleLogMessage(bid, lines);
  155. };
  156. void Router::battleNewRound(const BattleID & bid)
  157. {
  158. bai->battleNewRound(bid);
  159. }
  160. void Router::battleNewRoundFirst(const BattleID & bid)
  161. {
  162. bai->battleNewRoundFirst(bid);
  163. }
  164. void Router::battleObstaclesChanged(const BattleID & bid, const std::vector<ObstacleChanges> & obstacles)
  165. {
  166. bai->battleObstaclesChanged(bid, obstacles);
  167. };
  168. void Router::battleSpellCast(const BattleID & bid, const BattleSpellCast * sc)
  169. {
  170. bai->battleSpellCast(bid, sc);
  171. }
  172. void Router::battleStackMoved(const BattleID & bid, const CStack * stack, const BattleHexArray & dest, int distance, bool teleport)
  173. {
  174. bai->battleStackMoved(bid, stack, dest, distance, teleport);
  175. }
  176. void Router::battleStacksAttacked(const BattleID & bid, const std::vector<BattleStackAttacked> & bsa, bool ranged)
  177. {
  178. bai->battleStacksAttacked(bid, bsa, ranged);
  179. }
  180. void Router::battleStacksEffectsSet(const BattleID & bid, const SetStackEffect & sse)
  181. {
  182. bai->battleStacksEffectsSet(bid, sse);
  183. }
  184. void Router::battleStart(
  185. const BattleID & bid,
  186. const CCreatureSet * army1,
  187. const CCreatureSet * army2,
  188. int3 tile,
  189. const CGHeroInstance * hero1,
  190. const CGHeroInstance * hero2,
  191. BattleSide side,
  192. bool replayAllowed
  193. )
  194. {
  195. Schema::IModel * model;
  196. const std::string modelkey = side == BattleSide::ATTACKER ? "attacker" : "defender";
  197. model = GetModel(modelkey);
  198. auto modelside = model->getSide();
  199. auto realside = static_cast<Schema::Side>(EI(side));
  200. if(modelside != realside && modelside != Schema::Side::BOTH)
  201. logAi->warn("The loaded '%s' model was not trained to play as %s", modelkey, modelkey);
  202. switch(model->getType())
  203. {
  204. case Schema::ModelType::SCRIPTED:
  205. if(model->getName() == "StupidAI")
  206. {
  207. bai = CDynLibHandler::getNewBattleAI("StupidAI");
  208. bai->initBattleInterface(env, cb, autocombatPreferences);
  209. }
  210. else if(model->getName() == "BattleAI")
  211. {
  212. bai = CDynLibHandler::getNewBattleAI("BattleAI");
  213. bai->initBattleInterface(env, cb, autocombatPreferences);
  214. }
  215. else
  216. {
  217. THROW_FORMAT("Unexpected scripted model name: %s", model->getName());
  218. }
  219. break;
  220. case Schema::ModelType::NN:
  221. // XXX: must not call initBattleInterface here
  222. bai = Base::Create(model, env, cb, autocombatPreferences.enableSpellsUsage);
  223. break;
  224. default:
  225. THROW_FORMAT("Unexpected model type: %d", EI(model->getType()));
  226. }
  227. bai->battleStart(bid, army1, army2, tile, hero1, hero2, side, replayAllowed);
  228. }
  229. void Router::battleTriggerEffect(const BattleID & bid, const BattleTriggerEffect & bte)
  230. {
  231. bai->battleTriggerEffect(bid, bte);
  232. }
  233. void Router::battleUnitsChanged(const BattleID & bid, const std::vector<UnitChanges> & changes)
  234. {
  235. bai->battleUnitsChanged(bid, changes);
  236. }
  237. void Router::yourTacticPhase(const BattleID & bid, int distance)
  238. {
  239. bai->yourTacticPhase(bid, distance);
  240. }
  241. /*
  242. * private
  243. */
  244. void Router::error(const std::string & text) const
  245. {
  246. log(ELogLevel::ERROR, text);
  247. }
  248. void Router::warn(const std::string & text) const
  249. {
  250. log(ELogLevel::WARN, text);
  251. }
  252. void Router::info(const std::string & text) const
  253. {
  254. log(ELogLevel::INFO, text);
  255. }
  256. void Router::debug(const std::string & text) const
  257. {
  258. log(ELogLevel::DEBUG, text);
  259. }
  260. void Router::trace(const std::string & text) const
  261. {
  262. log(ELogLevel::TRACE, text);
  263. }
  264. void Router::log(ELogLevel::ELogLevel level, const std::string & text) const
  265. {
  266. if(logAi->getEffectiveLevel() <= level)
  267. logAi->debug("Router-%s [%s] %s", addrstr, colorname, text);
  268. }
  269. }