IdentifierStorage.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. /*
  2. * IdentifierStorage.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 "IdentifierStorage.h"
  12. #include "CModHandler.h"
  13. #include "ModScope.h"
  14. #include "../JsonNode.h"
  15. #include "../VCMI_Lib.h"
  16. #include "../constants/StringConstants.h"
  17. #include "../spells/CSpellHandler.h"
  18. #include <vstd/StringUtils.h>
  19. VCMI_LIB_NAMESPACE_BEGIN
  20. CIdentifierStorage::CIdentifierStorage()
  21. {
  22. //TODO: moddable spell schools
  23. for (auto i = 0; i < GameConstants::DEFAULT_SCHOOLS; ++i)
  24. registerObject(ModScope::scopeBuiltin(), "spellSchool", SpellConfig::SCHOOL[i].jsonName, SpellConfig::SCHOOL[i].id.getNum());
  25. registerObject(ModScope::scopeBuiltin(), "spellSchool", "any", SpellSchool::ANY.getNum());
  26. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  27. registerObject(ModScope::scopeBuiltin(), "resource", GameConstants::RESOURCE_NAMES[i], i);
  28. for (int i = 0; i < std::size(GameConstants::PLAYER_COLOR_NAMES); ++i)
  29. registerObject(ModScope::scopeBuiltin(), "playerColor", GameConstants::PLAYER_COLOR_NAMES[i], i);
  30. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  31. {
  32. registerObject(ModScope::scopeBuiltin(), "primSkill", NPrimarySkill::names[i], i);
  33. registerObject(ModScope::scopeBuiltin(), "primarySkill", NPrimarySkill::names[i], i);
  34. }
  35. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureDamageBoth", 0);
  36. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureDamageMin", 1);
  37. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureDamageMax", 2);
  38. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "damageTypeAll", -1);
  39. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "damageTypeMelee", 0);
  40. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "damageTypeRanged", 1);
  41. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "heroMovementLand", 1);
  42. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "heroMovementSea", 0);
  43. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "deathStareGorgon", 0);
  44. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "deathStareCommander", 1);
  45. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "rebirthRegular", 0);
  46. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "rebirthSpecial", 1);
  47. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "visionsMonsters", 0);
  48. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "visionsHeroes", 1);
  49. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "visionsTowns", 2);
  50. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "immunityBattleWide", 0);
  51. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "immunityEnemyHero", 1);
  52. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "transmutationPerHealth", 0);
  53. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "transmutationPerUnit", 1);
  54. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "destructionKillPercentage", 0);
  55. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "destructionKillAmount", 1);
  56. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "soulStealPermanent", 0);
  57. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "soulStealBattle", 1);
  58. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "movementFlying", 0);
  59. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "movementTeleporting", 1);
  60. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel1", 1);
  61. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel2", 2);
  62. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel3", 3);
  63. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel4", 4);
  64. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel5", 5);
  65. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel1", 1);
  66. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel2", 2);
  67. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel3", 3);
  68. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel4", 4);
  69. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel5", 5);
  70. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel6", 6);
  71. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel7", 7);
  72. }
  73. void CIdentifierStorage::checkIdentifier(std::string & ID)
  74. {
  75. if (boost::algorithm::ends_with(ID, "."))
  76. logMod->warn("BIG WARNING: identifier %s seems to be broken!", ID);
  77. else
  78. {
  79. size_t pos = 0;
  80. do
  81. {
  82. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  83. {
  84. logMod->warn("Warning: identifier %s is not in camelCase!", ID);
  85. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  86. }
  87. pos = ID.find('.', pos);
  88. }
  89. while(pos++ != std::string::npos);
  90. }
  91. }
  92. void CIdentifierStorage::requestIdentifier(ObjectCallback callback) const
  93. {
  94. checkIdentifier(callback.type);
  95. checkIdentifier(callback.name);
  96. assert(!callback.localScope.empty());
  97. if (state != ELoadingState::FINISHED) // enqueue request if loading is still in progress
  98. scheduledRequests.push_back(callback);
  99. else // execute immediately for "late" requests
  100. resolveIdentifier(callback);
  101. }
  102. CIdentifierStorage::ObjectCallback CIdentifierStorage::ObjectCallback::fromNameWithType(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback, bool optional)
  103. {
  104. assert(!scope.empty());
  105. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  106. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  107. if (scope == scopeAndFullName.first)
  108. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  109. ObjectCallback result;
  110. result.localScope = scope;
  111. result.remoteScope = scopeAndFullName.first;
  112. result.type = typeAndName.first;
  113. result.name = typeAndName.second;
  114. result.callback = callback;
  115. result.optional = optional;
  116. result.dynamicType = true;
  117. return result;
  118. }
  119. CIdentifierStorage::ObjectCallback CIdentifierStorage::ObjectCallback::fromNameAndType(const std::string & scope, const std::string & type, const std::string & fullName, const std::function<void(si32)> & callback, bool optional)
  120. {
  121. assert(!scope.empty());
  122. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  123. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  124. if(!typeAndName.first.empty())
  125. {
  126. if (typeAndName.first != type)
  127. logMod->warn("Identifier '%s' from mod '%s' requested with different type! Type '%s' expected!", fullName, scope, type);
  128. else
  129. logMod->debug("Target type for identifier '%s' defined in mod '%s' is redundant!", fullName, scope);
  130. }
  131. if (scope == scopeAndFullName.first)
  132. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  133. ObjectCallback result;
  134. result.localScope = scope;
  135. result.remoteScope = scopeAndFullName.first;
  136. result.type = type;
  137. result.name = typeAndName.second;
  138. result.callback = callback;
  139. result.optional = optional;
  140. result.dynamicType = false;
  141. return result;
  142. }
  143. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback) const
  144. {
  145. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, false));
  146. }
  147. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback) const
  148. {
  149. requestIdentifier(ObjectCallback::fromNameWithType(scope, fullName, callback, false));
  150. }
  151. void CIdentifierStorage::requestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback) const
  152. {
  153. requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, false));
  154. }
  155. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback) const
  156. {
  157. requestIdentifier(ObjectCallback::fromNameWithType(name.meta, name.String(), callback, false));
  158. }
  159. void CIdentifierStorage::tryRequestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback) const
  160. {
  161. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, true));
  162. }
  163. void CIdentifierStorage::tryRequestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback) const
  164. {
  165. requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, true));
  166. }
  167. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent) const
  168. {
  169. assert(state != ELoadingState::LOADING);
  170. auto options = ObjectCallback::fromNameAndType(scope, type, name, std::function<void(si32)>(), silent);
  171. return getIdentifierImpl(options, silent);
  172. }
  173. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & type, const JsonNode & name, bool silent) const
  174. {
  175. assert(state != ELoadingState::LOADING);
  176. auto options = ObjectCallback::fromNameAndType(name.meta, type, name.String(), std::function<void(si32)>(), silent);
  177. return getIdentifierImpl(options, silent);
  178. }
  179. std::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent) const
  180. {
  181. assert(state != ELoadingState::LOADING);
  182. auto options = ObjectCallback::fromNameWithType(name.meta, name.String(), std::function<void(si32)>(), silent);
  183. return getIdentifierImpl(options, silent);
  184. }
  185. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & fullName, bool silent) const
  186. {
  187. assert(state != ELoadingState::LOADING);
  188. auto options = ObjectCallback::fromNameWithType(scope, fullName, std::function<void(si32)>(), silent);
  189. return getIdentifierImpl(options, silent);
  190. }
  191. std::optional<si32> CIdentifierStorage::getIdentifierImpl(const ObjectCallback & options, bool silent) const
  192. {
  193. auto idList = getPossibleIdentifiers(options);
  194. if (idList.size() == 1)
  195. return idList.front().id;
  196. if (!silent)
  197. showIdentifierResolutionErrorDetails(options);
  198. return std::optional<si32>();
  199. }
  200. void CIdentifierStorage::showIdentifierResolutionErrorDetails(const ObjectCallback & options) const
  201. {
  202. auto idList = getPossibleIdentifiers(options);
  203. logMod->error("Failed to resolve identifier '%s' of type '%s' from mod '%s'", options.name, options.type, options.localScope);
  204. if (options.dynamicType && options.type.empty())
  205. {
  206. bool suggestionFound = false;
  207. for (auto const & entry : registeredObjects)
  208. {
  209. if (!boost::algorithm::ends_with(entry.first, options.name))
  210. continue;
  211. suggestionFound = true;
  212. logMod->error("Perhaps you wanted to use identifier '%s' from mod '%s' instead?", entry.first, entry.second.scope);
  213. }
  214. if (suggestionFound)
  215. return;
  216. }
  217. if (idList.empty())
  218. {
  219. // check whether identifier is unavailable due to a missing dependency on a mod
  220. ObjectCallback testOptions = options;
  221. testOptions.localScope = ModScope::scopeGame();
  222. testOptions.remoteScope = {};
  223. auto testList = getPossibleIdentifiers(testOptions);
  224. if (testList.empty())
  225. {
  226. logMod->error("Identifier '%s' of type '%s' does not exists in any loaded mod!", options.name, options.type);
  227. }
  228. else
  229. {
  230. // such identifiers exists, but were not picked for some reason
  231. if (options.remoteScope.empty())
  232. {
  233. // attempt to access identifier from mods that is not dependency
  234. for (auto const & testOption : testList)
  235. {
  236. logMod->error("Identifier '%s' exists in mod %s", options.name, testOption.scope);
  237. logMod->error("Please add mod '%s' as dependency of mod '%s' to access this identifier", testOption.scope, options.localScope);
  238. }
  239. }
  240. else
  241. {
  242. // attempt to access identifier in form 'modName:object', but identifier is only present in different mod
  243. for (auto const & testOption : testList)
  244. {
  245. logMod->error("Identifier '%s' exists in mod '%s' but identifier was explicitly requested from mod '%s'!", options.name, testOption.scope, options.remoteScope);
  246. if (options.dynamicType)
  247. logMod->error("Please use form '%s.%s' or '%s:%s.%s' to access this identifier", options.type, options.name, testOption.scope, options.type, options.name);
  248. else
  249. logMod->error("Please use form '%s' or '%s:%s' to access this identifier", options.name, testOption.scope, options.name);
  250. }
  251. }
  252. }
  253. }
  254. else
  255. {
  256. logMod->error("Multiple possible candidates:");
  257. for (auto const & testOption : idList)
  258. {
  259. logMod->error("Identifier %s exists in mod %s", options.name, testOption.scope);
  260. if (options.dynamicType)
  261. logMod->error("Please use '%s:%s.%s' to access this identifier", testOption.scope, options.type, options.name);
  262. else
  263. logMod->error("Please use '%s:%s' to access this identifier", testOption.scope, options.name);
  264. }
  265. }
  266. }
  267. void CIdentifierStorage::registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier)
  268. {
  269. assert(state != ELoadingState::FINISHED);
  270. ObjectData data;
  271. data.scope = scope;
  272. data.id = identifier;
  273. std::string fullID = type + '.' + name;
  274. checkIdentifier(fullID);
  275. std::pair<const std::string, ObjectData> mapping = std::make_pair(fullID, data);
  276. if(!vstd::containsMapping(registeredObjects, mapping))
  277. {
  278. logMod->trace("registered %s as %s:%s", fullID, scope, identifier);
  279. registeredObjects.insert(mapping);
  280. }
  281. }
  282. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request) const
  283. {
  284. std::set<std::string> allowedScopes;
  285. bool isValidScope = true;
  286. // called have not specified destination mod explicitly
  287. if (request.remoteScope.empty())
  288. {
  289. // special scope that should have access to all in-game objects
  290. if (request.localScope == ModScope::scopeGame())
  291. {
  292. for(const auto & modName : VLC->modh->getActiveMods())
  293. allowedScopes.insert(modName);
  294. }
  295. // normally ID's from all required mods, own mod and virtual built-in mod are allowed
  296. else if(request.localScope != ModScope::scopeBuiltin() && !request.localScope.empty())
  297. {
  298. allowedScopes = VLC->modh->getModDependencies(request.localScope, isValidScope);
  299. if(!isValidScope)
  300. return std::vector<ObjectData>();
  301. allowedScopes.insert(request.localScope);
  302. }
  303. // all mods can access built-in mod
  304. allowedScopes.insert(ModScope::scopeBuiltin());
  305. }
  306. else
  307. {
  308. //if destination mod was specified explicitly, restrict lookup to this mod
  309. if(request.remoteScope == ModScope::scopeBuiltin() )
  310. {
  311. //built-in mod is an implicit dependency for all mods, allow access into it
  312. allowedScopes.insert(request.remoteScope);
  313. }
  314. else if ( request.localScope == ModScope::scopeGame() )
  315. {
  316. // allow access, this is special scope that should have access to all in-game objects
  317. allowedScopes.insert(request.remoteScope);
  318. }
  319. else if(request.remoteScope == request.localScope )
  320. {
  321. // allow self-access
  322. allowedScopes.insert(request.remoteScope);
  323. }
  324. else
  325. {
  326. // allow access only if mod is in our dependencies
  327. auto myDeps = VLC->modh->getModDependencies(request.localScope, isValidScope);
  328. if(!isValidScope)
  329. return std::vector<ObjectData>();
  330. if(myDeps.count(request.remoteScope))
  331. allowedScopes.insert(request.remoteScope);
  332. }
  333. }
  334. std::string fullID = request.type + '.' + request.name;
  335. auto entries = registeredObjects.equal_range(fullID);
  336. if (entries.first != entries.second)
  337. {
  338. std::vector<ObjectData> locatedIDs;
  339. for (auto it = entries.first; it != entries.second; it++)
  340. {
  341. if (vstd::contains(allowedScopes, it->second.scope))
  342. {
  343. locatedIDs.push_back(it->second);
  344. }
  345. }
  346. return locatedIDs;
  347. }
  348. return std::vector<ObjectData>();
  349. }
  350. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request) const
  351. {
  352. auto identifiers = getPossibleIdentifiers(request);
  353. if (identifiers.size() == 1) // normally resolved ID
  354. {
  355. request.callback(identifiers.front().id);
  356. return true;
  357. }
  358. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  359. {
  360. return true;
  361. }
  362. // error found. Try to generate some debug info
  363. showIdentifierResolutionErrorDetails(request);
  364. return false;
  365. }
  366. void CIdentifierStorage::finalize()
  367. {
  368. assert(state == ELoadingState::LOADING);
  369. state = ELoadingState::FINALIZING;
  370. while ( !scheduledRequests.empty() )
  371. {
  372. // Use local copy since new requests may appear during resolving, invalidating any iterators
  373. auto request = scheduledRequests.back();
  374. scheduledRequests.pop_back();
  375. resolveIdentifier(request);
  376. }
  377. state = ELoadingState::FINISHED;
  378. }
  379. void CIdentifierStorage::debugDumpIdentifiers()
  380. {
  381. logMod->trace("List of all registered objects:");
  382. std::map<std::string, std::vector<std::string>> objectList;
  383. for(const auto & object : registeredObjects)
  384. {
  385. size_t categoryLength = object.first.find('.');
  386. assert(categoryLength != std::string::npos);
  387. std::string objectCategory = object.first.substr(0, categoryLength);
  388. std::string objectName = object.first.substr(categoryLength + 1);
  389. objectList[objectCategory].push_back("[" + object.second.scope + "] " + objectName);
  390. }
  391. for(auto & category : objectList)
  392. boost::range::sort(category.second);
  393. for(const auto & category : objectList)
  394. {
  395. logMod->trace("");
  396. logMod->trace("### %s", category.first);
  397. logMod->trace("");
  398. for(const auto & entry : category.second)
  399. logMod->trace("- " + entry);
  400. }
  401. }
  402. VCMI_LIB_NAMESPACE_END