CModHandler.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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. #include "ScriptHandler.h"
  27. #include "BattleFieldHandler.h"
  28. #include "ObstacleHandler.h"
  29. #include <vstd/StringUtils.h>
  30. VCMI_LIB_NAMESPACE_BEGIN
  31. CIdentifierStorage::CIdentifierStorage():
  32. state(LOADING)
  33. {
  34. }
  35. CIdentifierStorage::~CIdentifierStorage()
  36. {
  37. }
  38. void CIdentifierStorage::checkIdentifier(std::string & ID)
  39. {
  40. if (boost::algorithm::ends_with(ID, "."))
  41. logMod->warn("BIG WARNING: identifier %s seems to be broken!", ID);
  42. else
  43. {
  44. size_t pos = 0;
  45. do
  46. {
  47. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  48. {
  49. logMod->warn("Warning: identifier %s is not in camelCase!", ID);
  50. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  51. }
  52. pos = ID.find('.', pos);
  53. }
  54. while(pos++ != std::string::npos);
  55. }
  56. }
  57. CIdentifierStorage::ObjectCallback::ObjectCallback(
  58. std::string localScope, std::string remoteScope, std::string type,
  59. std::string name, const std::function<void(si32)> & callback,
  60. bool optional):
  61. localScope(localScope),
  62. remoteScope(remoteScope),
  63. type(type),
  64. name(name),
  65. callback(callback),
  66. optional(optional)
  67. {}
  68. void CIdentifierStorage::requestIdentifier(ObjectCallback callback)
  69. {
  70. checkIdentifier(callback.type);
  71. checkIdentifier(callback.name);
  72. assert(!callback.localScope.empty());
  73. if (state != FINISHED) // enqueue request if loading is still in progress
  74. scheduledRequests.push_back(callback);
  75. else // execute immediately for "late" requests
  76. resolveIdentifier(callback);
  77. }
  78. void CIdentifierStorage::requestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  79. {
  80. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  81. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, false));
  82. }
  83. void CIdentifierStorage::requestIdentifier(std::string scope, std::string fullName, const std::function<void(si32)>& callback)
  84. {
  85. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  86. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  87. requestIdentifier(ObjectCallback(scope, scopeAndFullName.first, typeAndName.first, typeAndName.second, callback, false));
  88. }
  89. void CIdentifierStorage::requestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  90. {
  91. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  92. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, false));
  93. }
  94. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback)
  95. {
  96. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:<type.name>
  97. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  98. requestIdentifier(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, callback, false));
  99. }
  100. void CIdentifierStorage::tryRequestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  101. {
  102. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  103. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, true));
  104. }
  105. void CIdentifierStorage::tryRequestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  106. {
  107. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  108. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, true));
  109. }
  110. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string scope, std::string type, std::string name, bool silent)
  111. {
  112. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  113. auto idList = getPossibleIdentifiers(ObjectCallback(scope, pair.first, type, pair.second, std::function<void(si32)>(), silent));
  114. if (idList.size() == 1)
  115. return idList.front().id;
  116. if (!silent)
  117. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name , type ,scope);
  118. return boost::optional<si32>();
  119. }
  120. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string type, const JsonNode & name, bool silent)
  121. {
  122. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  123. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, type, pair.second, std::function<void(si32)>(), silent));
  124. if (idList.size() == 1)
  125. return idList.front().id;
  126. if (!silent)
  127. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), type, name.meta);
  128. return boost::optional<si32>();
  129. }
  130. boost::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent)
  131. {
  132. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:<type.name>
  133. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  134. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, std::function<void(si32)>(), silent));
  135. if (idList.size() == 1)
  136. return idList.front().id;
  137. if (!silent)
  138. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), pair2.first, name.meta);
  139. return boost::optional<si32>();
  140. }
  141. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string scope, std::string fullName, bool silent)
  142. {
  143. auto pair = vstd::splitStringToPair(fullName, ':'); // remoteScope:<type.name>
  144. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  145. auto idList = getPossibleIdentifiers(ObjectCallback(scope, 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. logMod->error("Failed to resolve identifier %s of type %s from mod %s", fullName, pair2.first, scope);
  150. return boost::optional<si32>();
  151. }
  152. void CIdentifierStorage::registerObject(std::string scope, std::string type, std::string name, si32 identifier)
  153. {
  154. ObjectData data;
  155. data.scope = scope;
  156. data.id = identifier;
  157. std::string fullID = type + '.' + name;
  158. checkIdentifier(fullID);
  159. std::pair<const std::string, ObjectData> mapping = std::make_pair(fullID, data);
  160. if(!vstd::containsMapping(registeredObjects, mapping))
  161. {
  162. logMod->trace("registered %s as %s:%s", fullID, scope, identifier);
  163. registeredObjects.insert(mapping);
  164. }
  165. }
  166. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request)
  167. {
  168. std::set<std::string> allowedScopes;
  169. bool isValidScope = true;
  170. // called have not specified destination mod explicitly
  171. if (request.remoteScope.empty())
  172. {
  173. // special scope that should have access to all in-game objects
  174. if (request.localScope == CModHandler::scopeGame())
  175. {
  176. for (auto const & modName : VLC->modh->getActiveMods())
  177. allowedScopes.insert(modName);
  178. }
  179. // normally ID's from all required mods, own mod and virtual built-in mod are allowed
  180. else if(request.localScope != CModHandler::scopeBuiltin() && !request.localScope.empty())
  181. {
  182. allowedScopes = VLC->modh->getModDependencies(request.localScope, isValidScope);
  183. if(!isValidScope)
  184. return std::vector<ObjectData>();
  185. allowedScopes.insert(request.localScope);
  186. }
  187. // all mods can access built-in mod
  188. allowedScopes.insert(CModHandler::scopeBuiltin());
  189. }
  190. else
  191. {
  192. //if destination mod was specified explicitly, restrict lookup to this mod
  193. if(request.remoteScope == CModHandler::scopeBuiltin() )
  194. {
  195. //built-in mod is an implicit dependency for all mods, allow access into it
  196. allowedScopes.insert(request.remoteScope);
  197. }
  198. else if ( request.localScope == CModHandler::scopeGame() )
  199. {
  200. // allow access, this is special scope that should have access to all in-game objects
  201. allowedScopes.insert(request.remoteScope);
  202. }
  203. else if(request.remoteScope == request.localScope )
  204. {
  205. // allow self-access
  206. allowedScopes.insert(request.remoteScope);
  207. }
  208. else
  209. {
  210. // allow access only if mod is in our dependencies
  211. auto myDeps = VLC->modh->getModDependencies(request.localScope, isValidScope);
  212. if(!isValidScope)
  213. return std::vector<ObjectData>();
  214. if(myDeps.count(request.remoteScope))
  215. allowedScopes.insert(request.remoteScope);
  216. }
  217. }
  218. std::string fullID = request.type + '.' + request.name;
  219. auto entries = registeredObjects.equal_range(fullID);
  220. if (entries.first != entries.second)
  221. {
  222. std::vector<ObjectData> locatedIDs;
  223. for (auto it = entries.first; it != entries.second; it++)
  224. {
  225. if (vstd::contains(allowedScopes, it->second.scope))
  226. {
  227. locatedIDs.push_back(it->second);
  228. }
  229. }
  230. return locatedIDs;
  231. }
  232. return std::vector<ObjectData>();
  233. }
  234. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request)
  235. {
  236. auto identifiers = getPossibleIdentifiers(request);
  237. if (identifiers.size() == 1) // normally resolved ID
  238. {
  239. request.callback(identifiers.front().id);
  240. return true;
  241. }
  242. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  243. {
  244. return true;
  245. }
  246. // error found. Try to generate some debug info
  247. if (identifiers.size() == 0)
  248. logMod->error("Unknown identifier!");
  249. else
  250. logMod->error("Ambiguous identifier request!");
  251. logMod->error("Request for %s.%s from mod %s", request.type, request.name, request.localScope);
  252. for (auto id : identifiers)
  253. {
  254. logMod->error("\tID is available in mod %s", id.scope);
  255. }
  256. return false;
  257. }
  258. void CIdentifierStorage::finalize()
  259. {
  260. state = FINALIZING;
  261. bool errorsFound = false;
  262. while ( !scheduledRequests.empty() )
  263. {
  264. // Use local copy since new requests may appear during resolving, invalidating any iterators
  265. auto request = scheduledRequests.back();
  266. scheduledRequests.pop_back();
  267. if (!resolveIdentifier(request))
  268. errorsFound = true;
  269. }
  270. if (errorsFound)
  271. {
  272. for(auto object : registeredObjects)
  273. {
  274. logMod->trace("%s : %s -> %d", object.second.scope, object.first, object.second.id);
  275. }
  276. logMod->error("All known identifiers were dumped into log file");
  277. }
  278. assert(errorsFound == false);
  279. state = FINISHED;
  280. }
  281. ContentTypeHandler::ContentTypeHandler(IHandlerBase * handler, std::string objectName):
  282. handler(handler),
  283. objectName(objectName),
  284. originalData(handler->loadLegacyData((size_t)VLC->modh->settings.data["textData"][objectName].Float()))
  285. {
  286. for(auto & node : originalData)
  287. {
  288. node.setMeta(CModHandler::scopeBuiltin());
  289. }
  290. }
  291. bool ContentTypeHandler::preloadModData(std::string modName, std::vector<std::string> fileList, bool validate)
  292. {
  293. bool result;
  294. JsonNode data = JsonUtils::assembleFromFiles(fileList, result);
  295. data.setMeta(modName);
  296. ModInfo & modInfo = modData[modName];
  297. for(auto entry : data.Struct())
  298. {
  299. size_t colon = entry.first.find(':');
  300. if (colon == std::string::npos)
  301. {
  302. // normal object, local to this mod
  303. modInfo.modData[entry.first].swap(entry.second);
  304. }
  305. else
  306. {
  307. std::string remoteName = entry.first.substr(0, colon);
  308. std::string objectName = entry.first.substr(colon + 1);
  309. // patching this mod? Send warning and continue - this situation can be handled normally
  310. if (remoteName == modName)
  311. logMod->warn("Redundant namespace definition for %s", objectName);
  312. logMod->trace("Patching object %s (%s) from %s", objectName, remoteName, modName);
  313. JsonNode & remoteConf = modData[remoteName].patches[objectName];
  314. JsonUtils::merge(remoteConf, entry.second);
  315. }
  316. }
  317. return result;
  318. }
  319. bool ContentTypeHandler::loadMod(std::string modName, bool validate)
  320. {
  321. ModInfo & modInfo = modData[modName];
  322. bool result = true;
  323. auto performValidate = [&,this](JsonNode & data, const std::string & name){
  324. handler->beforeValidate(data);
  325. if (validate)
  326. result &= JsonUtils::validate(data, "vcmi:" + objectName, name);
  327. };
  328. // apply patches
  329. if (!modInfo.patches.isNull())
  330. JsonUtils::merge(modInfo.modData, modInfo.patches);
  331. for(auto & entry : modInfo.modData.Struct())
  332. {
  333. const std::string & name = entry.first;
  334. JsonNode & data = entry.second;
  335. if (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
  336. {
  337. if (modName != "core")
  338. logMod->warn("Mod %s is attempting to load original data! This should be reserved for built-in mod.", modName);
  339. // try to add H3 object data
  340. size_t index = static_cast<size_t>(data["index"].Float());
  341. if(originalData.size() > index)
  342. {
  343. logMod->trace("found original data in loadMod(%s) at index %d", name, index);
  344. JsonUtils::merge(originalData[index], data);
  345. std::swap(originalData[index], data);
  346. originalData[index].clear(); // do not use same data twice (same ID)
  347. }
  348. else
  349. {
  350. logMod->trace("no original data in loadMod(%s) at index %d", name, index);
  351. }
  352. performValidate(data, name);
  353. handler->loadObject(modName, name, data, index);
  354. }
  355. else
  356. {
  357. // normal new object
  358. logMod->trace("no index in loadMod(%s)", name);
  359. performValidate(data,name);
  360. handler->loadObject(modName, name, data);
  361. }
  362. }
  363. return result;
  364. }
  365. void ContentTypeHandler::loadCustom()
  366. {
  367. handler->loadCustom();
  368. }
  369. void ContentTypeHandler::afterLoadFinalization()
  370. {
  371. handler->afterLoadFinalization();
  372. }
  373. CContentHandler::CContentHandler()
  374. {
  375. }
  376. void CContentHandler::init()
  377. {
  378. handlers.insert(std::make_pair("heroClasses", ContentTypeHandler(&VLC->heroh->classes, "heroClass")));
  379. handlers.insert(std::make_pair("artifacts", ContentTypeHandler(VLC->arth, "artifact")));
  380. handlers.insert(std::make_pair("creatures", ContentTypeHandler(VLC->creh, "creature")));
  381. handlers.insert(std::make_pair("factions", ContentTypeHandler(VLC->townh, "faction")));
  382. handlers.insert(std::make_pair("objects", ContentTypeHandler(VLC->objtypeh, "object")));
  383. handlers.insert(std::make_pair("heroes", ContentTypeHandler(VLC->heroh, "hero")));
  384. handlers.insert(std::make_pair("spells", ContentTypeHandler(VLC->spellh, "spell")));
  385. handlers.insert(std::make_pair("skills", ContentTypeHandler(VLC->skillh, "skill")));
  386. handlers.insert(std::make_pair("templates", ContentTypeHandler((IHandlerBase *)VLC->tplh, "template")));
  387. #if SCRIPTING_ENABLED
  388. handlers.insert(std::make_pair("scripts", ContentTypeHandler(VLC->scriptHandler, "script")));
  389. #endif
  390. handlers.insert(std::make_pair("battlefields", ContentTypeHandler(VLC->battlefieldsHandler, "battlefield")));
  391. handlers.insert(std::make_pair("obstacles", ContentTypeHandler(VLC->obstacleHandler, "obstacle")));
  392. //TODO: any other types of moddables?
  393. }
  394. bool CContentHandler::preloadModData(std::string modName, JsonNode modConfig, bool validate)
  395. {
  396. bool result = true;
  397. for(auto & handler : handlers)
  398. {
  399. result &= handler.second.preloadModData(modName, modConfig[handler.first].convertTo<std::vector<std::string> >(), validate);
  400. }
  401. return result;
  402. }
  403. bool CContentHandler::loadMod(std::string modName, bool validate)
  404. {
  405. bool result = true;
  406. for(auto & handler : handlers)
  407. {
  408. result &= handler.second.loadMod(modName, validate);
  409. }
  410. return result;
  411. }
  412. void CContentHandler::loadCustom()
  413. {
  414. for(auto & handler : handlers)
  415. {
  416. handler.second.loadCustom();
  417. }
  418. }
  419. void CContentHandler::afterLoadFinalization()
  420. {
  421. for(auto & handler : handlers)
  422. {
  423. handler.second.afterLoadFinalization();
  424. }
  425. }
  426. void CContentHandler::preloadData(CModInfo & mod)
  427. {
  428. bool validate = (mod.validation != CModInfo::PASSED);
  429. // print message in format [<8-symbols checksum>] <modname>
  430. logMod->info("\t\t[%08x]%s", mod.checksum, mod.name);
  431. if (validate && mod.identifier != CModHandler::scopeBuiltin())
  432. {
  433. if (!JsonUtils::validate(mod.config, "vcmi:mod", mod.identifier))
  434. mod.validation = CModInfo::FAILED;
  435. }
  436. if (!preloadModData(mod.identifier, mod.config, validate))
  437. mod.validation = CModInfo::FAILED;
  438. }
  439. void CContentHandler::load(CModInfo & mod)
  440. {
  441. bool validate = (mod.validation != CModInfo::PASSED);
  442. if (!loadMod(mod.identifier, validate))
  443. mod.validation = CModInfo::FAILED;
  444. if (validate)
  445. {
  446. if (mod.validation != CModInfo::FAILED)
  447. logMod->info("\t\t[DONE] %s", mod.name);
  448. else
  449. logMod->error("\t\t[FAIL] %s", mod.name);
  450. }
  451. else
  452. logMod->info("\t\t[SKIP] %s", mod.name);
  453. }
  454. const ContentTypeHandler & CContentHandler::operator[](const std::string & name) const
  455. {
  456. return handlers.at(name);
  457. }
  458. static JsonNode loadModSettings(std::string path)
  459. {
  460. if (CResourceHandler::get("local")->existsResource(ResourceID(path)))
  461. {
  462. return JsonNode(ResourceID(path, EResType::TEXT));
  463. }
  464. // Probably new install. Create initial configuration
  465. CResourceHandler::get("local")->createResource(path);
  466. return JsonNode();
  467. }
  468. JsonNode addMeta(JsonNode config, std::string meta)
  469. {
  470. config.setMeta(meta);
  471. return config;
  472. }
  473. CModInfo::Version CModInfo::Version::GameVersion()
  474. {
  475. return Version(VCMI_VERSION_MAJOR, VCMI_VERSION_MINOR, VCMI_VERSION_PATCH);
  476. }
  477. CModInfo::Version CModInfo::Version::fromString(std::string from)
  478. {
  479. int major = 0, minor = 0, patch = 0;
  480. try
  481. {
  482. auto pointPos = from.find('.');
  483. major = std::stoi(from.substr(0, pointPos));
  484. if(pointPos != std::string::npos)
  485. {
  486. from = from.substr(pointPos + 1);
  487. pointPos = from.find('.');
  488. minor = std::stoi(from.substr(0, pointPos));
  489. if(pointPos != std::string::npos)
  490. patch = std::stoi(from.substr(pointPos + 1));
  491. }
  492. }
  493. catch(const std::invalid_argument &)
  494. {
  495. return Version();
  496. }
  497. return Version(major, minor, patch);
  498. }
  499. std::string CModInfo::Version::toString() const
  500. {
  501. return std::to_string(major) + '.' + std::to_string(minor) + '.' + std::to_string(patch);
  502. }
  503. bool CModInfo::Version::compatible(const Version & other, bool checkMinor, bool checkPatch) const
  504. {
  505. return (major == other.major &&
  506. (!checkMinor || minor >= other.minor) &&
  507. (!checkPatch || minor > other.minor || (minor == other.minor && patch >= other.patch)));
  508. }
  509. bool CModInfo::Version::isNull() const
  510. {
  511. return major == 0 && minor == 0 && patch == 0;
  512. }
  513. CModInfo::CModInfo():
  514. checksum(0),
  515. enabled(false),
  516. validation(PENDING)
  517. {
  518. }
  519. CModInfo::CModInfo(std::string identifier,const JsonNode & local, const JsonNode & config):
  520. identifier(identifier),
  521. name(config["name"].String()),
  522. description(config["description"].String()),
  523. dependencies(config["depends"].convertTo<std::set<std::string> >()),
  524. conflicts(config["conflicts"].convertTo<std::set<std::string> >()),
  525. checksum(0),
  526. enabled(false),
  527. validation(PENDING),
  528. config(addMeta(config, identifier))
  529. {
  530. version = Version::fromString(config["version"].String());
  531. if(!config["compatibility"].isNull())
  532. {
  533. vcmiCompatibleMin = Version::fromString(config["compatibility"]["min"].String());
  534. vcmiCompatibleMax = Version::fromString(config["compatibility"]["max"].String());
  535. }
  536. loadLocalData(local);
  537. }
  538. JsonNode CModInfo::saveLocalData() const
  539. {
  540. std::ostringstream stream;
  541. stream << std::noshowbase << std::hex << std::setw(8) << std::setfill('0') << checksum;
  542. JsonNode conf;
  543. conf["active"].Bool() = enabled;
  544. conf["validated"].Bool() = validation != FAILED;
  545. conf["checksum"].String() = stream.str();
  546. return conf;
  547. }
  548. std::string CModInfo::getModDir(std::string name)
  549. {
  550. return "MODS/" + boost::algorithm::replace_all_copy(name, ".", "/MODS/");
  551. }
  552. std::string CModInfo::getModFile(std::string name)
  553. {
  554. return getModDir(name) + "/mod.json";
  555. }
  556. void CModInfo::updateChecksum(ui32 newChecksum)
  557. {
  558. // comment-out next line to force validation of all mods ignoring checksum
  559. if (newChecksum != checksum)
  560. {
  561. checksum = newChecksum;
  562. validation = PENDING;
  563. }
  564. }
  565. void CModInfo::loadLocalData(const JsonNode & data)
  566. {
  567. bool validated = false;
  568. enabled = true;
  569. checksum = 0;
  570. if (data.getType() == JsonNode::JsonType::DATA_BOOL)
  571. {
  572. enabled = data.Bool();
  573. }
  574. if (data.getType() == JsonNode::JsonType::DATA_STRUCT)
  575. {
  576. enabled = data["active"].Bool();
  577. validated = data["validated"].Bool();
  578. checksum = strtol(data["checksum"].String().c_str(), nullptr, 16);
  579. }
  580. //check compatibility
  581. bool wasEnabled = enabled;
  582. enabled = enabled && (vcmiCompatibleMin.isNull() || Version::GameVersion().compatible(vcmiCompatibleMin));
  583. enabled = enabled && (vcmiCompatibleMax.isNull() || vcmiCompatibleMax.compatible(Version::GameVersion()));
  584. if(wasEnabled && !enabled)
  585. logGlobal->warn("Mod %s is incompatible with current version of VCMI and cannot be enabled", name);
  586. if (enabled)
  587. validation = validated ? PASSED : PENDING;
  588. else
  589. validation = validated ? PASSED : FAILED;
  590. }
  591. CModHandler::CModHandler() : content(std::make_shared<CContentHandler>())
  592. {
  593. modules.COMMANDERS = false;
  594. modules.STACK_ARTIFACT = false;
  595. modules.STACK_EXP = false;
  596. modules.MITHRIL = false;
  597. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  598. {
  599. identifiers.registerObject(CModHandler::scopeBuiltin(), "resource", GameConstants::RESOURCE_NAMES[i], i);
  600. }
  601. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  602. {
  603. identifiers.registerObject(CModHandler::scopeBuiltin(), "primSkill", PrimarySkill::names[i], i);
  604. identifiers.registerObject(CModHandler::scopeBuiltin(), "primarySkill", PrimarySkill::names[i], i);
  605. }
  606. }
  607. CModHandler::~CModHandler()
  608. {
  609. }
  610. void CModHandler::loadConfigFromFile (std::string name)
  611. {
  612. std::string paths;
  613. for(auto& p : CResourceHandler::get()->getResourceNames(ResourceID("config/" + name)))
  614. {
  615. paths += p.string() + ", ";
  616. }
  617. paths = paths.substr(0, paths.size() - 2);
  618. logMod->debug("Loading hardcoded features settings from [%s], result:", paths);
  619. settings.data = JsonUtils::assembleFromFiles("config/" + name);
  620. const JsonNode & hardcodedFeatures = settings.data["hardcodedFeatures"];
  621. settings.MAX_HEROES_AVAILABLE_PER_PLAYER = static_cast<int>(hardcodedFeatures["MAX_HEROES_AVAILABLE_PER_PLAYER"].Integer());
  622. logMod->debug("\tMAX_HEROES_AVAILABLE_PER_PLAYER\t%d", settings.MAX_HEROES_AVAILABLE_PER_PLAYER);
  623. settings.MAX_HEROES_ON_MAP_PER_PLAYER = static_cast<int>(hardcodedFeatures["MAX_HEROES_ON_MAP_PER_PLAYER"].Integer());
  624. logMod->debug("\tMAX_HEROES_ON_MAP_PER_PLAYER\t%d", settings.MAX_HEROES_ON_MAP_PER_PLAYER);
  625. settings.CREEP_SIZE = static_cast<int>(hardcodedFeatures["CREEP_SIZE"].Integer());
  626. logMod->debug("\tCREEP_SIZE\t%d", settings.CREEP_SIZE);
  627. settings.WEEKLY_GROWTH = static_cast<int>(hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Integer());
  628. logMod->debug("\tWEEKLY_GROWTH\t%d", settings.WEEKLY_GROWTH);
  629. settings.NEUTRAL_STACK_EXP = static_cast<int>(hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Integer());
  630. logMod->debug("\tNEUTRAL_STACK_EXP\t%d", settings.NEUTRAL_STACK_EXP);
  631. settings.MAX_BUILDING_PER_TURN = static_cast<int>(hardcodedFeatures["MAX_BUILDING_PER_TURN"].Integer());
  632. logMod->debug("\tMAX_BUILDING_PER_TURN\t%d", settings.MAX_BUILDING_PER_TURN);
  633. settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
  634. logMod->debug("\tDWELLINGS_ACCUMULATE_CREATURES\t%d", static_cast<int>(settings.DWELLINGS_ACCUMULATE_CREATURES));
  635. settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool();
  636. logMod->debug("\tALL_CREATURES_GET_DOUBLE_MONTHS\t%d", static_cast<int>(settings.ALL_CREATURES_GET_DOUBLE_MONTHS));
  637. settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS = hardcodedFeatures["WINNING_HERO_WITH_NO_TROOPS_RETREATS"].Bool();
  638. logMod->debug("\tWINNING_HERO_WITH_NO_TROOPS_RETREATS\t%d", static_cast<int>(settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS));
  639. settings.BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE = hardcodedFeatures["BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE"].Bool();
  640. logMod->debug("\tBLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE\t%d", static_cast<int>(settings.BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE));
  641. settings.NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS = hardcodedFeatures["NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS"].Bool();
  642. logMod->debug("\tNO_RANDOM_SPECIAL_WEEKS_AND_MONTHS\t%d", static_cast<int>(settings.NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS));
  643. const JsonNode & gameModules = settings.data["modules"];
  644. modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool();
  645. logMod->debug("\tSTACK_EXP\t%d", static_cast<int>(modules.STACK_EXP));
  646. modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool();
  647. logMod->debug("\tSTACK_ARTIFACT\t%d", static_cast<int>(modules.STACK_ARTIFACT));
  648. modules.COMMANDERS = gameModules["COMMANDERS"].Bool();
  649. logMod->debug("\tCOMMANDERS\t%d", static_cast<int>(modules.COMMANDERS));
  650. modules.MITHRIL = gameModules["MITHRIL"].Bool();
  651. logMod->debug("\tMITHRIL\t%d", static_cast<int>(modules.MITHRIL));
  652. }
  653. // currentList is passed by value to get current list of depending mods
  654. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  655. {
  656. const CModInfo & mod = allMods.at(modID);
  657. // Mod already present? We found a loop
  658. if (vstd::contains(currentList, modID))
  659. {
  660. logMod->error("Error: Circular dependency detected! Printing dependency list:");
  661. logMod->error("\t%s -> ", mod.name);
  662. return true;
  663. }
  664. currentList.insert(modID);
  665. // recursively check every dependency of this mod
  666. for(const TModID & dependency : mod.dependencies)
  667. {
  668. if (hasCircularDependency(dependency, currentList))
  669. {
  670. logMod->error("\t%s ->\n", mod.name); // conflict detected, print dependency list
  671. return true;
  672. }
  673. }
  674. return false;
  675. }
  676. bool CModHandler::checkDependencies(const std::vector <TModID> & input) const
  677. {
  678. for(const TModID & id : input)
  679. {
  680. const CModInfo & mod = allMods.at(id);
  681. for(const TModID & dep : mod.dependencies)
  682. {
  683. if(!vstd::contains(input, dep))
  684. {
  685. logMod->error("Error: Mod %s requires missing %s!", mod.name, dep);
  686. return false;
  687. }
  688. }
  689. for(const TModID & conflicting : mod.conflicts)
  690. {
  691. if(vstd::contains(input, conflicting))
  692. {
  693. logMod->error("Error: Mod %s conflicts with %s!", mod.name, allMods.at(conflicting).name);
  694. return false;
  695. }
  696. }
  697. if(hasCircularDependency(id))
  698. return false;
  699. }
  700. return true;
  701. }
  702. // Returned vector affects the resource loaders call order (see CFilesystemList::load).
  703. // The loaders call order matters when dependent mod overrides resources in its dependencies.
  704. std::vector <TModID> CModHandler::validateAndSortDependencies(std::vector <TModID> modsToResolve) const
  705. {
  706. // Topological sort algorithm.
  707. // TODO: Investigate possible ways to improve performance.
  708. boost::range::sort(modsToResolve); // Sort mods per name
  709. std::vector <TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  710. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  711. std::set <TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  712. // Mod is resolved if it has not dependencies or all its dependencies are already resolved
  713. auto isResolved = [&](const CModInfo & mod) -> CModInfo::EValidationStatus
  714. {
  715. if(mod.dependencies.size() > resolvedModIDs.size())
  716. return CModInfo::PENDING;
  717. for(const TModID & dependency : mod.dependencies)
  718. {
  719. if(!vstd::contains(resolvedModIDs, dependency))
  720. return CModInfo::PENDING;
  721. }
  722. return CModInfo::PASSED;
  723. };
  724. while(true)
  725. {
  726. std::set <TModID> resolvedOnCurrentTreeLevel;
  727. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  728. {
  729. if(isResolved(allMods.at(*it)) == CModInfo::PASSED)
  730. {
  731. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node childs will be resolved on the next iteration
  732. sortedValidMods.push_back(*it);
  733. it = modsToResolve.erase(it);
  734. continue;
  735. }
  736. it++;
  737. }
  738. if(resolvedOnCurrentTreeLevel.size())
  739. {
  740. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  741. continue;
  742. }
  743. // If there're no valid mods on the current mods tree level, no more mod can be resolved, should be end.
  744. break;
  745. }
  746. // Left mods have unresolved dependencies, output all to log.
  747. for(const auto & brokenModID : modsToResolve)
  748. {
  749. const CModInfo & brokenMod = allMods.at(brokenModID);
  750. for(const TModID & dependency : brokenMod.dependencies)
  751. {
  752. if(!vstd::contains(resolvedModIDs, dependency))
  753. logMod->error("Mod '%s' will not work: it depends on mod '%s', which is not installed.", brokenMod.name, dependency);
  754. }
  755. }
  756. return sortedValidMods;
  757. }
  758. std::vector<std::string> CModHandler::getModList(std::string path)
  759. {
  760. std::string modDir = boost::to_upper_copy(path + "MODS/");
  761. size_t depth = boost::range::count(modDir, '/');
  762. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourceID & id) -> bool
  763. {
  764. if (id.getType() != EResType::DIRECTORY)
  765. return false;
  766. if (!boost::algorithm::starts_with(id.getName(), modDir))
  767. return false;
  768. if (boost::range::count(id.getName(), '/') != depth )
  769. return false;
  770. return true;
  771. });
  772. //storage for found mods
  773. std::vector<std::string> foundMods;
  774. for (auto & entry : list)
  775. {
  776. std::string name = entry.getName();
  777. name.erase(0, modDir.size()); //Remove path prefix
  778. if (!name.empty())
  779. foundMods.push_back(name);
  780. }
  781. return foundMods;
  782. }
  783. bool CModHandler::isScopeReserved(const TModID & scope)
  784. {
  785. static const std::array<TModID, 3> reservedScopes = {
  786. "core", "map", "game"
  787. };
  788. return std::find(reservedScopes.begin(), reservedScopes.end(), scope) != reservedScopes.end();
  789. }
  790. const TModID & CModHandler::scopeBuiltin()
  791. {
  792. static const TModID scope = "core";
  793. return scope;
  794. }
  795. const TModID & CModHandler::scopeGame()
  796. {
  797. static const TModID scope = "game";
  798. return scope;
  799. }
  800. const TModID & CModHandler::scopeMap()
  801. {
  802. //TODO: implement accessing map dependencies for both H3 and VCMI maps
  803. // for now, allow access to any identifiers
  804. static const TModID scope = "game";
  805. return scope;
  806. }
  807. void CModHandler::loadMods(std::string path, std::string parent, const JsonNode & modSettings, bool enableMods)
  808. {
  809. for(std::string modName : getModList(path))
  810. loadOneMod(modName, parent, modSettings, enableMods);
  811. }
  812. void CModHandler::loadOneMod(std::string modName, std::string parent, const JsonNode & modSettings, bool enableMods)
  813. {
  814. boost::to_lower(modName);
  815. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  816. if ( isScopeReserved(modFullName))
  817. {
  818. logMod->error("Can not load mod %s - this name is reserved for internal use!", modFullName);
  819. return;
  820. }
  821. if(CResourceHandler::get("initial")->existsResource(ResourceID(CModInfo::getModFile(modFullName))))
  822. {
  823. CModInfo mod(modFullName, modSettings[modName], JsonNode(ResourceID(CModInfo::getModFile(modFullName))));
  824. if (!parent.empty()) // this is submod, add parent to dependencies
  825. mod.dependencies.insert(parent);
  826. allMods[modFullName] = mod;
  827. if (mod.enabled && enableMods)
  828. activeMods.push_back(modFullName);
  829. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.enabled);
  830. }
  831. }
  832. void CModHandler::loadMods(bool onlyEssential)
  833. {
  834. JsonNode modConfig;
  835. if(onlyEssential)
  836. {
  837. loadOneMod("vcmi", "", modConfig, true);//only vcmi and submods
  838. }
  839. else
  840. {
  841. modConfig = loadModSettings("config/modSettings.json");
  842. loadMods("", "", modConfig["activeMods"], true);
  843. }
  844. coreMod = CModInfo(CModHandler::scopeBuiltin(), modConfig[CModHandler::scopeBuiltin()], JsonNode(ResourceID("config/gameConfig.json")));
  845. coreMod.name = "Original game files";
  846. }
  847. std::vector<std::string> CModHandler::getAllMods()
  848. {
  849. std::vector<std::string> modlist;
  850. for (auto & entry : allMods)
  851. modlist.push_back(entry.first);
  852. return modlist;
  853. }
  854. std::vector<std::string> CModHandler::getActiveMods()
  855. {
  856. return activeMods;
  857. }
  858. static JsonNode genDefaultFS()
  859. {
  860. // default FS config for mods: directory "Content" that acts as H3 root directory
  861. JsonNode defaultFS;
  862. defaultFS[""].Vector().resize(2);
  863. defaultFS[""].Vector()[0]["type"].String() = "zip";
  864. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  865. defaultFS[""].Vector()[1]["type"].String() = "dir";
  866. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  867. return defaultFS;
  868. }
  869. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  870. {
  871. static const JsonNode defaultFS = genDefaultFS();
  872. if (!conf["filesystem"].isNull())
  873. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  874. else
  875. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  876. }
  877. static ui32 calculateModChecksum(const std::string modName, ISimpleResourceLoader * filesystem)
  878. {
  879. boost::crc_32_type modChecksum;
  880. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  881. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  882. // second - add mod.json into checksum because filesystem does not contains this file
  883. // FIXME: remove workaround for core mod
  884. if (modName != CModHandler::scopeBuiltin())
  885. {
  886. ResourceID modConfFile(CModInfo::getModFile(modName), EResType::TEXT);
  887. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  888. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  889. }
  890. // third - add all detected text files from this mod into checksum
  891. auto files = filesystem->getFilteredFiles([](const ResourceID & resID)
  892. {
  893. return resID.getType() == EResType::TEXT &&
  894. ( boost::starts_with(resID.getName(), "DATA") ||
  895. boost::starts_with(resID.getName(), "CONFIG"));
  896. });
  897. for (const ResourceID & file : files)
  898. {
  899. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  900. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  901. }
  902. return modChecksum.checksum();
  903. }
  904. void CModHandler::loadModFilesystems()
  905. {
  906. activeMods = validateAndSortDependencies(activeMods);
  907. coreMod.updateChecksum(calculateModChecksum(CModHandler::scopeBuiltin(), CResourceHandler::get(CModHandler::scopeBuiltin())));
  908. for(std::string & modName : activeMods)
  909. {
  910. CModInfo & mod = allMods[modName];
  911. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  912. }
  913. }
  914. std::set<TModID> CModHandler::getModDependencies(TModID modId, bool & isModFound)
  915. {
  916. auto it = allMods.find(modId);
  917. isModFound = (it != allMods.end());
  918. if(isModFound)
  919. return it->second.dependencies;
  920. logMod->error("Mod not found: '%s'", modId);
  921. return std::set<TModID>();
  922. }
  923. void CModHandler::initializeConfig()
  924. {
  925. loadConfigFromFile("defaultMods.json");
  926. }
  927. void CModHandler::load()
  928. {
  929. CStopWatch totalTime, timer;
  930. logMod->info("\tInitializing content handler: %d ms", timer.getDiff());
  931. content->init();
  932. for(const TModID & modName : activeMods)
  933. {
  934. logMod->trace("Generating checksum for %s", modName);
  935. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  936. }
  937. // first - load virtual builtin mod that contains all data
  938. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  939. content->preloadData(coreMod);
  940. for(const TModID & modName : activeMods)
  941. content->preloadData(allMods[modName]);
  942. logMod->info("\tParsing mod data: %d ms", timer.getDiff());
  943. content->load(coreMod);
  944. for(const TModID & modName : activeMods)
  945. content->load(allMods[modName]);
  946. #if SCRIPTING_ENABLED
  947. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  948. #endif
  949. content->loadCustom();
  950. logMod->info("\tLoading mod data: %d ms", timer.getDiff());
  951. VLC->creh->loadCrExpBon();
  952. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  953. identifiers.finalize();
  954. logMod->info("\tResolving identifiers: %d ms", timer.getDiff());
  955. content->afterLoadFinalization();
  956. logMod->info("\tHandlers post-load finalization: %d ms ", timer.getDiff());
  957. logMod->info("\tAll game content loaded in %d ms", totalTime.getDiff());
  958. }
  959. void CModHandler::afterLoad(bool onlyEssential)
  960. {
  961. JsonNode modSettings;
  962. for (auto & modEntry : allMods)
  963. {
  964. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  965. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  966. }
  967. modSettings[CModHandler::scopeBuiltin()] = coreMod.saveLocalData();
  968. if(!onlyEssential)
  969. {
  970. FileStream file(*CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::out | std::ofstream::trunc);
  971. file << modSettings.toJson();
  972. }
  973. }
  974. std::string CModHandler::normalizeIdentifier(const std::string & scope, const std::string & remoteScope, const std::string & identifier)
  975. {
  976. auto p = vstd::splitStringToPair(identifier, ':');
  977. if(p.first.empty())
  978. p.first = scope;
  979. if(p.first == remoteScope)
  980. p.first.clear();
  981. return p.first.empty() ? p.second : p.first + ":" + p.second;
  982. }
  983. void CModHandler::parseIdentifier(const std::string & fullIdentifier, std::string & scope, std::string & type, std::string & identifier)
  984. {
  985. auto p = vstd::splitStringToPair(fullIdentifier, ':');
  986. scope = p.first;
  987. auto p2 = vstd::splitStringToPair(p.second, '.');
  988. if(p2.first != "")
  989. {
  990. type = p2.first;
  991. identifier = p2.second;
  992. }
  993. else
  994. {
  995. type = p.second;
  996. identifier.clear();
  997. }
  998. }
  999. std::string CModHandler::makeFullIdentifier(const std::string & scope, const std::string & type, const std::string & identifier)
  1000. {
  1001. if(type.empty())
  1002. logGlobal->error("Full identifier (%s %s) requires type name", scope, identifier);
  1003. std::string actualScope = scope;
  1004. std::string actualName = identifier;
  1005. //ignore scope if identifier is scoped
  1006. auto scopeAndName = vstd::splitStringToPair(identifier, ':');
  1007. if(scopeAndName.first != "")
  1008. {
  1009. actualScope = scopeAndName.first;
  1010. actualName = scopeAndName.second;
  1011. }
  1012. if(actualScope.empty())
  1013. {
  1014. return actualName.empty() ? type : type + "." + actualName;
  1015. }
  1016. else
  1017. {
  1018. return actualName.empty() ? actualScope+ ":" + type : actualScope + ":" + type + "." + actualName;
  1019. }
  1020. }
  1021. VCMI_LIB_NAMESPACE_END