CModHandler.cpp 30 KB

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