CModHandler.cpp 29 KB

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