CModHandler.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. #include "StdInc.h"
  2. #include "CModHandler.h"
  3. #include "CDefObjInfoHandler.h"
  4. #include "JsonNode.h"
  5. #include "filesystem/Filesystem.h"
  6. #include "CCreatureHandler.h"
  7. #include "CArtHandler.h"
  8. #include "CTownHandler.h"
  9. #include "CHeroHandler.h"
  10. #include "CObjectHandler.h"
  11. #include "StringConstants.h"
  12. #include "CStopWatch.h"
  13. #include "IHandlerBase.h"
  14. /*
  15. * CModHandler.cpp, part of VCMI engine
  16. *
  17. * Authors: listed in file AUTHORS in main folder
  18. *
  19. * License: GNU General Public License v2.0 or later
  20. * Full text of license available in license.txt file, in main folder
  21. *
  22. */
  23. void CIdentifierStorage::checkIdentifier(std::string & ID)
  24. {
  25. if (boost::algorithm::ends_with(ID, "."))
  26. logGlobal->warnStream() << "BIG WARNING: identifier " << ID << " seems to be broken!";
  27. else
  28. {
  29. size_t pos = 0;
  30. do
  31. {
  32. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  33. {
  34. logGlobal->warnStream() << "Warning: identifier " << ID << " is not in camelCase!";
  35. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  36. }
  37. pos = ID.find('.', pos);
  38. }
  39. while(pos++ != std::string::npos);
  40. }
  41. }
  42. CIdentifierStorage::ObjectCallback::ObjectCallback(std::string localScope, std::string remoteScope, std::string type,
  43. std::string name, const std::function<void(si32)> & callback):
  44. localScope(localScope),
  45. remoteScope(remoteScope),
  46. type(type),
  47. name(name),
  48. callback(callback)
  49. {}
  50. static std::pair<std::string, std::string> splitString(std::string input, char separator)
  51. {
  52. std::pair<std::string, std::string> ret;
  53. size_t splitPos = input.find(separator);
  54. if (splitPos == std::string::npos)
  55. {
  56. ret.first.clear();
  57. ret.second = input;
  58. }
  59. else
  60. {
  61. ret.first = input.substr(0, splitPos);
  62. ret.second = input.substr(splitPos + 1);
  63. }
  64. return ret;
  65. }
  66. void CIdentifierStorage::requestIdentifier(ObjectCallback callback)
  67. {
  68. checkIdentifier(callback.type);
  69. checkIdentifier(callback.name);
  70. assert(!callback.localScope.empty());
  71. scheduledRequests.push_back(callback);
  72. }
  73. void CIdentifierStorage::requestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  74. {
  75. auto pair = splitString(name, ':'); // remoteScope:name
  76. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback));
  77. }
  78. void CIdentifierStorage::requestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  79. {
  80. auto pair = splitString(name.String(), ':'); // remoteScope:name
  81. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback));
  82. }
  83. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback)
  84. {
  85. auto pair = splitString(name.String(), ':'); // remoteScope:<type.name>
  86. auto pair2 = splitString(pair.second, '.'); // type.name
  87. requestIdentifier(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, callback));
  88. }
  89. void CIdentifierStorage::registerObject(std::string scope, std::string type, std::string name, si32 identifier)
  90. {
  91. ObjectData data;
  92. data.scope = scope;
  93. data.id = identifier;
  94. std::string fullID = type + '.' + name;
  95. checkIdentifier(fullID);
  96. registeredObjects.insert(std::make_pair(fullID, data));
  97. }
  98. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request)
  99. {
  100. std::set<std::string> allowedScopes;
  101. if (request.remoteScope.empty())
  102. {
  103. // normally ID's from all required mods, own mod and virtual "core" mod are allowed
  104. if (request.localScope != "core")
  105. allowedScopes = VLC->modh->getModData(request.localScope).dependencies;
  106. allowedScopes.insert(request.localScope);
  107. allowedScopes.insert("core");
  108. }
  109. else
  110. {
  111. //...unless destination mod was specified explicitly
  112. auto myDeps = VLC->modh->getModData(request.localScope).dependencies;
  113. if (request.remoteScope == "core" || // allow only available to all core mod
  114. myDeps.count(request.remoteScope)) // or dependencies
  115. allowedScopes.insert(request.remoteScope);
  116. }
  117. std::string fullID = request.type + '.' + request.name;
  118. auto entries = registeredObjects.equal_range(fullID);
  119. if (entries.first != entries.second)
  120. {
  121. size_t matchesFound = 0;
  122. for (auto it = entries.first; it != entries.second; it++)
  123. {
  124. if (vstd::contains(allowedScopes, it->second.scope))
  125. {
  126. if (matchesFound == 0) // trigger only once
  127. request.callback(it->second.id);
  128. matchesFound++;
  129. }
  130. }
  131. if (matchesFound == 1)
  132. return true; // success, only one matching ID
  133. // error found. Try to generate some debug info
  134. if (matchesFound == 0)
  135. logGlobal->errorStream() << "Unknown identifier!";
  136. else
  137. logGlobal->errorStream() << "Ambiguous identifier request!";
  138. logGlobal->errorStream() << "Request for " << request.type << "." << request.name << " from mod " << request.localScope;
  139. for (auto it = entries.first; it != entries.second; it++)
  140. {
  141. logGlobal->errorStream() << "\tID is available in mod " << it->second.scope;
  142. }
  143. }
  144. logGlobal->errorStream() << "Unknown identifier " << request.type << "." << request.name << " from mod " << request.localScope;
  145. return false;
  146. }
  147. void CIdentifierStorage::finalize()
  148. {
  149. bool errorsFound = false;
  150. for(const ObjectCallback & request : scheduledRequests)
  151. {
  152. errorsFound |= !resolveIdentifier(request);
  153. }
  154. if (errorsFound)
  155. {
  156. for(auto object : registeredObjects)
  157. {
  158. logGlobal->traceStream() << object.first << " -> " << object.second.id;
  159. }
  160. logGlobal->errorStream() << "All known identifiers were dumped into log file";
  161. }
  162. assert(errorsFound == false);
  163. }
  164. CContentHandler::ContentTypeHandler::ContentTypeHandler(IHandlerBase * handler, std::string objectName):
  165. handler(handler),
  166. objectName(objectName),
  167. originalData(handler->loadLegacyData(VLC->modh->settings.data["textData"][objectName].Float()))
  168. {
  169. for(auto & node : originalData)
  170. {
  171. node.setMeta("core");
  172. }
  173. }
  174. bool CContentHandler::ContentTypeHandler::preloadModData(std::string modName, std::vector<std::string> fileList, bool validate)
  175. {
  176. bool result;
  177. JsonNode data = JsonUtils::assembleFromFiles(fileList, result);
  178. data.setMeta(modName);
  179. ModInfo & modInfo = modData[modName];
  180. for(auto entry : data.Struct())
  181. {
  182. size_t colon = entry.first.find(':');
  183. if (colon == std::string::npos)
  184. {
  185. // normal object, local to this mod
  186. modInfo.modData[entry.first].swap(entry.second);
  187. }
  188. else
  189. {
  190. std::string remoteName = entry.first.substr(0, colon);
  191. std::string objectName = entry.first.substr(colon + 1);
  192. // patching this mod? Send warning and continue - this situation can be handled normally
  193. if (remoteName == modName)
  194. logGlobal->warnStream() << "Redundant namespace definition for " << objectName;
  195. JsonNode & remoteConf = modData[remoteName].patches[objectName];
  196. JsonUtils::merge(remoteConf, entry.second);
  197. }
  198. }
  199. return result;
  200. }
  201. bool CContentHandler::ContentTypeHandler::loadMod(std::string modName, bool validate)
  202. {
  203. ModInfo & modInfo = modData[modName];
  204. bool result = true;
  205. // apply patches
  206. if (!modInfo.patches.isNull())
  207. JsonUtils::merge(modInfo.modData, modInfo.patches);
  208. for(auto entry : modInfo.modData.Struct())
  209. {
  210. const std::string & name = entry.first;
  211. JsonNode & data = entry.second;
  212. if (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
  213. {
  214. // try to add H3 object data
  215. size_t index = data["index"].Float();
  216. if (originalData.size() > index)
  217. {
  218. JsonUtils::merge(originalData[index], data);
  219. if (validate)
  220. result &= JsonUtils::validate(originalData[index], "vcmi:" + objectName, name);
  221. handler->loadObject(modName, name, originalData[index], index);
  222. originalData[index].clear(); // do not use same data twice (same ID)
  223. continue;
  224. }
  225. }
  226. // normal new object or one with index bigger that data size
  227. if (validate)
  228. result &= JsonUtils::validate(data, "vcmi:" + objectName, name);
  229. handler->loadObject(modName, name, data);
  230. }
  231. return result;
  232. }
  233. void CContentHandler::ContentTypeHandler::afterLoadFinalization()
  234. {
  235. handler->afterLoadFinalization();
  236. }
  237. CContentHandler::CContentHandler()
  238. {
  239. handlers.insert(std::make_pair("heroClasses", ContentTypeHandler(&VLC->heroh->classes, "heroClass")));
  240. handlers.insert(std::make_pair("artifacts", ContentTypeHandler(VLC->arth, "artifact")));
  241. handlers.insert(std::make_pair("creatures", ContentTypeHandler(VLC->creh, "creature")));
  242. handlers.insert(std::make_pair("factions", ContentTypeHandler(VLC->townh, "faction")));
  243. handlers.insert(std::make_pair("heroes", ContentTypeHandler(VLC->heroh, "hero")));
  244. //TODO: spells, bonuses, something else?
  245. }
  246. bool CContentHandler::preloadModData(std::string modName, JsonNode modConfig, bool validate)
  247. {
  248. bool result = true;
  249. for(auto & handler : handlers)
  250. {
  251. result &= handler.second.preloadModData(modName, modConfig[handler.first].convertTo<std::vector<std::string> >(), validate);
  252. }
  253. return result;
  254. }
  255. bool CContentHandler::loadMod(std::string modName, bool validate)
  256. {
  257. bool result = true;
  258. for(auto & handler : handlers)
  259. {
  260. result &= handler.second.loadMod(modName, validate);
  261. }
  262. return result;
  263. }
  264. void CContentHandler::afterLoadFinalization()
  265. {
  266. for(auto & handler : handlers)
  267. {
  268. handler.second.afterLoadFinalization();
  269. }
  270. }
  271. void CContentHandler::preloadData(CModInfo & mod)
  272. {
  273. bool validate = (mod.validation != CModInfo::PASSED);
  274. // print message in format [<8-symbols checksum>] <modname>
  275. logGlobal->infoStream() << "\t\t[" << std::noshowbase << std::hex << std::setw(8) << std::setfill('0')
  276. << mod.checksum << "] " << mod.name;
  277. if (validate && mod.identifier != "core")
  278. {
  279. if (!JsonUtils::validate(mod.config, "vcmi:mod", mod.identifier))
  280. mod.validation = CModInfo::FAILED;
  281. }
  282. if (!preloadModData(mod.identifier, mod.config, validate))
  283. mod.validation = CModInfo::FAILED;
  284. }
  285. void CContentHandler::load(CModInfo & mod)
  286. {
  287. bool validate = (mod.validation != CModInfo::PASSED);
  288. if (!loadMod(mod.identifier, validate))
  289. mod.validation = CModInfo::FAILED;
  290. if (validate)
  291. {
  292. if (mod.validation != CModInfo::FAILED)
  293. logGlobal->infoStream() << "\t\t[DONE] " << mod.name;
  294. else
  295. logGlobal->errorStream() << "\t\t[FAIL] " << mod.name;
  296. }
  297. else
  298. logGlobal->infoStream() << "\t\t[SKIP] " << mod.name;
  299. }
  300. CModHandler::CModHandler()
  301. {
  302. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  303. {
  304. identifiers.registerObject("core", "resource", GameConstants::RESOURCE_NAMES[i], i);
  305. }
  306. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  307. identifiers.registerObject("core", "primSkill", PrimarySkill::names[i], i);
  308. }
  309. void CModHandler::loadConfigFromFile (std::string name)
  310. {
  311. settings.data = JsonUtils::assembleFromFiles("config/" + name);
  312. const JsonNode & hardcodedFeatures = settings.data["hardcodedFeatures"];
  313. settings.CREEP_SIZE = hardcodedFeatures["CREEP_SIZE"].Float();
  314. settings.WEEKLY_GROWTH = hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Float();
  315. settings.NEUTRAL_STACK_EXP = hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Float();
  316. settings.MAX_BUILDING_PER_TURN = hardcodedFeatures["MAX_BUILDING_PER_TURN"].Float();
  317. settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
  318. settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool();
  319. const JsonNode & gameModules = settings.data["modules"];
  320. modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool();
  321. modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool();
  322. modules.COMMANDERS = gameModules["COMMANDERS"].Bool();
  323. modules.MITHRIL = gameModules["MITHRIL"].Bool();
  324. }
  325. // currentList is passed by value to get current list of depending mods
  326. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  327. {
  328. const CModInfo & mod = allMods.at(modID);
  329. // Mod already present? We found a loop
  330. if (vstd::contains(currentList, modID))
  331. {
  332. logGlobal->errorStream() << "Error: Circular dependency detected! Printing dependency list:";
  333. logGlobal->errorStream() << "\t" << mod.name << " -> ";
  334. return true;
  335. }
  336. currentList.insert(modID);
  337. // recursively check every dependency of this mod
  338. for(const TModID & dependency : mod.dependencies)
  339. {
  340. if (hasCircularDependency(dependency, currentList))
  341. {
  342. logGlobal->errorStream() << "\t" << mod.name << " ->\n"; // conflict detected, print dependency list
  343. return true;
  344. }
  345. }
  346. return false;
  347. }
  348. bool CModHandler::checkDependencies(const std::vector <TModID> & input) const
  349. {
  350. for(const TModID & id : input)
  351. {
  352. const CModInfo & mod = allMods.at(id);
  353. for(const TModID & dep : mod.dependencies)
  354. {
  355. if (!vstd::contains(input, dep))
  356. {
  357. logGlobal->errorStream() << "Error: Mod " << mod.name << " requires missing " << dep << "!";
  358. return false;
  359. }
  360. }
  361. for(const TModID & conflicting : mod.conflicts)
  362. {
  363. if (vstd::contains(input, conflicting))
  364. {
  365. logGlobal->errorStream() << "Error: Mod " << mod.name << " conflicts with " << allMods.at(conflicting).name << "!";
  366. return false;
  367. }
  368. }
  369. if (hasCircularDependency(id))
  370. return false;
  371. }
  372. return true;
  373. }
  374. std::vector <TModID> CModHandler::resolveDependencies(std::vector <TModID> input) const
  375. {
  376. // Topological sort algorithm
  377. // May not be the fastest one but VCMI does not needs any speed here
  378. // Unless user have dozens of mods with complex dependencies this code should be fine
  379. // first - sort input to have input strictly based on name (and not on hashmap or anything else)
  380. boost::range::sort(input);
  381. std::vector <TModID> output;
  382. output.reserve(input.size());
  383. std::set <TModID> resolvedMods;
  384. // Check if all mod dependencies are resolved (moved to resolvedMods)
  385. auto isResolved = [&](const CModInfo mod) -> bool
  386. {
  387. for(const TModID & dependency : mod.dependencies)
  388. {
  389. if (!vstd::contains(resolvedMods, dependency))
  390. return false;
  391. }
  392. return true;
  393. };
  394. while (!input.empty())
  395. {
  396. std::set <TModID> toResolve; // list of mods resolved on this iteration
  397. for (auto it = input.begin(); it != input.end();)
  398. {
  399. if (isResolved(allMods.at(*it)))
  400. {
  401. toResolve.insert(*it);
  402. output.push_back(*it);
  403. it = input.erase(it);
  404. continue;
  405. }
  406. it++;
  407. }
  408. resolvedMods.insert(toResolve.begin(), toResolve.end());
  409. }
  410. return output;
  411. }
  412. static JsonNode updateModSettingsFormat(JsonNode config)
  413. {
  414. for (auto & entry : config["activeMods"].Struct())
  415. {
  416. if (entry.second.getType() == JsonNode::DATA_BOOL)
  417. {
  418. entry.second["active"].Bool() = entry.second.Bool();
  419. }
  420. }
  421. return config;
  422. }
  423. static JsonNode loadModSettings(std::string path)
  424. {
  425. if (CResourceHandler::get()->existsResource(ResourceID(path)))
  426. {
  427. // mod compatibility: check if modSettings has old, 0.94 format
  428. return updateModSettingsFormat(JsonNode(ResourceID(path, EResType::TEXT)));
  429. }
  430. // Probably new install. Create initial configuration
  431. CResourceHandler::get()->createResource(path);
  432. return JsonNode();
  433. }
  434. CModInfo::CModInfo(std::string identifier,const JsonNode & local, const JsonNode & config):
  435. identifier(identifier),
  436. name(config["name"].String()),
  437. description(config["description"].String()),
  438. dependencies(config["depends"].convertTo<std::set<std::string> >()),
  439. conflicts(config["conflicts"].convertTo<std::set<std::string> >()),
  440. validation(PENDING),
  441. config(config)
  442. {
  443. loadLocalData(local);
  444. }
  445. JsonNode CModInfo::saveLocalData()
  446. {
  447. std::ostringstream stream;
  448. stream << std::noshowbase << std::hex << std::setw(8) << std::setfill('0') << checksum;
  449. JsonNode conf;
  450. conf["active"].Bool() = enabled;
  451. conf["validated"].Bool() = validation != FAILED;
  452. conf["checksum"].String() = stream.str();
  453. return conf;
  454. }
  455. void CModInfo::updateChecksum(ui32 newChecksum)
  456. {
  457. if (newChecksum != checksum)
  458. {
  459. checksum = newChecksum;
  460. validation = PENDING;
  461. }
  462. }
  463. void CModInfo::loadLocalData(const JsonNode & data)
  464. {
  465. bool validated = false;
  466. if (data.isNull())
  467. {
  468. enabled = true;
  469. checksum = 0;
  470. }
  471. else
  472. {
  473. enabled = data["active"].Bool();
  474. validated = data["validated"].Bool();
  475. checksum = strtol(data["checksum"].String().c_str(), nullptr, 16);
  476. }
  477. if (enabled)
  478. validation = validated ? PASSED : PENDING;
  479. else
  480. validation = validated ? PASSED : FAILED;
  481. }
  482. void CModHandler::initializeMods(std::vector<std::string> availableMods)
  483. {
  484. const JsonNode modConfig = loadModSettings("config/modSettings.json");
  485. const JsonNode & modList = modConfig["activeMods"];
  486. std::vector <TModID> detectedMods;
  487. for(std::string name : availableMods)
  488. {
  489. boost::to_lower(name);
  490. std::string modFileName = "mods/" + name + "/mod.json";
  491. if (CResourceHandler::get()->existsResource(ResourceID(modFileName)))
  492. {
  493. CModInfo mod(name, modList[name], JsonNode(ResourceID(modFileName)));
  494. allMods[name] = mod;
  495. if (mod.enabled)
  496. detectedMods.push_back(name);
  497. }
  498. else
  499. logGlobal->warnStream() << "\t\t Directory " << name << " does not contains VCMI mod";
  500. }
  501. coreMod = CModInfo("core", modConfig["core"], JsonNode(ResourceID("config/gameConfig.json")));
  502. coreMod.name = "Original game files";
  503. if (!checkDependencies(detectedMods))
  504. {
  505. logGlobal->errorStream() << "Critical error: failed to load mods! Exiting...";
  506. exit(1);
  507. }
  508. activeMods = resolveDependencies(detectedMods);
  509. loadModFilesystems();
  510. }
  511. static JsonNode genDefaultFS()
  512. {
  513. // default FS config for mods: directory "Content" that acts as H3 root directory
  514. JsonNode defaultFS;
  515. defaultFS[""].Vector().resize(2);
  516. defaultFS[""].Vector()[0]["type"].String() = "zip";
  517. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  518. defaultFS[""].Vector()[1]["type"].String() = "dir";
  519. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  520. return defaultFS;
  521. }
  522. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  523. {
  524. static const JsonNode defaultFS = genDefaultFS();
  525. if (!conf["filesystem"].isNull())
  526. return CResourceHandler::createFileSystem("mods/" + modName, conf["filesystem"]);
  527. else
  528. return CResourceHandler::createFileSystem("mods/" + modName, defaultFS);
  529. }
  530. static ui32 calculateModChecksum(const std::string modName, ISimpleResourceLoader * filesystem)
  531. {
  532. boost::crc_32_type modChecksum;
  533. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  534. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  535. // second - add mod.json into checksum because filesystem does not contains this file
  536. // FIXME: remove workaround for core mod
  537. if (modName != "core")
  538. {
  539. ResourceID modConfFile("mods/" + modName + "/mod", EResType::TEXT);
  540. ui32 configChecksum = CResourceHandler::getInitial()->load(modConfFile)->calculateCRC32();
  541. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  542. }
  543. // third - add all detected text files from this mod into checksum
  544. auto files = filesystem->getFilteredFiles([](const ResourceID & resID)
  545. {
  546. return resID.getType() == EResType::TEXT &&
  547. ( boost::starts_with(resID.getName(), "DATA") ||
  548. boost::starts_with(resID.getName(), "CONFIG"));
  549. });
  550. // these two files may change between two runs of vcmi and must be handled separately
  551. files.erase(ResourceID("CONFIG/SETTINGS", EResType::TEXT));
  552. files.erase(ResourceID("CONFIG/MODSETTINGS", EResType::TEXT));
  553. for (const ResourceID & file : files)
  554. {
  555. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  556. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  557. }
  558. return modChecksum.checksum();
  559. }
  560. void CModHandler::loadModFilesystems()
  561. {
  562. coreMod.updateChecksum(calculateModChecksum("core", CResourceHandler::getCoreData()));
  563. for(std::string & modName : activeMods)
  564. {
  565. CModInfo & mod = allMods[modName];
  566. auto filesystem = genModFilesystem(modName, mod.config);
  567. CResourceHandler::get()->addLoader(filesystem, false);
  568. logGlobal->traceStream() << "Generating checksum for " << modName;
  569. mod.updateChecksum(calculateModChecksum(modName, filesystem));
  570. }
  571. }
  572. CModInfo & CModHandler::getModData(TModID modId)
  573. {
  574. CModInfo & mod = allMods.at(modId);
  575. assert(vstd::contains(activeMods, modId)); // not really necessary but won't hurt
  576. return mod;
  577. }
  578. void CModHandler::initializeConfig()
  579. {
  580. loadConfigFromFile("defaultMods.json");
  581. }
  582. void CModHandler::load()
  583. {
  584. CStopWatch totalTime, timer;
  585. CContentHandler content;
  586. logGlobal->infoStream() << "\tInitializing content handler: " << timer.getDiff() << " ms";
  587. // first - load virtual "core" mod that contains all data
  588. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  589. content.preloadData(coreMod);
  590. for(const TModID & modName : activeMods)
  591. content.preloadData(allMods[modName]);
  592. logGlobal->infoStream() << "\tParsing mod data: " << timer.getDiff() << " ms";
  593. content.load(coreMod);
  594. for(const TModID & modName : activeMods)
  595. content.load(allMods[modName]);
  596. logGlobal->infoStream() << "\tLoading mod data: " << timer.getDiff() << "ms";
  597. VLC->creh->loadCrExpBon();
  598. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  599. identifiers.finalize();
  600. logGlobal->infoStream() << "\tResolving identifiers: " << timer.getDiff() << " ms";
  601. content.afterLoadFinalization();
  602. logGlobal->infoStream() << "\tHandlers post-load finalization: " << timer.getDiff() << " ms";
  603. logGlobal->infoStream() << "\tAll game content loaded in " << totalTime.getDiff() << " ms";
  604. }
  605. void CModHandler::afterLoad()
  606. {
  607. JsonNode modSettings;
  608. for (auto & modEntry : allMods)
  609. modSettings["activeMods"][modEntry.first] = modEntry.second.saveLocalData();
  610. modSettings["core"] = coreMod.saveLocalData();
  611. std::ofstream file(*CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::trunc);
  612. file << modSettings;
  613. reload();
  614. }
  615. void CModHandler::reload()
  616. {
  617. {
  618. //recreate adventure map defs
  619. assert(!VLC->dobjinfo->gobjs[Obj::MONSTER].empty()); //make sure that at least some def info was found
  620. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::MONSTER].begin()->second;
  621. for(auto & crea : VLC->creh->creatures)
  622. {
  623. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::MONSTER], crea->idNumber)) // no obj info for this type
  624. {
  625. auto info = new CGDefInfo(*baseInfo);
  626. info->subid = crea->idNumber;
  627. info->name = crea->advMapDef;
  628. VLC->dobjinfo->gobjs[Obj::MONSTER][crea->idNumber] = info;
  629. }
  630. }
  631. }
  632. {
  633. assert(!VLC->dobjinfo->gobjs[Obj::ARTIFACT].empty());
  634. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::ARTIFACT].begin()->second;
  635. for(auto & art : VLC->arth->artifacts)
  636. {
  637. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::ARTIFACT], art->id)) // no obj info for this type
  638. {
  639. auto info = new CGDefInfo(*baseInfo);
  640. info->subid = art->id;
  641. info->name = art->advMapDef;
  642. VLC->dobjinfo->gobjs[Obj::ARTIFACT][art->id] = info;
  643. }
  644. }
  645. }
  646. {
  647. assert(!VLC->dobjinfo->gobjs[Obj::TOWN].empty()); //make sure that at least some def info was found
  648. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::TOWN].begin()->second;
  649. auto & townInfos = VLC->dobjinfo->gobjs[Obj::TOWN];
  650. for(auto & faction : VLC->townh->factions)
  651. {
  652. TFaction index = faction->index;
  653. CTown * town = faction->town;
  654. if (town)
  655. {
  656. auto & cientInfo = town->clientInfo;
  657. if (!vstd::contains(VLC->dobjinfo->gobjs[Obj::TOWN], index)) // no obj info for this type
  658. {
  659. auto info = new CGDefInfo(*baseInfo);
  660. info->subid = index;
  661. townInfos[index] = info;
  662. }
  663. townInfos[index]->name = cientInfo.advMapCastle;
  664. VLC->dobjinfo->villages[index] = new CGDefInfo(*townInfos[index]);
  665. VLC->dobjinfo->villages[index]->name = cientInfo.advMapVillage;
  666. VLC->dobjinfo->capitols[index] = new CGDefInfo(*townInfos[index]);
  667. VLC->dobjinfo->capitols[index]->name = cientInfo.advMapCapitol;
  668. for (int i = 0; i < town->dwellings.size(); ++i)
  669. {
  670. const CGDefInfo * baseInfo = VLC->dobjinfo->gobjs[Obj::CREATURE_GENERATOR1][i]; //get same blockmap as first dwelling of tier i
  671. for (auto cre : town->creatures[i]) //both unupgraded and upgraded get same dwelling
  672. {
  673. auto info = new CGDefInfo(*baseInfo);
  674. info->subid = cre;
  675. info->name = town->dwellings[i];
  676. VLC->dobjinfo->gobjs[Obj::CREATURE_GENERATOR1][cre] = info;
  677. VLC->objh->cregens[cre] = cre; //map of dwelling -> creature id
  678. }
  679. }
  680. }
  681. }
  682. }
  683. }