CModHandler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. tlog0 << "BIG WARNING: identifier " << ID << " seems to be broken!\n";
  26. else
  27. {
  28. size_t pos = 0;
  29. do
  30. {
  31. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  32. {
  33. tlog0 << "Warning: identifier " << ID << " is not in camelCase!\n";
  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. tlog2 << "incorrect primSkill name requested\n";
  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. BOOST_FOREACH(auto object, missingObjects)
  76. {
  77. tlog1 << "Error: object " << object.first << " was not found!\n";
  78. }
  79. assert(missingObjects.empty());
  80. }
  81. CModHandler::CModHandler()
  82. {
  83. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  84. {
  85. identifiers.registerObject("resource." + GameConstants::RESOURCE_NAMES[i], i);
  86. }
  87. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  88. identifiers.registerObject("primSkill." + PrimarySkill::names[i], i);
  89. loadConfigFromFile ("defaultMods");
  90. }
  91. void CModHandler::loadConfigFromFile (std::string name)
  92. {
  93. const JsonNode config(ResourceID("config/" + name + ".json"));
  94. const JsonNode & hardcodedFeatures = config["hardcodedFeatures"];
  95. settings.CREEP_SIZE = hardcodedFeatures["CREEP_SIZE"].Float();
  96. settings.WEEKLY_GROWTH = hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Float();
  97. settings.NEUTRAL_STACK_EXP = hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Float();
  98. settings.MAX_BUILDING_PER_TURN = hardcodedFeatures["MAX_BUILDING_PER_TURN"].Float();
  99. settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
  100. settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool();
  101. const JsonNode & gameModules = config["modules"];
  102. modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool();
  103. modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool();
  104. modules.COMMANDERS = gameModules["COMMANDERS"].Bool();
  105. modules.MITHRIL = gameModules["MITHRIL"].Bool();
  106. }
  107. // currentList is passed by value to get current list of depending mods
  108. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  109. {
  110. const CModInfo & mod = allMods.at(modID);
  111. // Mod already present? We found a loop
  112. if (vstd::contains(currentList, modID))
  113. {
  114. tlog0 << "Error: Circular dependency detected! Printing dependency list:\n";
  115. tlog0 << "\t" << mod.name << " -> \n";
  116. return true;
  117. }
  118. currentList.insert(modID);
  119. // recursively check every dependency of this mod
  120. BOOST_FOREACH(const TModID & dependency, mod.dependencies)
  121. {
  122. if (hasCircularDependency(dependency, currentList))
  123. {
  124. tlog0 << "\t" << mod.name << " ->\n"; // conflict detected, print dependency list
  125. return true;
  126. }
  127. }
  128. return false;
  129. }
  130. bool CModHandler::checkDependencies(const std::vector <TModID> & input) const
  131. {
  132. BOOST_FOREACH(const TModID & id, input)
  133. {
  134. const CModInfo & mod = allMods.at(id);
  135. BOOST_FOREACH(const TModID & dep, mod.dependencies)
  136. {
  137. if (!vstd::contains(input, dep))
  138. {
  139. tlog0 << "Error: Mod " << mod.name << " requires missing " << dep << "!\n";
  140. return false;
  141. }
  142. }
  143. BOOST_FOREACH(const TModID & conflicting, mod.conflicts)
  144. {
  145. if (vstd::contains(input, conflicting))
  146. {
  147. tlog0 << "Error: Mod " << mod.name << " conflicts with " << allMods.at(conflicting).name << "!\n";
  148. return false;
  149. }
  150. }
  151. if (hasCircularDependency(id))
  152. return false;
  153. }
  154. return true;
  155. }
  156. std::vector <TModID> CModHandler::resolveDependencies(std::vector <TModID> input) const
  157. {
  158. // Algorithm may not be the fastest one but VCMI does not needs any speed here
  159. // Unless user have dozens of mods with complex dependencies this cide should be fine
  160. std::vector <TModID> output;
  161. output.reserve(input.size());
  162. std::set <TModID> resolvedMods;
  163. // Check if all mod dependencies are resolved (moved to resolvedMods)
  164. auto isResolved = [&](const CModInfo mod) -> bool
  165. {
  166. BOOST_FOREACH(const TModID & dependency, mod.dependencies)
  167. {
  168. if (!vstd::contains(resolvedMods, dependency))
  169. return false;
  170. }
  171. return true;
  172. };
  173. while (!input.empty())
  174. {
  175. for (auto it = input.begin(); it != input.end();)
  176. {
  177. if (isResolved(allMods.at(*it)))
  178. {
  179. resolvedMods.insert(*it);
  180. output.push_back(*it);
  181. it = input.erase(it);
  182. continue;
  183. }
  184. it++;
  185. }
  186. }
  187. return output;
  188. }
  189. void CModHandler::initialize(std::vector<std::string> availableMods)
  190. {
  191. JsonNode modConfig(ResourceID("config/modSettings.json"));
  192. const JsonNode & modList = modConfig["activeMods"];
  193. JsonNode resultingList;
  194. std::vector <TModID> detectedMods;
  195. BOOST_FOREACH(std::string name, availableMods)
  196. {
  197. boost::to_lower(name);
  198. std::string modFileName = "mods/" + name + "/mod.json";
  199. if (CResourceHandler::get()->existsResource(ResourceID(modFileName)))
  200. {
  201. const JsonNode config = JsonNode(ResourceID(modFileName));
  202. if (config.isNull())
  203. continue;
  204. if (!modList[name].isNull() && modList[name].Bool() == false )
  205. {
  206. resultingList[name].Bool() = false;
  207. continue; // disabled mod
  208. }
  209. resultingList[name].Bool() = true;
  210. CModInfo & mod = allMods[name];
  211. mod.identifier = name;
  212. mod.name = config["name"].String();
  213. mod.description = config["description"].String();
  214. mod.dependencies = config["depends"].convertTo<std::set<std::string> >();
  215. mod.conflicts = config["conflicts"].convertTo<std::set<std::string> >();
  216. detectedMods.push_back(name);
  217. }
  218. else
  219. tlog3 << "\t\t Directory " << name << " does not contains VCMI mod\n";
  220. }
  221. if (!checkDependencies(detectedMods))
  222. {
  223. tlog0 << "Critical error: failed to load mods! Exiting...\n";
  224. exit(1);
  225. }
  226. activeMods = resolveDependencies(detectedMods);
  227. modConfig["activeMods"] = resultingList;
  228. CResourceHandler::get()->createResource("CONFIG/modSettings.json");
  229. std::ofstream file(CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::trunc);
  230. file << modConfig;
  231. }
  232. std::vector<std::string> CModHandler::getActiveMods()
  233. {
  234. return activeMods;
  235. }
  236. template<typename Handler>
  237. void handleData(Handler handler, const JsonNode & sourceList)
  238. {
  239. JsonNode config = JsonUtils::assembleFromFiles(sourceList.convertTo<std::vector<std::string> >());
  240. BOOST_FOREACH(auto & entry, config.Struct())
  241. {
  242. if (!entry.second.isNull()) // may happens if mod removed object by setting json entry to null
  243. {
  244. handler->load(entry.first, entry.second);
  245. }
  246. }
  247. }
  248. void CModHandler::loadActiveMods()
  249. {
  250. BOOST_FOREACH(const TModID & modName, activeMods)
  251. {
  252. tlog1 << "\t\tLoading mod ";
  253. tlog2 << allMods[modName].name << "\n";
  254. std::string modFileName = "mods/" + modName + "/mod.json";
  255. const JsonNode config = JsonNode(ResourceID(modFileName));
  256. handleData(VLC->townh, config["factions"]);
  257. handleData(VLC->creh, config["creatures"]);
  258. handleData(VLC->arth, config["artifacts"]);
  259. //todo: spells
  260. handleData(&VLC->heroh->classes, config["heroClasses"]);
  261. handleData(VLC->heroh, config["heroes"]);
  262. }
  263. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  264. identifiers.finalize();
  265. }
  266. void CModHandler::reload()
  267. {
  268. {
  269. //recreate adventure map defs
  270. assert(!VLC->dobjinfo->gobjs[Obj::MONSTER].empty()); //make sure that at least some def info was found
  271. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::MONSTER].begin()->second;
  272. BOOST_FOREACH(auto & crea, VLC->creh->creatures)
  273. {
  274. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::MONSTER], crea->idNumber)) // no obj info for this type
  275. {
  276. CGDefInfo * info = new CGDefInfo(*baseInfo);
  277. info->subid = crea->idNumber;
  278. info->name = crea->advMapDef;
  279. VLC->dobjinfo->gobjs[Obj::MONSTER][crea->idNumber] = info;
  280. }
  281. }
  282. }
  283. {
  284. assert(!VLC->dobjinfo->gobjs[Obj::ARTIFACT].empty());
  285. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::ARTIFACT].begin()->second;
  286. BOOST_FOREACH(auto & art, VLC->arth->artifacts)
  287. {
  288. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::ARTIFACT], art->id)) // no obj info for this type
  289. {
  290. CGDefInfo * info = new CGDefInfo(*baseInfo);
  291. info->subid = art->id;
  292. info->name = art->advMapDef;
  293. VLC->dobjinfo->gobjs[Obj::ARTIFACT][art->id] = info;
  294. }
  295. }
  296. }
  297. {
  298. assert(!VLC->dobjinfo->gobjs[Obj::TOWN].empty()); //make sure that at least some def info was found
  299. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::TOWN].begin()->second;
  300. auto & townInfos = VLC->dobjinfo->gobjs[Obj::TOWN];
  301. BOOST_FOREACH(auto & town, VLC->townh->towns)
  302. {
  303. auto & cientInfo = town.second.clientInfo;
  304. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::TOWN], town.first)) // no obj info for this type
  305. {
  306. CGDefInfo * info = new CGDefInfo(*baseInfo);
  307. info->subid = town.first;
  308. townInfos[town.first] = info;
  309. }
  310. townInfos[town.first]->name = cientInfo.advMapCastle;
  311. VLC->dobjinfo->villages[town.first] = new CGDefInfo(*townInfos[town.first]);
  312. VLC->dobjinfo->villages[town.first]->name = cientInfo.advMapVillage;
  313. VLC->dobjinfo->capitols[town.first] = new CGDefInfo(*townInfos[town.first]);
  314. VLC->dobjinfo->capitols[town.first]->name = cientInfo.advMapCapitol;
  315. for (int i = 0; i < town.second.dwellings.size(); ++i)
  316. {
  317. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::CREATURE_GENERATOR1][i]; //get same blockmap as first dwelling of tier i
  318. BOOST_FOREACH (auto cre, town.second.creatures[i]) //both unupgraded and upgraded get same dwelling
  319. {
  320. CGDefInfo * info = new CGDefInfo(*baseInfo);
  321. info->subid = cre;
  322. info->name = town.second.dwellings[i];
  323. VLC->dobjinfo->gobjs[Obj::CREATURE_GENERATOR1][cre] = info;
  324. VLC->objh->cregens[cre] = cre; //map of dwelling -> creature id
  325. }
  326. }
  327. }
  328. }
  329. }