CObjectClassesHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. /*
  2. * CObjectClassesHandler.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 "CObjectClassesHandler.h"
  12. #include "../filesystem/Filesystem.h"
  13. #include "../filesystem/CBinaryReader.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../GameConstants.h"
  16. #include "../constants/StringConstants.h"
  17. #include "../CGeneralTextHandler.h"
  18. #include "../GameSettings.h"
  19. #include "../JsonNode.h"
  20. #include "../CSoundBase.h"
  21. #include "../mapObjectConstructors/CBankInstanceConstructor.h"
  22. #include "../mapObjectConstructors/CRewardableConstructor.h"
  23. #include "../mapObjectConstructors/CommonConstructors.h"
  24. #include "../mapObjectConstructors/DwellingInstanceConstructor.h"
  25. #include "../mapObjectConstructors/HillFortInstanceConstructor.h"
  26. #include "../mapObjectConstructors/ShipyardInstanceConstructor.h"
  27. #include "../mapObjects/CGCreature.h"
  28. #include "../mapObjects/CGPandoraBox.h"
  29. #include "../mapObjects/CQuest.h"
  30. #include "../mapObjects/ObjectTemplate.h"
  31. #include "../mapObjects/CGMarket.h"
  32. #include "../mapObjects/MiscObjects.h"
  33. #include "../mapObjects/CGHeroInstance.h"
  34. #include "../mapObjects/CGTownInstance.h"
  35. #include "../modding/IdentifierStorage.h"
  36. #include "../modding/CModHandler.h"
  37. VCMI_LIB_NAMESPACE_BEGIN
  38. CObjectClassesHandler::CObjectClassesHandler()
  39. {
  40. #define SET_HANDLER_CLASS(STRING, CLASSNAME) handlerConstructors[STRING] = std::make_shared<CLASSNAME>;
  41. #define SET_HANDLER(STRING, TYPENAME) handlerConstructors[STRING] = std::make_shared<CDefaultObjectTypeHandler<TYPENAME>>
  42. // list of all known handlers, hardcoded for now since the only way to add new objects is via C++ code
  43. //Note: should be in sync with registerTypesMapObjectTypes function
  44. SET_HANDLER_CLASS("configurable", CRewardableConstructor);
  45. SET_HANDLER_CLASS("dwelling", DwellingInstanceConstructor);
  46. SET_HANDLER_CLASS("hero", CHeroInstanceConstructor);
  47. SET_HANDLER_CLASS("town", CTownInstanceConstructor);
  48. SET_HANDLER_CLASS("bank", CBankInstanceConstructor);
  49. SET_HANDLER_CLASS("boat", BoatInstanceConstructor);
  50. SET_HANDLER_CLASS("market", MarketInstanceConstructor);
  51. SET_HANDLER_CLASS("hillFort", HillFortInstanceConstructor);
  52. SET_HANDLER_CLASS("shipyard", ShipyardInstanceConstructor);
  53. SET_HANDLER_CLASS("monster", CreatureInstanceConstructor);
  54. SET_HANDLER_CLASS("resource", ResourceInstanceConstructor);
  55. SET_HANDLER_CLASS("static", CObstacleConstructor);
  56. SET_HANDLER_CLASS("", CObstacleConstructor);
  57. SET_HANDLER("randomArtifact", CGArtifact);
  58. SET_HANDLER("randomHero", CGHeroInstance);
  59. SET_HANDLER("randomResource", CGResource);
  60. SET_HANDLER("randomTown", CGTownInstance);
  61. SET_HANDLER("randomMonster", CGCreature);
  62. SET_HANDLER("randomDwelling", CGDwelling);
  63. SET_HANDLER("generic", CGObjectInstance);
  64. SET_HANDLER("artifact", CGArtifact);
  65. SET_HANDLER("borderGate", CGBorderGate);
  66. SET_HANDLER("borderGuard", CGBorderGuard);
  67. SET_HANDLER("denOfThieves", CGDenOfthieves);
  68. SET_HANDLER("event", CGEvent);
  69. SET_HANDLER("garrison", CGGarrison);
  70. SET_HANDLER("heroPlaceholder", CGHeroPlaceholder);
  71. SET_HANDLER("keymaster", CGKeymasterTent);
  72. SET_HANDLER("lighthouse", CGLighthouse);
  73. SET_HANDLER("magi", CGMagi);
  74. SET_HANDLER("mine", CGMine);
  75. SET_HANDLER("obelisk", CGObelisk);
  76. SET_HANDLER("pandora", CGPandoraBox);
  77. SET_HANDLER("prison", CGHeroInstance);
  78. SET_HANDLER("questGuard", CGQuestGuard);
  79. SET_HANDLER("seerHut", CGSeerHut);
  80. SET_HANDLER("sign", CGSignBottle);
  81. SET_HANDLER("siren", CGSirens);
  82. SET_HANDLER("monolith", CGMonolith);
  83. SET_HANDLER("subterraneanGate", CGSubterraneanGate);
  84. SET_HANDLER("whirlpool", CGWhirlpool);
  85. SET_HANDLER("terrain", CGTerrainPatch);
  86. #undef SET_HANDLER_CLASS
  87. #undef SET_HANDLER
  88. }
  89. CObjectClassesHandler::~CObjectClassesHandler()
  90. {
  91. for(auto * p : objects)
  92. delete p;
  93. }
  94. std::vector<JsonNode> CObjectClassesHandler::loadLegacyData()
  95. {
  96. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_OBJECT);
  97. CLegacyConfigParser parser(TextPath::builtin("Data/Objects.txt"));
  98. auto totalNumber = static_cast<size_t>(parser.readNumber()); // first line contains number of objects to read and nothing else
  99. parser.endLine();
  100. for (size_t i = 0; i < totalNumber; i++)
  101. {
  102. auto * tmpl = new ObjectTemplate;
  103. tmpl->readTxt(parser);
  104. parser.endLine();
  105. std::pair<si32, si32> key(tmpl->id.num, tmpl->subid);
  106. legacyTemplates.insert(std::make_pair(key, std::shared_ptr<const ObjectTemplate>(tmpl)));
  107. }
  108. objects.resize(256);
  109. std::vector<JsonNode> ret(dataSize);// create storage for 256 objects
  110. assert(dataSize == 256);
  111. CLegacyConfigParser namesParser(TextPath::builtin("Data/ObjNames.txt"));
  112. for (size_t i=0; i<256; i++)
  113. {
  114. ret[i]["name"].String() = namesParser.readString();
  115. namesParser.endLine();
  116. }
  117. JsonNode cregen1;
  118. JsonNode cregen4;
  119. CLegacyConfigParser cregen1Parser(TextPath::builtin("data/crgen1"));
  120. do
  121. {
  122. JsonNode subObject;
  123. subObject["name"].String() = cregen1Parser.readString();
  124. cregen1.Vector().push_back(subObject);
  125. }
  126. while(cregen1Parser.endLine());
  127. CLegacyConfigParser cregen4Parser(TextPath::builtin("data/crgen4"));
  128. do
  129. {
  130. JsonNode subObject;
  131. subObject["name"].String() = cregen4Parser.readString();
  132. cregen4.Vector().push_back(subObject);
  133. }
  134. while(cregen4Parser.endLine());
  135. ret[Obj::CREATURE_GENERATOR1]["subObjects"] = cregen1;
  136. ret[Obj::CREATURE_GENERATOR4]["subObjects"] = cregen4;
  137. ret[Obj::REFUGEE_CAMP]["subObjects"].Vector().push_back(ret[Obj::REFUGEE_CAMP]);
  138. ret[Obj::WAR_MACHINE_FACTORY]["subObjects"].Vector().push_back(ret[Obj::WAR_MACHINE_FACTORY]);
  139. return ret;
  140. }
  141. void CObjectClassesHandler::loadSubObject(const std::string & scope, const std::string & identifier, const JsonNode & entry, ObjectClass * obj)
  142. {
  143. auto object = loadSubObjectFromJson(scope, identifier, entry, obj, obj->objects.size());
  144. assert(object);
  145. obj->objects.push_back(object);
  146. registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype);
  147. for(const auto & compatID : entry["compatibilityIdentifiers"].Vector())
  148. registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype);
  149. }
  150. void CObjectClassesHandler::loadSubObject(const std::string & scope, const std::string & identifier, const JsonNode & entry, ObjectClass * obj, size_t index)
  151. {
  152. auto object = loadSubObjectFromJson(scope, identifier, entry, obj, index);
  153. assert(object);
  154. assert(obj->objects[index] == nullptr); // ensure that this id was not loaded before
  155. obj->objects[index] = object;
  156. registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype);
  157. for(const auto & compatID : entry["compatibilityIdentifiers"].Vector())
  158. registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype);
  159. }
  160. TObjectTypeHandler CObjectClassesHandler::loadSubObjectFromJson(const std::string & scope, const std::string & identifier, const JsonNode & entry, ObjectClass * obj, size_t index)
  161. {
  162. assert(identifier.find(':') == std::string::npos);
  163. assert(!scope.empty());
  164. std::string handler = obj->handlerName;
  165. if(!handlerConstructors.count(handler))
  166. {
  167. logMod->error("Handler with name %s was not found!", handler);
  168. // workaround for potential crash - if handler does not exists, continue with generic handler that is used for objects without any custom logc
  169. handler = "generic";
  170. assert(handlerConstructors.count(handler) != 0);
  171. }
  172. auto createdObject = handlerConstructors.at(handler)();
  173. createdObject->modScope = scope;
  174. createdObject->typeName = obj->identifier;;
  175. createdObject->subTypeName = identifier;
  176. createdObject->type = obj->id;
  177. createdObject->subtype = index;
  178. createdObject->init(entry);
  179. auto range = legacyTemplates.equal_range(std::make_pair(obj->id, index));
  180. for (auto & templ : boost::make_iterator_range(range.first, range.second))
  181. {
  182. createdObject->addTemplate(templ.second);
  183. }
  184. legacyTemplates.erase(range.first, range.second);
  185. logGlobal->debug("Loaded object %s(%d)::%s(%d)", obj->getJsonKey(), obj->id, identifier, index);
  186. return createdObject;
  187. }
  188. std::string ObjectClass::getJsonKey() const
  189. {
  190. return modScope + ':' + identifier;
  191. }
  192. std::string ObjectClass::getNameTextID() const
  193. {
  194. return TextIdentifier("object", modScope, identifier, "name").get();
  195. }
  196. std::string ObjectClass::getNameTranslated() const
  197. {
  198. return VLC->generaltexth->translate(getNameTextID());
  199. }
  200. ObjectClass * CObjectClassesHandler::loadFromJson(const std::string & scope, const JsonNode & json, const std::string & name, size_t index)
  201. {
  202. auto * obj = new ObjectClass();
  203. obj->modScope = scope;
  204. obj->identifier = name;
  205. obj->handlerName = json["handler"].String();
  206. obj->base = json["base"];
  207. obj->id = index;
  208. VLC->generaltexth->registerString(scope, obj->getNameTextID(), json["name"].String());
  209. obj->objects.resize(json["lastReservedIndex"].Float() + 1);
  210. for (auto subData : json["types"].Struct())
  211. {
  212. if (!subData.second["index"].isNull())
  213. {
  214. const std::string & subMeta = subData.second["index"].meta;
  215. if ( subMeta != "core")
  216. logMod->warn("Object %s:%s.%s - attempt to load object with preset index! This option is reserved for built-in mod", subMeta, name, subData.first );
  217. size_t subIndex = subData.second["index"].Integer();
  218. loadSubObject(subData.second.meta, subData.first, subData.second, obj, subIndex);
  219. }
  220. else
  221. loadSubObject(subData.second.meta, subData.first, subData.second, obj);
  222. }
  223. return obj;
  224. }
  225. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  226. {
  227. auto * object = loadFromJson(scope, data, name, objects.size());
  228. objects.push_back(object);
  229. VLC->identifiersHandler->registerObject(scope, "object", name, object->id);
  230. }
  231. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  232. {
  233. auto * object = loadFromJson(scope, data, name, index);
  234. assert(objects[(si32)index] == nullptr); // ensure that this id was not loaded before
  235. objects[static_cast<si32>(index)] = object;
  236. VLC->identifiersHandler->registerObject(scope, "object", name, object->id);
  237. }
  238. void CObjectClassesHandler::loadSubObject(const std::string & identifier, JsonNode config, MapObjectID ID, MapObjectSubID subID)
  239. {
  240. config.setType(JsonNode::JsonType::DATA_STRUCT); // ensure that input is not NULL
  241. assert(objects[ID]);
  242. if ( subID >= objects[ID]->objects.size())
  243. objects[ID]->objects.resize(subID+1);
  244. JsonUtils::inherit(config, objects.at(ID)->base);
  245. loadSubObject(config.meta, identifier, config, objects[ID], subID);
  246. }
  247. void CObjectClassesHandler::removeSubObject(MapObjectID ID, MapObjectSubID subID)
  248. {
  249. assert(objects[ID]);
  250. assert(subID < objects[ID]->objects.size());
  251. objects[ID]->objects[subID] = nullptr;
  252. }
  253. std::vector<bool> CObjectClassesHandler::getDefaultAllowed() const
  254. {
  255. return std::vector<bool>(); //TODO?
  256. }
  257. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(MapObjectID type, MapObjectSubID subtype) const
  258. {
  259. try
  260. {
  261. auto result = objects.at(type)->objects.at(subtype);
  262. if (result != nullptr)
  263. return result;
  264. }
  265. catch (std::out_of_range & e)
  266. {
  267. // Leave catch block silently
  268. }
  269. std::string errorString = "Failed to find object of type " + std::to_string(type) + "::" + std::to_string(subtype);
  270. logGlobal->error(errorString);
  271. throw std::runtime_error(errorString);
  272. }
  273. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(const std::string & scope, const std::string & type, const std::string & subtype) const
  274. {
  275. std::optional<si32> id = VLC->identifiers()->getIdentifier(scope, "object", type);
  276. if(id)
  277. {
  278. auto * object = objects[id.value()];
  279. std::optional<si32> subID = VLC->identifiers()->getIdentifier(scope, object->getJsonKey(), subtype);
  280. if (subID)
  281. return object->objects[subID.value()];
  282. }
  283. std::string errorString = "Failed to find object of type " + type + "::" + subtype;
  284. logGlobal->error(errorString);
  285. throw std::runtime_error(errorString);
  286. }
  287. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(CompoundMapObjectID compoundIdentifier) const
  288. {
  289. return getHandlerFor(compoundIdentifier.primaryID, compoundIdentifier.secondaryID);
  290. }
  291. std::set<MapObjectID> CObjectClassesHandler::knownObjects() const
  292. {
  293. std::set<MapObjectID> ret;
  294. for(auto * entry : objects)
  295. if (entry)
  296. ret.insert(entry->id);
  297. return ret;
  298. }
  299. std::set<MapObjectSubID> CObjectClassesHandler::knownSubObjects(MapObjectID primaryID) const
  300. {
  301. std::set<MapObjectSubID> ret;
  302. if (!objects.at(primaryID))
  303. {
  304. logGlobal->error("Failed to find object %d", primaryID);
  305. return ret;
  306. }
  307. for(const auto & entry : objects.at(primaryID)->objects)
  308. if (entry)
  309. ret.insert(entry->subtype);
  310. return ret;
  311. }
  312. void CObjectClassesHandler::beforeValidate(JsonNode & object)
  313. {
  314. for (auto & entry : object["types"].Struct())
  315. {
  316. if (object.Struct().count("subObjects"))
  317. {
  318. const auto & vector = object["subObjects"].Vector();
  319. if (entry.second.Struct().count("index"))
  320. {
  321. size_t index = entry.second["index"].Integer();
  322. if (index < vector.size())
  323. JsonUtils::inherit(entry.second, vector[index]);
  324. }
  325. }
  326. JsonUtils::inherit(entry.second, object["base"]);
  327. for (auto & templ : entry.second["templates"].Struct())
  328. JsonUtils::inherit(templ.second, entry.second["base"]);
  329. }
  330. object.Struct().erase("subObjects");
  331. }
  332. void CObjectClassesHandler::afterLoadFinalization()
  333. {
  334. for(auto * entry : objects)
  335. {
  336. if (!entry)
  337. continue;
  338. for(const auto & obj : entry->objects)
  339. {
  340. if (!obj)
  341. continue;
  342. obj->afterLoadFinalization();
  343. if(obj->getTemplates().empty())
  344. logGlobal->warn("No templates found for %s:%s", entry->getJsonKey(), obj->getJsonKey());
  345. }
  346. }
  347. generateExtraMonolithsForRMG();
  348. }
  349. void CObjectClassesHandler::generateExtraMonolithsForRMG()
  350. {
  351. //duplicate existing two-way portals to make reserve for RMG
  352. auto& portalVec = objects[Obj::MONOLITH_TWO_WAY]->objects;
  353. //FIXME: Monoliths in this vector can be already not useful for every terrain
  354. const size_t portalCount = portalVec.size();
  355. //Invalid portals will be skipped and portalVec size stays unchanged
  356. for (size_t i = portalCount; portalVec.size() < 100; ++i)
  357. {
  358. auto index = static_cast<si32>(i % portalCount);
  359. auto portal = portalVec[index];
  360. auto templates = portal->getTemplates();
  361. if (templates.empty() || !templates[0]->canBePlacedAtAnyTerrain())
  362. {
  363. continue; //Do not clone HoTA water-only portals or any others we can't use
  364. }
  365. //deep copy of noncopyable object :?
  366. auto newPortal = std::make_shared<CDefaultObjectTypeHandler<CGMonolith>>();
  367. newPortal->rmgInfo = portal->getRMGInfo();
  368. newPortal->base = portal->base; //not needed?
  369. newPortal->templates = portal->getTemplates();
  370. newPortal->sounds = portal->getSounds();
  371. newPortal->aiValue = portal->getAiValue();
  372. newPortal->battlefield = portal->battlefield; //getter is not initialized at this point
  373. newPortal->modScope = portal->modScope; //private
  374. newPortal->typeName = portal->getTypeName();
  375. newPortal->subTypeName = std::string("monolith") + std::to_string(portalVec.size());
  376. newPortal->type = portal->getIndex();
  377. newPortal->subtype = portalVec.size(); //indexes must be unique, they are returned as a set
  378. portalVec.push_back(newPortal);
  379. }
  380. }
  381. std::string CObjectClassesHandler::getObjectName(MapObjectID type, MapObjectSubID subtype) const
  382. {
  383. const auto handler = getHandlerFor(type, subtype);
  384. if (handler && handler->hasNameTextID())
  385. return handler->getNameTranslated();
  386. else
  387. return objects[type]->getNameTranslated();
  388. }
  389. SObjectSounds CObjectClassesHandler::getObjectSounds(MapObjectID type, MapObjectSubID subtype) const
  390. {
  391. // TODO: these objects may have subID's that does not have associated handler:
  392. // Prison: uses hero type as subID
  393. // Hero: uses hero type as subID, but registers hero classes as subtypes
  394. // Spell scroll: uses spell ID as subID
  395. if(type == Obj::PRISON || type == Obj::HERO || type == Obj::SPELL_SCROLL)
  396. subtype = 0;
  397. assert(objects[type]);
  398. assert(subtype < objects[type]->objects.size());
  399. return getHandlerFor(type, subtype)->getSounds();
  400. }
  401. std::string CObjectClassesHandler::getObjectHandlerName(MapObjectID type) const
  402. {
  403. return objects.at(type)->handlerName;
  404. }
  405. std::string CObjectClassesHandler::getJsonKey(MapObjectID type) const
  406. {
  407. return objects.at(type)->getJsonKey();
  408. }
  409. VCMI_LIB_NAMESPACE_END