CModHandler.cpp 30 KB

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