CModHandler.cpp 32 KB

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