CModHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. #include "StdInc.h"
  2. #include "CModHandler.h"
  3. #include "CDefObjInfoHandler.h"
  4. #include "JsonNode.h"
  5. #include "filesystem/CResourceLoader.h"
  6. #include "filesystem/ISimpleResourceLoader.h"
  7. #include "CCreatureHandler.h"
  8. #include "CArtHandler.h"
  9. #include "CTownHandler.h"
  10. #include "CHeroHandler.h"
  11. #include "CObjectHandler.h"
  12. #include "StringConstants.h"
  13. /*
  14. * CModHandler.cpp, part of VCMI engine
  15. *
  16. * Authors: listed in file AUTHORS in main folder
  17. *
  18. * License: GNU General Public License v2.0 or later
  19. * Full text of license available in license.txt file, in main folder
  20. *
  21. */
  22. void CIdentifierStorage::checkIdentifier(std::string & ID)
  23. {
  24. if (boost::algorithm::ends_with(ID, "."))
  25. logGlobal->warnStream() << "BIG WARNING: identifier " << ID << " seems to be broken!";
  26. else
  27. {
  28. size_t pos = 0;
  29. do
  30. {
  31. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  32. {
  33. logGlobal->warnStream() << "Warning: identifier " << ID << " is not in camelCase!";
  34. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  35. }
  36. pos = ID.find('.', pos);
  37. }
  38. while(pos++ != std::string::npos);
  39. }
  40. }
  41. void CIdentifierStorage::requestIdentifier(std::string name, const boost::function<void(si32)> & callback)
  42. {
  43. checkIdentifier(name);
  44. auto iter = registeredObjects.find(name);
  45. if (iter != registeredObjects.end())
  46. callback(iter->second); //already registered - trigger callback immediately
  47. else
  48. {
  49. if(boost::algorithm::starts_with(name, "primSkill."))
  50. logGlobal->warnStream() << "incorrect primSkill name requested";
  51. missingObjects[name].push_back(callback); // queue callback
  52. }
  53. }
  54. void CIdentifierStorage::registerObject(std::string name, si32 identifier)
  55. {
  56. checkIdentifier(name);
  57. // do not allow to register same object twice
  58. assert(registeredObjects.find(name) == registeredObjects.end());
  59. registeredObjects[name] = identifier;
  60. auto iter = missingObjects.find(name);
  61. if (iter != missingObjects.end())
  62. {
  63. //call all awaiting callbacks
  64. BOOST_FOREACH(auto function, iter->second)
  65. {
  66. function(identifier);
  67. }
  68. missingObjects.erase(iter);
  69. }
  70. }
  71. void CIdentifierStorage::finalize() const
  72. {
  73. // print list of missing objects and crash
  74. // in future should try to do some cleanup (like returning all id's as 0)
  75. if (!missingObjects.empty())
  76. {
  77. BOOST_FOREACH(auto object, missingObjects)
  78. {
  79. logGlobal->errorStream() << "Error: object " << object.first << " was not found!";
  80. }
  81. BOOST_FOREACH(auto object, registeredObjects)
  82. {
  83. logGlobal->traceStream() << object.first << " -> " << object.second;
  84. }
  85. logGlobal->errorStream() << "All known identifiers were dumped into log file";
  86. }
  87. assert(missingObjects.empty());
  88. }
  89. CModHandler::CModHandler()
  90. {
  91. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  92. {
  93. identifiers.registerObject("resource." + GameConstants::RESOURCE_NAMES[i], i);
  94. }
  95. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  96. identifiers.registerObject("primSkill." + PrimarySkill::names[i], i);
  97. loadConfigFromFile ("defaultMods");
  98. }
  99. void CModHandler::loadConfigFromFile (std::string name)
  100. {
  101. const JsonNode config(ResourceID("config/" + name + ".json"));
  102. const JsonNode & hardcodedFeatures = config["hardcodedFeatures"];
  103. settings.CREEP_SIZE = hardcodedFeatures["CREEP_SIZE"].Float();
  104. settings.WEEKLY_GROWTH = hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Float();
  105. settings.NEUTRAL_STACK_EXP = hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Float();
  106. settings.MAX_BUILDING_PER_TURN = hardcodedFeatures["MAX_BUILDING_PER_TURN"].Float();
  107. settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
  108. settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool();
  109. const JsonNode & gameModules = config["modules"];
  110. modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool();
  111. modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool();
  112. modules.COMMANDERS = gameModules["COMMANDERS"].Bool();
  113. modules.MITHRIL = gameModules["MITHRIL"].Bool();
  114. }
  115. // currentList is passed by value to get current list of depending mods
  116. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  117. {
  118. const CModInfo & mod = allMods.at(modID);
  119. // Mod already present? We found a loop
  120. if (vstd::contains(currentList, modID))
  121. {
  122. logGlobal->errorStream() << "Error: Circular dependency detected! Printing dependency list:";
  123. logGlobal->errorStream() << "\t" << mod.name << " -> ";
  124. return true;
  125. }
  126. currentList.insert(modID);
  127. // recursively check every dependency of this mod
  128. BOOST_FOREACH(const TModID & dependency, mod.dependencies)
  129. {
  130. if (hasCircularDependency(dependency, currentList))
  131. {
  132. logGlobal->errorStream() << "\t" << mod.name << " ->\n"; // conflict detected, print dependency list
  133. return true;
  134. }
  135. }
  136. return false;
  137. }
  138. bool CModHandler::checkDependencies(const std::vector <TModID> & input) const
  139. {
  140. BOOST_FOREACH(const TModID & id, input)
  141. {
  142. const CModInfo & mod = allMods.at(id);
  143. BOOST_FOREACH(const TModID & dep, mod.dependencies)
  144. {
  145. if (!vstd::contains(input, dep))
  146. {
  147. logGlobal->errorStream() << "Error: Mod " << mod.name << " requires missing " << dep << "!";
  148. return false;
  149. }
  150. }
  151. BOOST_FOREACH(const TModID & conflicting, mod.conflicts)
  152. {
  153. if (vstd::contains(input, conflicting))
  154. {
  155. logGlobal->errorStream() << "Error: Mod " << mod.name << " conflicts with " << allMods.at(conflicting).name << "!";
  156. return false;
  157. }
  158. }
  159. if (hasCircularDependency(id))
  160. return false;
  161. }
  162. return true;
  163. }
  164. std::vector <TModID> CModHandler::resolveDependencies(std::vector <TModID> input) const
  165. {
  166. // Algorithm may not be the fastest one but VCMI does not needs any speed here
  167. // Unless user have dozens of mods with complex dependencies this cide should be fine
  168. std::vector <TModID> output;
  169. output.reserve(input.size());
  170. std::set <TModID> resolvedMods;
  171. // Check if all mod dependencies are resolved (moved to resolvedMods)
  172. auto isResolved = [&](const CModInfo mod) -> bool
  173. {
  174. BOOST_FOREACH(const TModID & dependency, mod.dependencies)
  175. {
  176. if (!vstd::contains(resolvedMods, dependency))
  177. return false;
  178. }
  179. return true;
  180. };
  181. while (!input.empty())
  182. {
  183. for (auto it = input.begin(); it != input.end();)
  184. {
  185. if (isResolved(allMods.at(*it)))
  186. {
  187. resolvedMods.insert(*it);
  188. output.push_back(*it);
  189. it = input.erase(it);
  190. continue;
  191. }
  192. it++;
  193. }
  194. }
  195. return output;
  196. }
  197. void CModHandler::initialize(std::vector<std::string> availableMods)
  198. {
  199. std::string confName = "config/modSettings.json";
  200. JsonNode modConfig;
  201. // Porbably new install. Create initial configuration
  202. if (!CResourceHandler::get()->existsResource(ResourceID(confName)))
  203. CResourceHandler::get()->createResource(confName);
  204. else
  205. modConfig = JsonNode(ResourceID(confName));
  206. CResourceHandler::get()->createResource("config/modSettings.json");
  207. const JsonNode & modList = modConfig["activeMods"];
  208. JsonNode resultingList;
  209. std::vector <TModID> detectedMods;
  210. BOOST_FOREACH(std::string name, availableMods)
  211. {
  212. boost::to_lower(name);
  213. std::string modFileName = "mods/" + name + "/mod.json";
  214. if (CResourceHandler::get()->existsResource(ResourceID(modFileName)))
  215. {
  216. const JsonNode config = JsonNode(ResourceID(modFileName));
  217. if (config.isNull())
  218. continue;
  219. if (!modList[name].isNull() && modList[name].Bool() == false )
  220. {
  221. resultingList[name].Bool() = false;
  222. continue; // disabled mod
  223. }
  224. resultingList[name].Bool() = true;
  225. CModInfo & mod = allMods[name];
  226. mod.identifier = name;
  227. mod.name = config["name"].String();
  228. mod.description = config["description"].String();
  229. mod.dependencies = config["depends"].convertTo<std::set<std::string> >();
  230. mod.conflicts = config["conflicts"].convertTo<std::set<std::string> >();
  231. detectedMods.push_back(name);
  232. }
  233. else
  234. logGlobal->warnStream() << "\t\t Directory " << name << " does not contains VCMI mod";
  235. }
  236. if (!checkDependencies(detectedMods))
  237. {
  238. logGlobal->errorStream() << "Critical error: failed to load mods! Exiting...";
  239. exit(1);
  240. }
  241. activeMods = resolveDependencies(detectedMods);
  242. modConfig["activeMods"] = resultingList;
  243. CResourceHandler::get()->createResource("CONFIG/modSettings.json");
  244. std::ofstream file(CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::trunc);
  245. file << modConfig;
  246. }
  247. std::vector<std::string> CModHandler::getActiveMods()
  248. {
  249. return activeMods;
  250. }
  251. template<typename Handler>
  252. void CModHandler::handleData(Handler handler, const JsonNode & source, std::string listName, std::string schemaName)
  253. {
  254. JsonNode config = JsonUtils::assembleFromFiles(source[listName].convertTo<std::vector<std::string> >());
  255. BOOST_FOREACH(auto & entry, config.Struct())
  256. {
  257. if (!entry.second.isNull()) // may happens if mod removed object by setting json entry to null
  258. {
  259. JsonUtils::validate(entry.second, schemaName, entry.first);
  260. handler->load(entry.first, entry.second);
  261. }
  262. }
  263. }
  264. void CModHandler::loadActiveMods()
  265. {
  266. BOOST_FOREACH(const TModID & modName, activeMods)
  267. {
  268. logGlobal->infoStream() << "\t\tLoading mod " << allMods[modName].name;
  269. std::string modFileName = "mods/" + modName + "/mod.json";
  270. const JsonNode config = JsonNode(ResourceID(modFileName));
  271. JsonUtils::validate(config, "vcmi:mod", modName);
  272. handleData(VLC->townh, config, "factions", "vcmi:faction");
  273. handleData(VLC->creh, config, "creatures", "vcmi:creature");
  274. handleData(VLC->arth, config, "artifacts", "vcmi:artifact");
  275. //todo: spells
  276. handleData(&VLC->heroh->classes, config,"heroClasses", "vcmi:heroClass");
  277. handleData(VLC->heroh, config, "heroes", "vcmi:hero");
  278. }
  279. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  280. identifiers.finalize();
  281. }
  282. void CModHandler::reload()
  283. {
  284. {
  285. //recreate adventure map defs
  286. assert(!VLC->dobjinfo->gobjs[Obj::MONSTER].empty()); //make sure that at least some def info was found
  287. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::MONSTER].begin()->second;
  288. BOOST_FOREACH(auto & crea, VLC->creh->creatures)
  289. {
  290. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::MONSTER], crea->idNumber)) // no obj info for this type
  291. {
  292. CGDefInfo * info = new CGDefInfo(*baseInfo);
  293. info->subid = crea->idNumber;
  294. info->name = crea->advMapDef;
  295. VLC->dobjinfo->gobjs[Obj::MONSTER][crea->idNumber] = info;
  296. }
  297. }
  298. }
  299. {
  300. assert(!VLC->dobjinfo->gobjs[Obj::ARTIFACT].empty());
  301. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::ARTIFACT].begin()->second;
  302. BOOST_FOREACH(auto & art, VLC->arth->artifacts)
  303. {
  304. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::ARTIFACT], art->id)) // no obj info for this type
  305. {
  306. CGDefInfo * info = new CGDefInfo(*baseInfo);
  307. info->subid = art->id;
  308. info->name = art->advMapDef;
  309. VLC->dobjinfo->gobjs[Obj::ARTIFACT][art->id] = info;
  310. }
  311. }
  312. }
  313. {
  314. assert(!VLC->dobjinfo->gobjs[Obj::TOWN].empty()); //make sure that at least some def info was found
  315. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::TOWN].begin()->second;
  316. auto & townInfos = VLC->dobjinfo->gobjs[Obj::TOWN];
  317. BOOST_FOREACH(auto & town, VLC->townh->towns)
  318. {
  319. auto & cientInfo = town.second.clientInfo;
  320. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::TOWN], town.first)) // no obj info for this type
  321. {
  322. CGDefInfo * info = new CGDefInfo(*baseInfo);
  323. info->subid = town.first;
  324. townInfos[town.first] = info;
  325. }
  326. townInfos[town.first]->name = cientInfo.advMapCastle;
  327. VLC->dobjinfo->villages[town.first] = new CGDefInfo(*townInfos[town.first]);
  328. VLC->dobjinfo->villages[town.first]->name = cientInfo.advMapVillage;
  329. VLC->dobjinfo->capitols[town.first] = new CGDefInfo(*townInfos[town.first]);
  330. VLC->dobjinfo->capitols[town.first]->name = cientInfo.advMapCapitol;
  331. for (int i = 0; i < town.second.dwellings.size(); ++i)
  332. {
  333. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::CREATURE_GENERATOR1][i]; //get same blockmap as first dwelling of tier i
  334. BOOST_FOREACH (auto cre, town.second.creatures[i]) //both unupgraded and upgraded get same dwelling
  335. {
  336. CGDefInfo * info = new CGDefInfo(*baseInfo);
  337. info->subid = cre;
  338. info->name = town.second.dwellings[i];
  339. VLC->dobjinfo->gobjs[Obj::CREATURE_GENERATOR1][cre] = info;
  340. VLC->objh->cregens[cre] = cre; //map of dwelling -> creature id
  341. }
  342. }
  343. }
  344. }
  345. }