CObjectClassesHandler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 "../StringConstants.h"
  17. #include "../CGeneralTextHandler.h"
  18. #include "../CModHandler.h"
  19. #include "../JsonNode.h"
  20. #include "CRewardableConstructor.h"
  21. #include "CommonConstructors.h"
  22. #include "MapObjects.h"
  23. CObjectClassesHandler::CObjectClassesHandler()
  24. {
  25. #define SET_HANDLER_CLASS(STRING, CLASSNAME) handlerConstructors[STRING] = std::make_shared<CLASSNAME>;
  26. #define SET_HANDLER(STRING, TYPENAME) handlerConstructors[STRING] = std::make_shared<CDefaultObjectTypeHandler<TYPENAME>>
  27. // list of all known handlers, hardcoded for now since the only way to add new objects is via C++ code
  28. //Note: should be in sync with registerTypesMapObjectTypes function
  29. SET_HANDLER_CLASS("configurable", CRewardableConstructor);
  30. SET_HANDLER_CLASS("dwelling", CDwellingInstanceConstructor);
  31. SET_HANDLER_CLASS("hero", CHeroInstanceConstructor);
  32. SET_HANDLER_CLASS("town", CTownInstanceConstructor);
  33. SET_HANDLER_CLASS("bank", CBankInstanceConstructor);
  34. SET_HANDLER_CLASS("static", CObstacleConstructor);
  35. SET_HANDLER_CLASS("", CObstacleConstructor);
  36. SET_HANDLER("randomArtifact", CGArtifact);
  37. SET_HANDLER("randomHero", CGHeroInstance);
  38. SET_HANDLER("randomResource", CGResource);
  39. SET_HANDLER("randomTown", CGTownInstance);
  40. SET_HANDLER("randomMonster", CGCreature);
  41. SET_HANDLER("randomDwelling", CGDwelling);
  42. SET_HANDLER("generic", CGObjectInstance);
  43. SET_HANDLER("market", CGMarket);
  44. SET_HANDLER("cartographer", CCartographer);
  45. SET_HANDLER("artifact", CGArtifact);
  46. SET_HANDLER("blackMarket", CGBlackMarket);
  47. SET_HANDLER("boat", CGBoat);
  48. SET_HANDLER("bonusingObject", CGBonusingObject);
  49. SET_HANDLER("borderGate", CGBorderGate);
  50. SET_HANDLER("borderGuard", CGBorderGuard);
  51. SET_HANDLER("monster", CGCreature);
  52. SET_HANDLER("denOfThieves", CGDenOfthieves);
  53. SET_HANDLER("event", CGEvent);
  54. SET_HANDLER("garrison", CGGarrison);
  55. SET_HANDLER("heroPlaceholder", CGHeroPlaceholder);
  56. SET_HANDLER("keymaster", CGKeymasterTent);
  57. SET_HANDLER("lighthouse", CGLighthouse);
  58. SET_HANDLER("magi", CGMagi);
  59. SET_HANDLER("magicSpring", CGMagicSpring);
  60. SET_HANDLER("magicWell", CGMagicWell);
  61. SET_HANDLER("market", CGMarket);
  62. SET_HANDLER("mine", CGMine);
  63. SET_HANDLER("obelisk", CGObelisk);
  64. SET_HANDLER("observatory", CGObservatory);
  65. SET_HANDLER("onceVisitable", CGOnceVisitable);
  66. SET_HANDLER("pandora", CGPandoraBox);
  67. SET_HANDLER("pickable", CGPickable);
  68. SET_HANDLER("prison", CGHeroInstance);
  69. SET_HANDLER("questGuard", CGQuestGuard);
  70. SET_HANDLER("resource", CGResource);
  71. SET_HANDLER("scholar", CGScholar);
  72. SET_HANDLER("seerHut", CGSeerHut);
  73. SET_HANDLER("shipyard", CGShipyard);
  74. SET_HANDLER("shrine", CGShrine);
  75. SET_HANDLER("sign", CGSignBottle);
  76. SET_HANDLER("siren", CGSirens);
  77. SET_HANDLER("monolith", CGMonolith);
  78. SET_HANDLER("subterraneanGate", CGSubterraneanGate);
  79. SET_HANDLER("whirlpool", CGWhirlpool);
  80. SET_HANDLER("university", CGUniversity);
  81. SET_HANDLER("oncePerHero", CGVisitableOPH);
  82. SET_HANDLER("oncePerWeek", CGVisitableOPW);
  83. SET_HANDLER("witch", CGWitchHut);
  84. #undef SET_HANDLER_CLASS
  85. #undef SET_HANDLER
  86. }
  87. CObjectClassesHandler::~CObjectClassesHandler()
  88. {
  89. for(auto p : objects)
  90. delete p.second;
  91. }
  92. std::vector<JsonNode> CObjectClassesHandler::loadLegacyData(size_t dataSize)
  93. {
  94. CLegacyConfigParser parser("Data/Objects.txt");
  95. size_t totalNumber = parser.readNumber(); // first line contains number of objects to read and nothing else
  96. parser.endLine();
  97. for (size_t i=0; i<totalNumber; i++)
  98. {
  99. ObjectTemplate templ;
  100. templ.readTxt(parser);
  101. parser.endLine();
  102. std::pair<si32, si32> key(templ.id.num, templ.subid);
  103. legacyTemplates.insert(std::make_pair(key, templ));
  104. }
  105. std::vector<JsonNode> ret(dataSize);// create storage for 256 objects
  106. assert(dataSize == 256);
  107. CLegacyConfigParser namesParser("Data/ObjNames.txt");
  108. for (size_t i=0; i<256; i++)
  109. {
  110. ret[i]["name"].String() = namesParser.readString();
  111. namesParser.endLine();
  112. }
  113. CLegacyConfigParser cregen1Parser("data/crgen1");
  114. do
  115. customNames[Obj::CREATURE_GENERATOR1].push_back(cregen1Parser.readString());
  116. while(cregen1Parser.endLine());
  117. CLegacyConfigParser cregen4Parser("data/crgen4");
  118. do
  119. customNames[Obj::CREATURE_GENERATOR4].push_back(cregen4Parser.readString());
  120. while(cregen4Parser.endLine());
  121. return ret;
  122. }
  123. /// selects preferred ID (or subID) for new object
  124. template<typename Map>
  125. si32 selectNextID(const JsonNode & fixedID, const Map & map, si32 defaultID)
  126. {
  127. if (!fixedID.isNull() && fixedID.Float() < defaultID)
  128. return fixedID.Float(); // H3M object with fixed ID
  129. if (map.empty())
  130. return defaultID; // no objects loaded, keep gap for H3M objects
  131. if (map.rbegin()->first >= defaultID)
  132. return map.rbegin()->first + 1; // some modded objects loaded, return next available
  133. return defaultID; // some H3M objects loaded, first modded found
  134. }
  135. void CObjectClassesHandler::loadObjectEntry(const std::string & identifier, const JsonNode & entry, ObjectContainter * obj)
  136. {
  137. if (!handlerConstructors.count(obj->handlerName))
  138. {
  139. logGlobal->errorStream() << "Handler with name " << obj->handlerName << " was not found!";
  140. return;
  141. }
  142. std::string convertedId = VLC->modh->normalizeIdentifier(entry.meta, "core", identifier);
  143. si32 id = selectNextID(entry["index"], obj->subObjects, 1000);
  144. auto handler = handlerConstructors.at(obj->handlerName)();
  145. handler->setType(obj->id, id);
  146. handler->setTypeName(obj->identifier, convertedId);
  147. if (customNames.count(obj->id) && customNames.at(obj->id).size() > id)
  148. handler->init(entry, customNames.at(obj->id).at(id));
  149. else
  150. handler->init(entry);
  151. if (handler->getTemplates().empty())
  152. {
  153. auto range = legacyTemplates.equal_range(std::make_pair(obj->id, id));
  154. for (auto & templ : boost::make_iterator_range(range.first, range.second))
  155. {
  156. handler->addTemplate(templ.second);
  157. }
  158. legacyTemplates.erase(range.first, range.second);
  159. }
  160. logGlobal->debugStream() << "Loaded object " << obj->identifier << "(" << obj->id << ")" << ":" << convertedId << "(" << id << ")" ;
  161. assert(!obj->subObjects.count(id)); // DO NOT override
  162. obj->subObjects[id] = handler;
  163. obj->subIds[convertedId] = id;
  164. }
  165. CObjectClassesHandler::ObjectContainter * CObjectClassesHandler::loadFromJson(const JsonNode & json, const std::string & name)
  166. {
  167. auto obj = new ObjectContainter();
  168. obj->identifier = name;
  169. obj->name = json["name"].String();
  170. obj->handlerName = json["handler"].String();
  171. obj->base = json["base"];
  172. obj->id = selectNextID(json["index"], objects, 256);
  173. for (auto entry : json["types"].Struct())
  174. {
  175. loadObjectEntry(entry.first, entry.second, obj);
  176. }
  177. return obj;
  178. }
  179. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  180. {
  181. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  182. objects[object->id] = object;
  183. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  184. }
  185. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  186. {
  187. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  188. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  189. objects[index] = object;
  190. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  191. }
  192. void CObjectClassesHandler::loadSubObject(const std::string & identifier, JsonNode config, si32 ID, boost::optional<si32> subID)
  193. {
  194. config.setType(JsonNode::DATA_STRUCT); // ensure that input is not NULL
  195. assert(objects.count(ID));
  196. if (subID)
  197. {
  198. assert(objects.at(ID)->subObjects.count(subID.get()) == 0);
  199. assert(config["index"].isNull());
  200. config["index"].Float() = subID.get();
  201. }
  202. std::string oldMeta = config.meta; // FIXME: move into inheritNode?
  203. JsonUtils::inherit(config, objects.at(ID)->base);
  204. config.setMeta(oldMeta);
  205. loadObjectEntry(identifier, config, objects[ID]);
  206. }
  207. void CObjectClassesHandler::removeSubObject(si32 ID, si32 subID)
  208. {
  209. assert(objects.count(ID));
  210. assert(objects.at(ID)->subObjects.count(subID));
  211. objects.at(ID)->subObjects.erase(subID); //TODO: cleanup string id map
  212. }
  213. std::vector<bool> CObjectClassesHandler::getDefaultAllowed() const
  214. {
  215. return std::vector<bool>(); //TODO?
  216. }
  217. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(si32 type, si32 subtype) const
  218. {
  219. if (objects.count(type))
  220. {
  221. if (objects.at(type)->subObjects.count(subtype))
  222. return objects.at(type)->subObjects.at(subtype);
  223. }
  224. logGlobal->errorStream() << "Failed to find object of type " << type << ":" << subtype;
  225. throw std::runtime_error("Object type handler not found");
  226. }
  227. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(std::string type, std::string subtype) const
  228. {
  229. boost::optional<si32> id = VLC->modh->identifiers.getIdentifier("core", "object", type, false);
  230. if(id)
  231. {
  232. si32 subId = objects.at(id.get())->subIds.at(subtype);
  233. return objects.at(id.get())->subObjects.at(subId);
  234. }
  235. logGlobal->errorStream() << "Failed to find object of type " << type << ":" << subtype;
  236. throw std::runtime_error("Object type handler not found");
  237. }
  238. std::set<si32> CObjectClassesHandler::knownObjects() const
  239. {
  240. std::set<si32> ret;
  241. for (auto entry : objects)
  242. ret.insert(entry.first);
  243. return ret;
  244. }
  245. std::set<si32> CObjectClassesHandler::knownSubObjects(si32 primaryID) const
  246. {
  247. std::set<si32> ret;
  248. if (objects.count(primaryID))
  249. {
  250. for (auto entry : objects.at(primaryID)->subObjects)
  251. ret.insert(entry.first);
  252. }
  253. return ret;
  254. }
  255. void CObjectClassesHandler::beforeValidate(JsonNode & object)
  256. {
  257. for (auto & entry : object["types"].Struct())
  258. {
  259. JsonUtils::inherit(entry.second, object["base"]);
  260. for (auto & templ : entry.second["templates"].Struct())
  261. {
  262. JsonUtils::inherit(templ.second, entry.second["base"]);
  263. }
  264. }
  265. }
  266. void CObjectClassesHandler::afterLoadFinalization()
  267. {
  268. for (auto entry : objects)
  269. {
  270. for (auto obj : entry.second->subObjects)
  271. {
  272. obj.second->afterLoadFinalization();
  273. if (obj.second->getTemplates().empty())
  274. logGlobal->warnStream() << "No templates found for " << entry.first << ":" << obj.first;
  275. }
  276. }
  277. //duplicate existing two-way portals to make reserve for RMG
  278. auto& portalVec = objects[Obj::MONOLITH_TWO_WAY]->subObjects;
  279. size_t portalCount = portalVec.size();
  280. size_t currentIndex = portalCount;
  281. while (portalVec.size() < 100)
  282. {
  283. portalVec[currentIndex] = portalVec[currentIndex % portalCount];
  284. currentIndex++;
  285. }
  286. }
  287. std::string CObjectClassesHandler::getObjectName(si32 type) const
  288. {
  289. if (objects.count(type))
  290. return objects.at(type)->name;
  291. logGlobal->errorStream() << "Access to non existing object of type " << type;
  292. return "";
  293. }
  294. std::string CObjectClassesHandler::getObjectName(si32 type, si32 subtype) const
  295. {
  296. if (knownSubObjects(type).count(subtype))
  297. {
  298. auto name = getHandlerFor(type, subtype)->getCustomName();
  299. if (name)
  300. return name.get();
  301. }
  302. return getObjectName(type);
  303. }
  304. std::string CObjectClassesHandler::getObjectHandlerName(si32 type) const
  305. {
  306. return objects.at(type)->handlerName;
  307. }
  308. AObjectTypeHandler::AObjectTypeHandler():
  309. type(-1), subtype(-1)
  310. {
  311. }
  312. AObjectTypeHandler::~AObjectTypeHandler()
  313. {
  314. }
  315. void AObjectTypeHandler::setType(si32 type, si32 subtype)
  316. {
  317. this->type = type;
  318. this->subtype = subtype;
  319. }
  320. void AObjectTypeHandler::setTypeName(std::string type, std::string subtype)
  321. {
  322. this->typeName = type;
  323. this->subTypeName = subtype;
  324. }
  325. static ui32 loadJsonOrMax(const JsonNode & input)
  326. {
  327. if (input.isNull())
  328. return std::numeric_limits<ui32>::max();
  329. else
  330. return input.Float();
  331. }
  332. void AObjectTypeHandler::init(const JsonNode & input, boost::optional<std::string> name)
  333. {
  334. base = input["base"];
  335. if (!input["rmg"].isNull())
  336. {
  337. rmgInfo.value = input["rmg"]["value"].Float();
  338. rmgInfo.mapLimit = loadJsonOrMax(input["rmg"]["mapLimit"]);
  339. rmgInfo.zoneLimit = loadJsonOrMax(input["rmg"]["zoneLimit"]);
  340. rmgInfo.rarity = input["rmg"]["rarity"].Float();
  341. } // else block is not needed - set in constructor
  342. for (auto entry : input["templates"].Struct())
  343. {
  344. entry.second.setType(JsonNode::DATA_STRUCT);
  345. JsonUtils::inherit(entry.second, base);
  346. ObjectTemplate tmpl;
  347. tmpl.id = Obj(type);
  348. tmpl.subid = subtype;
  349. tmpl.stringID = entry.first; // FIXME: create "fullID" - type.object.template?
  350. tmpl.readJson(entry.second);
  351. templates.push_back(tmpl);
  352. }
  353. if (input["name"].isNull())
  354. objectName = name;
  355. else
  356. objectName.reset(input["name"].String());
  357. initTypeData(input);
  358. }
  359. bool AObjectTypeHandler::objectFilter(const CGObjectInstance *, const ObjectTemplate &) const
  360. {
  361. return false; // by default there are no overrides
  362. }
  363. void AObjectTypeHandler::preInitObject(CGObjectInstance * obj) const
  364. {
  365. obj->ID = Obj(type);
  366. obj->subID = subtype;
  367. obj->typeName = typeName;
  368. obj->subTypeName = subTypeName;
  369. }
  370. void AObjectTypeHandler::initTypeData(const JsonNode & input)
  371. {
  372. // empty implementation for overrides
  373. }
  374. boost::optional<std::string> AObjectTypeHandler::getCustomName() const
  375. {
  376. return objectName;
  377. }
  378. void AObjectTypeHandler::addTemplate(const ObjectTemplate & templ)
  379. {
  380. templates.push_back(templ);
  381. templates.back().id = Obj(type);
  382. templates.back().subid = subtype;
  383. }
  384. void AObjectTypeHandler::addTemplate(JsonNode config)
  385. {
  386. config.setType(JsonNode::DATA_STRUCT); // ensure that input is not null
  387. JsonUtils::inherit(config, base);
  388. ObjectTemplate tmpl;
  389. tmpl.id = Obj(type);
  390. tmpl.subid = subtype;
  391. tmpl.stringID = ""; // TODO?
  392. tmpl.readJson(config);
  393. templates.push_back(tmpl);
  394. }
  395. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates() const
  396. {
  397. return templates;
  398. }
  399. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates(si32 terrainType) const// FIXME: replace with ETerrainType
  400. {
  401. std::vector<ObjectTemplate> templates = getTemplates();
  402. std::vector<ObjectTemplate> filtered;
  403. std::copy_if(templates.begin(), templates.end(), std::back_inserter(filtered), [&](const ObjectTemplate & obj)
  404. {
  405. return obj.canBePlacedAt(ETerrainType(terrainType));
  406. });
  407. // H3 defines allowed terrains in a weird way - artifacts, monsters and resources have faulty masks here
  408. // Perhaps we should re-define faulty templates and remove this workaround (already done for resources)
  409. if (type == Obj::ARTIFACT || type == Obj::MONSTER)
  410. return templates;
  411. else
  412. return filtered;
  413. }
  414. boost::optional<ObjectTemplate> AObjectTypeHandler::getOverride(si32 terrainType, const CGObjectInstance * object) const
  415. {
  416. std::vector<ObjectTemplate> ret = getTemplates(terrainType);
  417. for (auto & tmpl : ret)
  418. {
  419. if (objectFilter(object, tmpl))
  420. return tmpl;
  421. }
  422. return boost::optional<ObjectTemplate>();
  423. }
  424. const RandomMapInfo & AObjectTypeHandler::getRMGInfo()
  425. {
  426. return rmgInfo;
  427. }
  428. bool AObjectTypeHandler::isStaticObject()
  429. {
  430. return false; // most of classes are not static
  431. }
  432. void AObjectTypeHandler::afterLoadFinalization()
  433. {
  434. }