IdentifierStorage.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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);
  25. registerObject(ModScope::scopeBuiltin(), "spellSchool", "any", SpellSchool(ESpellSchool::ANY));
  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. }
  36. void CIdentifierStorage::checkIdentifier(std::string & ID)
  37. {
  38. if (boost::algorithm::ends_with(ID, "."))
  39. logMod->warn("BIG WARNING: identifier %s seems to be broken!", ID);
  40. else
  41. {
  42. size_t pos = 0;
  43. do
  44. {
  45. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  46. {
  47. logMod->warn("Warning: identifier %s is not in camelCase!", ID);
  48. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  49. }
  50. pos = ID.find('.', pos);
  51. }
  52. while(pos++ != std::string::npos);
  53. }
  54. }
  55. void CIdentifierStorage::requestIdentifier(ObjectCallback callback) const
  56. {
  57. checkIdentifier(callback.type);
  58. checkIdentifier(callback.name);
  59. assert(!callback.localScope.empty());
  60. if (state != ELoadingState::FINISHED) // enqueue request if loading is still in progress
  61. scheduledRequests.push_back(callback);
  62. else // execute immediately for "late" requests
  63. resolveIdentifier(callback);
  64. }
  65. CIdentifierStorage::ObjectCallback CIdentifierStorage::ObjectCallback::fromNameWithType(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback, bool optional)
  66. {
  67. assert(!scope.empty());
  68. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  69. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  70. if (scope == scopeAndFullName.first)
  71. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  72. ObjectCallback result;
  73. result.localScope = scope;
  74. result.remoteScope = scopeAndFullName.first;
  75. result.type = typeAndName.first;
  76. result.name = typeAndName.second;
  77. result.callback = callback;
  78. result.optional = optional;
  79. return result;
  80. }
  81. 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)
  82. {
  83. assert(!scope.empty());
  84. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  85. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  86. if(!typeAndName.first.empty())
  87. {
  88. if (typeAndName.first != type)
  89. logMod->error("Identifier '%s' from mod '%s' requested with different type! Type '%s' expected!", fullName, scope, type);
  90. else
  91. logMod->debug("Target type for identifier '%s' defined in mod '%s' is redundant!", fullName, scope);
  92. }
  93. if (scope == scopeAndFullName.first)
  94. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  95. ObjectCallback result;
  96. result.localScope = scope;
  97. result.remoteScope = scopeAndFullName.first;
  98. result.type = type;
  99. result.name = typeAndName.second;
  100. result.callback = callback;
  101. result.optional = optional;
  102. return result;
  103. }
  104. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback) const
  105. {
  106. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, false));
  107. }
  108. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback) const
  109. {
  110. requestIdentifier(ObjectCallback::fromNameWithType(scope, fullName, callback, false));
  111. }
  112. void CIdentifierStorage::requestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback) const
  113. {
  114. requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, false));
  115. }
  116. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback) const
  117. {
  118. requestIdentifier(ObjectCallback::fromNameWithType(name.meta, name.String(), callback, false));
  119. }
  120. void CIdentifierStorage::tryRequestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback) const
  121. {
  122. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, true));
  123. }
  124. void CIdentifierStorage::tryRequestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback) const
  125. {
  126. requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, true));
  127. }
  128. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent) const
  129. {
  130. assert(state != ELoadingState::LOADING);
  131. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(scope, type, name, std::function<void(si32)>(), silent));
  132. if (idList.size() == 1)
  133. return idList.front().id;
  134. if (!silent)
  135. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name , type ,scope);
  136. return std::optional<si32>();
  137. }
  138. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & type, const JsonNode & name, bool silent) const
  139. {
  140. assert(state != ELoadingState::LOADING);
  141. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(name.meta, type, name.String(), std::function<void(si32)>(), silent));
  142. if (idList.size() == 1)
  143. return idList.front().id;
  144. if (!silent)
  145. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), type, name.meta);
  146. return std::optional<si32>();
  147. }
  148. std::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent) const
  149. {
  150. assert(state != ELoadingState::LOADING);
  151. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(name.meta, name.String(), std::function<void(si32)>(), silent));
  152. if (idList.size() == 1)
  153. return idList.front().id;
  154. if (!silent)
  155. logMod->error("Failed to resolve identifier %s from mod %s", name.String(), name.meta);
  156. return std::optional<si32>();
  157. }
  158. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & fullName, bool silent) const
  159. {
  160. assert(state != ELoadingState::LOADING);
  161. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(scope, fullName, std::function<void(si32)>(), silent));
  162. if (idList.size() == 1)
  163. return idList.front().id;
  164. if (!silent)
  165. logMod->error("Failed to resolve identifier %s from mod %s", fullName, scope);
  166. return std::optional<si32>();
  167. }
  168. void CIdentifierStorage::registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier)
  169. {
  170. assert(state != ELoadingState::FINISHED);
  171. ObjectData data;
  172. data.scope = scope;
  173. data.id = identifier;
  174. std::string fullID = type + '.' + name;
  175. checkIdentifier(fullID);
  176. std::pair<const std::string, ObjectData> mapping = std::make_pair(fullID, data);
  177. if(!vstd::containsMapping(registeredObjects, mapping))
  178. {
  179. logMod->trace("registered %s as %s:%s", fullID, scope, identifier);
  180. registeredObjects.insert(mapping);
  181. }
  182. }
  183. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request) const
  184. {
  185. std::set<std::string> allowedScopes;
  186. bool isValidScope = true;
  187. // called have not specified destination mod explicitly
  188. if (request.remoteScope.empty())
  189. {
  190. // special scope that should have access to all in-game objects
  191. if (request.localScope == ModScope::scopeGame())
  192. {
  193. for(const auto & modName : VLC->modh->getActiveMods())
  194. allowedScopes.insert(modName);
  195. }
  196. // normally ID's from all required mods, own mod and virtual built-in mod are allowed
  197. else if(request.localScope != ModScope::scopeBuiltin() && !request.localScope.empty())
  198. {
  199. allowedScopes = VLC->modh->getModDependencies(request.localScope, isValidScope);
  200. if(!isValidScope)
  201. return std::vector<ObjectData>();
  202. allowedScopes.insert(request.localScope);
  203. }
  204. // all mods can access built-in mod
  205. allowedScopes.insert(ModScope::scopeBuiltin());
  206. }
  207. else
  208. {
  209. //if destination mod was specified explicitly, restrict lookup to this mod
  210. if(request.remoteScope == ModScope::scopeBuiltin() )
  211. {
  212. //built-in mod is an implicit dependency for all mods, allow access into it
  213. allowedScopes.insert(request.remoteScope);
  214. }
  215. else if ( request.localScope == ModScope::scopeGame() )
  216. {
  217. // allow access, this is special scope that should have access to all in-game objects
  218. allowedScopes.insert(request.remoteScope);
  219. }
  220. else if(request.remoteScope == request.localScope )
  221. {
  222. // allow self-access
  223. allowedScopes.insert(request.remoteScope);
  224. }
  225. else
  226. {
  227. // allow access only if mod is in our dependencies
  228. auto myDeps = VLC->modh->getModDependencies(request.localScope, isValidScope);
  229. if(!isValidScope)
  230. return std::vector<ObjectData>();
  231. if(myDeps.count(request.remoteScope))
  232. allowedScopes.insert(request.remoteScope);
  233. }
  234. }
  235. std::string fullID = request.type + '.' + request.name;
  236. auto entries = registeredObjects.equal_range(fullID);
  237. if (entries.first != entries.second)
  238. {
  239. std::vector<ObjectData> locatedIDs;
  240. for (auto it = entries.first; it != entries.second; it++)
  241. {
  242. if (vstd::contains(allowedScopes, it->second.scope))
  243. {
  244. locatedIDs.push_back(it->second);
  245. }
  246. }
  247. return locatedIDs;
  248. }
  249. return std::vector<ObjectData>();
  250. }
  251. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request) const
  252. {
  253. auto identifiers = getPossibleIdentifiers(request);
  254. if (identifiers.size() == 1) // normally resolved ID
  255. {
  256. request.callback(identifiers.front().id);
  257. return true;
  258. }
  259. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  260. {
  261. return true;
  262. }
  263. // error found. Try to generate some debug info
  264. if(identifiers.empty())
  265. logMod->error("Unknown identifier!");
  266. else
  267. logMod->error("Ambiguous identifier request!");
  268. logMod->error("Request for %s.%s from mod %s", request.type, request.name, request.localScope);
  269. for(const auto & id : identifiers)
  270. {
  271. logMod->error("\tID is available in mod %s", id.scope);
  272. }
  273. return false;
  274. }
  275. void CIdentifierStorage::finalize()
  276. {
  277. assert(state == ELoadingState::LOADING);
  278. state = ELoadingState::FINALIZING;
  279. bool errorsFound = false;
  280. while ( !scheduledRequests.empty() )
  281. {
  282. // Use local copy since new requests may appear during resolving, invalidating any iterators
  283. auto request = scheduledRequests.back();
  284. scheduledRequests.pop_back();
  285. if (!resolveIdentifier(request))
  286. errorsFound = true;
  287. }
  288. debugDumpIdentifiers();
  289. if (errorsFound)
  290. logMod->error("All known identifiers were dumped into log file");
  291. assert(errorsFound == false);
  292. state = ELoadingState::FINISHED;
  293. }
  294. void CIdentifierStorage::debugDumpIdentifiers()
  295. {
  296. logMod->trace("List of all registered objects:");
  297. std::map<std::string, std::vector<std::string>> objectList;
  298. for(const auto & object : registeredObjects)
  299. {
  300. size_t categoryLength = object.first.find('.');
  301. assert(categoryLength != std::string::npos);
  302. std::string objectCategory = object.first.substr(0, categoryLength);
  303. std::string objectName = object.first.substr(categoryLength + 1);
  304. objectList[objectCategory].push_back("[" + object.second.scope + "] " + objectName);
  305. }
  306. for(auto & category : objectList)
  307. boost::range::sort(category.second);
  308. for(const auto & category : objectList)
  309. {
  310. logMod->trace("");
  311. logMod->trace("### %s", category.first);
  312. logMod->trace("");
  313. for(const auto & entry : category.second)
  314. logMod->trace("- " + entry);
  315. }
  316. }
  317. VCMI_LIB_NAMESPACE_END